pull/1/head
Michael_xu 4 years ago
parent 5313863618
commit 5782b6c665

@ -13,9 +13,7 @@
QQ群交流群⑩群[486745026](https:////shang.qq.com/wpa/qunwpa?idkey=f4687b809bf63f08f707aa1c56dee8dbcb9526237c429c4532222021d65bf83c)
赞赏一下吧~~
![](https://github.com/72crm/72crm/blob/master/ux/intro_img/g11.png)
Github下载地址[https://github.com/72wukong](https://github.com/72wukong)
悟空CRM采用全新的前后端分离模式本仓库代码中已集成前端vue打包后文件可免去打包操作
@ -35,13 +33,15 @@ QQ群交流群⑩群[486745026](https:////shang.qq.com/wpa/qunwpa?idkey=f4687
UI框架Element-UI 2.6.3
悟空crm11.0的运行环境要求PHP5.6以上
悟空crm11.0的运行环境要求PHP7.0以上
## 注意事项
:exclamation: :exclamation: :exclamation: v11.0.2版本开始cache类缓存方式由原file类型改为redis类型因此需要开启PHP Redis扩展必须确保已经安装了Redis服务以及PHP Redis驱动
:exclamation: :exclamation: :exclamation: 多公海功能需按照项目根目录下《多公海-执行客户回收的方法说明.docx》文件进行配置
## 一键安装
代码中已集成前端vue打包后文件可免去打包操作
@ -70,7 +70,7 @@ UI框架Element-UI 2.6.3
导入服务端根文件夹数据库文件public/sql/5kcrm.sql并修改config/database.php配置文件。
### 配置要求
PHP >= 5.6.0
PHP >= 7.0.*
当访问 http://localhost/, 出现“悟空软件”即代表后端接口搭建成功。
### 前端部署
安装node.js 前端部分是基于node.js上运行的所以必须先安装`node.js`版本要求为6.0以上

@ -203,4 +203,29 @@ function formatPubKey($pubKey) {
}
$fKey .= "-----END PUBLIC KEY-----";
return $fKey;
}
/**
* foreach循环内查询数据
* @param string $types
* @param $data
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/15 0015 14:39
*/
function foreachData($types='',$data)
{
switch ($types) {
case 'admin_structure' :
$res=Db::name('AdminUser')->where('id',$data)->value('realname');
break;
case '' :
$res=Db::name('AdminUser')->where('id',$data['id'])->update(['structure_id'=>$data['structure_id']]);
break;
case 'market':
$res=Db::name('MarketData')->whereIn('id',$data)->select();
break;
}
return $res;
}

@ -29,7 +29,7 @@ class ApiCommon extends Common
$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');
@ -52,7 +52,5 @@ class ApiCommon extends Common
session('user_id', $userInfo['id']);
// 更新缓存
Cache::set('Auth_'.$authKey, $cache, $loginExpire);
// cache('Auth_'.$authKey, $cache, $loginExpire, 'UserToken');
// $GLOBALS['userInfo'] = $userInfo;
}
}

@ -31,8 +31,52 @@ class Base extends Common
if (!$data) {
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()

@ -54,6 +54,8 @@ class ConfigSet extends ApiCommon
{
$configModel = model('Config');
$param = $this->param;
$userInfo=$this->userInfo;
$param['user_id']=$userInfo['id'];
if (!$param['id']) {
return resultArray(['error' => '参数错误']);
}

@ -24,7 +24,7 @@ class DailyRule extends ApiCommon
{
$action = [
'permission'=>[''],
'allow'=>['welcome', 'setwelcome', 'worklogrule', 'setworklogrule','scheduleList','addschedule','setschedule','delschedule']
'allow'=>['welcome', 'setwelcome', 'worklogrule', 'setworklogrule','schedulelist','addschedule','setschedule','delschedule']
];
Hook::listen('check_auth',$action);
$request = Request::instance();
@ -58,11 +58,12 @@ class DailyRule extends ApiCommon
public function setWelcome(DailyRuleLogic $dailyRuleLogic)
{
$mark = $this->param['welcome'];
$userInfo=$this->userInfo;
if (empty($mark)) return resultArray(['error' => '缺少日志欢迎语!']);
if (!$dailyRuleLogic->setWelcome($mark)) return resultArray(['error' => '添加失败!']);
# 系统操作日志
SystemActionLog($userInfo['id'], 'admin_oalog_rule','work_task','1','update','日志欢迎语' , '', '','设置了日志欢迎语');
return resultArray(['data' => '添加成功!']);
}
@ -93,9 +94,10 @@ class DailyRule extends ApiCommon
public function setWorkLogRule(DailyRuleLogic $dailyRuleLogic)
{
if (empty($this->param['rule'])) return resultArray(['error' => '缺少规则参数!']);
$userInfo=$this->userInfo;
$dailyRuleLogic->setWorkLogRule($this->param['rule']);
# 系统操作日志
SystemActionLog($userInfo['id'], 'admin_oalog_rule','work_task', 1, 'update','日志规则' , '', '','设置了日志规则');
return resultArray(['data' => '设置成功!']);
}
@ -120,8 +122,11 @@ class DailyRule extends ApiCommon
* @throws \think\exception\PDOException
*/
public function setSchedule(DailyRuleLogic $dailyRuleLogic){
$userInfo=$this->userInfo;
if(empty($this->param['id'])) return resultArray(['error'=>'缺少参数']);
$dailyRuleLogic->setSchedule($this->param);
# 系统操作日志
SystemActionLog($userInfo['id'], 'admin_oalog_rule','work_task', 1, 'update','日程类型' , '', '','设置了日程类型');
return resultArray(['data' => '设置成功!']);
}
@ -132,8 +137,11 @@ class DailyRule extends ApiCommon
* @return \think\response\Json
*/
public function addSchedule(DailyRuleLogic $dailyRuleLogic){
$userInfo=$this->userInfo;
if(empty($this->param['name'])) return resultArray(['error'=>'缺少参数']);
$dailyRuleLogic->addSchedule($this->param);
# 系统操作日志
SystemActionLog($userInfo['id'], 'admin_oalog_rule','work_task', 1, 'save','日程类型' , '', '','新增了日程类型');
return resultArray(['data' => '添加成功!']);
}
@ -144,8 +152,11 @@ class DailyRule extends ApiCommon
* @return \think\response\Json
*/
public function delSchedule(DailyRuleLogic $dailyRuleLogic){
$userInfo=$this->userInfo;
if(empty($this->param['id'])) return resultArray(['error'=>'缺少参数']);
$dailyRuleLogic->delSchedule($this->param['id']);
# 系统操作日志
SystemActionLog($userInfo['id'], 'admin_oalog_rule','work_task', 1, 'update','日程类型' , '', '','删除了日程类型');
return resultArray(['data' => '删除成功!']);
}

@ -82,6 +82,7 @@ class ExamineFlow extends ApiCommon
$param['structure_ids'] = arrayToString($param['structure_ids']);
$res = $examineFlowModel->createData($param);
$param['config'] = $param['config'] ? 1 : 0;
SystemActionLog($userInfo['id'], 'admin_examine','approval', $res['flow_id'], 'save', $param['name'], '', '','添加了审批流:'.$param['name']);
if ($res) {
$config = $param['config'];
if ((int)$config == 1) {
@ -94,6 +95,7 @@ class ExamineFlow extends ApiCommon
return resultArray(['error' => $examineStepModel->getError()]);
}
}
return resultArray(['data' => '添加成功']);
} else {
return resultArray(['error' => $examineFlowModel->getError()]);
@ -144,7 +146,8 @@ class ExamineFlow extends ApiCommon
$upData['delete_user_id'] = $userInfo['id'];
$upData['status'] = 0;
db('admin_examine_flow')->where(['flow_id' => $flowId])->update($upData);
# 添加系统操作日志
SystemActionLog($userInfo['id'], 'admin_examine','approval', $flowId, 'update', $param['name'], '', '','编辑了审批流:'.$param['name']);
$config = $param['config'];
if ((int)$config == 1) {
//固定审批流
@ -220,11 +223,15 @@ class ExamineFlow extends ApiCommon
public function delete()
{
$examineFlowModel = model('ExamineFlow');
$param = $this->param;
$param = $this->param;
$userInfo = $this->userInfo;
$data = $examineFlowModel->signDelById($param['flow_id']);
if (!$data) {
return resultArray(['error' => $examineFlowModel->getError()]);
}
# 系统操作日志
$newData = db('admin_examine_flow')->where(['flow_id' => $param['flow_id']])->find();
SystemActionLog($userInfo['id'], 'admin_examine','approval', $param['flow_id'], 'update', $newData['name'], '', '','删除了审批流:'.$newData['name']);
return resultArray(['data' => '删除成功']);
}
@ -238,12 +245,22 @@ class ExamineFlow extends ApiCommon
public function enables()
{
$examineFlowModel = model('ExamineFlow');
$param = $this->param;
$param = $this->param;
$userInfo=$this->userInfo;
$id = [$param['flow_id']];
$data = $examineFlowModel->enableDatas($id, $param['status']);
$data = $examineFlowModel->enableDatas($id, $param['status']);
# 系统操作日志
if (!$data) {
return resultArray(['error' => $examineFlowModel->getError()]);
}
}
if($param['status']==0){
$content='禁用了:';
}else{
$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' => '操作成功']);
}

@ -108,7 +108,7 @@ class Field extends ApiCommon
if ($this->param['types'] == 'oa_examine' && $this->param['types_id'] < 7) {
return resultArray(['error' => '系统审批类型暂不支持编辑']);
}
$userInfo=$this->userInfo;
$fieldModel = model('Field');
$param = $this->param;
@ -160,25 +160,37 @@ 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)) {
if (!$data = $fieldModel->updateDataById($updateParam, $types)) {
$errorMessage[] = $fieldModel->getError();
}
}
# 删除
if (!empty($delParam)) {
if (!$data = $fieldModel->delDataById($delParam)) {
if (!empty($fieldModel->getError())) $errorMessage[] = $fieldModel->getError();
if (!$data = $fieldModel->delDataById($delParam, $types)) {
$errorMessage[] = $fieldModel->getError();
}
}
@ -188,6 +200,27 @@ class Field extends ApiCommon
if ($errorMessage) {
return resultArray(['error' => $errorMessage]);
} else {
# 系统操作记录
$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($types !== 'oa_examine'){
$systemModules='customer';
}else{
$systemModules='approval';
}
SystemActionLog($userInfo['id'], $types,$systemModules, 1, 'update', $recordModules[$types], '','','编辑了自定义字段:'.$recordModules[$types]);
return resultArray(['data' => '修改成功']);
}
}
@ -227,6 +260,11 @@ 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']);
//读写权限
@ -342,6 +380,15 @@ class Field extends ApiCommon
$action_id = $param['action_id'] ? : '';
$data = $fieldModel->field($param, $dataInfo) ? : [];
# 回访模块下,负责人名称变更为回访人
if ($param['types'] == 'crm_visit') {
foreach ($data AS $key => $value) {
if ($value['field'] == 'owner_user_id') {
$data[$key]['name'] = '回访人';
break;
}
}
}
# 去掉客户模块下的成交信息
if ($param['types'] == 'crm_customer' && $param['action'] == 'read') {
foreach ($data AS $key => $value) {
@ -351,28 +398,18 @@ class Field extends ApiCommon
}
}
}
if ($param['types'] == 'crm_customer' && $param['action'] == 'index') {
# 合同回款 基本信息审核状态
if(in_array($param['types'], ['crm_receivables', 'crm_contract']) && $param['action'] == 'read'){
$check=['0'=>'待审核','1'=>'审核中','2'=>'审核通过','3'=>'审核未通过','4'=>'撤销','5'=>'草稿(未提交)','6'=>'作废'];
$data[] = [
'field' => 'pool_day',
'name' => '距进入公海天数',
'field' => 'check_status',
'name' => '审核状态',
'form_type' => 'text',
'writeStatus' => 0,
'fieldName' => 'pool_day'
];
}
# 客户锁定状态
if ($param['types'] == 'crm_customer' && $param['action'] == 'index') {
$data[] = [
'field' => "is_lock",
'fieldName' => "is_lock",
'form_type' => "text",
'name' => "锁定状态",
'width' => ""
'fieldName' => 'check_status',
'value' => $check[$dataInfo['check_status']],
];
}
# 合同自动编号设置
if ($param['types'] == 'crm_contract') {
foreach ($data AS $key => $value) {
@ -436,7 +473,7 @@ class Field extends ApiCommon
case 'crm_leads' :
$leadsModel = new Leads();
$leadsData = $leadsModel->getSystemInfo($action_id);
$leadsArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'follow_time' => '最后跟进时间'];
$leadsArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间'];
foreach ($leadsData AS $key => $value) {
if (empty($leadsArray[$key])) continue;
@ -453,7 +490,7 @@ class Field extends ApiCommon
case 'crm_customer' :
$customerModel = new Customer();
$customerData = $customerModel->getSystemInfo($action_id);
$customerArray = ['obtain_time' => '负责人获取客户时间', 'create_time' => '创建时间', 'update_time' => '更新时间', 'follow_time' => '最后跟进时间', 'follow_record' => '最后跟进记录', 'deal_status' => '成交状态'];
$customerArray = ['obtain_time' => '负责人获取客户时间', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间', 'last_record' => '最后跟进记录', 'deal_status' => '成交状态'];
foreach ($customerData AS $key => $value) {
if (empty($customerArray[$key])) continue;
@ -470,7 +507,7 @@ class Field extends ApiCommon
case 'crm_contacts' :
$contactsModel = new Contacts();
$contactsData = $contactsModel->getSystemInfo($action_id);
$contactsArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'follow_time' => '最后跟进时间'];
$contactsArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间'];
foreach ($contactsData AS $key => $value) {
if (empty($contactsArray[$key])) continue;
@ -487,7 +524,7 @@ class Field extends ApiCommon
case 'crm_business' :
$businessModel = new Business();
$businessData = $businessModel->getSystemInfo($action_id);
$businessArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'follow_time' => '最后跟进时间'];
$businessArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间'];
foreach ($businessData AS $key => $value) {
if (empty($businessArray[$key])) continue;
@ -504,7 +541,7 @@ class Field extends ApiCommon
case 'crm_contract' :
$contractModel = new Contract();
$contractData = $contractModel->getSystemInfo($action_id);
$contractArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'follow_time' => '最后跟进时间', 'done_money' => '已收款金额', 'un_money' => '未收款金额'];
$contractArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间', 'done_money' => '已收款金额', 'un_money' => '未收款金额'];
foreach ($contractData AS $key => $value) {
if (empty($contractArray[$key])) continue;
@ -521,7 +558,7 @@ class Field extends ApiCommon
case 'crm_receivables' :
$receivablesModel = new Receivables();
$receivablesData = $receivablesModel->getSystemInfo($action_id);
$receivablesArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
$receivablesArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
foreach ($receivablesData AS $key => $value) {
if (empty($receivablesArray[$key])) continue;
@ -538,7 +575,7 @@ class Field extends ApiCommon
case 'crm_product' :
$productModel = new Product();
$productData = $productModel->getSystemInfo($action_id);
$productArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
$productArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
foreach ($productData AS $key => $value) {
if (empty($productArray[$key])) continue;
@ -555,7 +592,7 @@ class Field extends ApiCommon
case 'crm_visit' :
$visitLogic = new VisitLogic();
$visitData = $visitLogic->getSystemInfo($action_id);
$visitArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
$visitArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
foreach ($visitData AS $key => $value) {
if (empty($visitArray[$key])) continue;
@ -572,7 +609,8 @@ class Field extends ApiCommon
}
}
$data = $fieldModel->resetField($param['types'], $data);
$data = $fieldModel->resetField($user_id, $param['types'], $param['action'], $data);
return resultArray(['data' => array_values($data)]);
}

@ -78,6 +78,7 @@ class Groups extends ApiCommon
*/
public function save(FieldGrantLogic $fieldGrantLogic)
{
$userInfo=$this->userInfo;
$groupModel = model('Group');
$param = $this->param;
$param['rules'] = arrayToString($param['rules']);
@ -85,7 +86,9 @@ class Groups extends ApiCommon
if (!$lastInsId) {
return resultArray(['error' => $groupModel->getError()]);
}
# 添加记录
SystemActionLog($userInfo['id'], 'admin_group','role', $lastInsId, 'save', $param['title'], '', '', '添加了角色:' . $param['title']);
# 新增客户管理角色的字段授权数据
if (isset($param['pid']) && $param['pid'] == 2) {
$fieldGrantLogic->createCrmFieldGrant($lastInsId);
@ -179,6 +182,7 @@ class Groups extends ApiCommon
{
$groupModel = model('Group');
$param = $this->param;
$userInfo = $this->userInfo;
$dataInfo = $groupModel->getDataById($param['id']);
if (!$dataInfo) {
return resultArray(['error' => '参数错误']);
@ -191,7 +195,9 @@ class Groups extends ApiCommon
if (!$data) {
return resultArray(['error' => $groupModel->getError()]);
}
# 添加记录
SystemActionLog($userInfo['id'], 'admin_group','role', $data, 'copy', $dataInfo['title'], '', '', '添加了角色:' . $dataInfo['title']);
# 复制客户管理角色的字段授权数据
if (!empty($dataInfo['pid']) && $dataInfo['pid'] == 2) {
$fieldGrantLogic->copyCrmFieldGrant($param['id'], $data);

@ -7,6 +7,7 @@
namespace app\admin\controller;
use app\crm\logic\CustomerPoolLogic;
use think\Hook;
use think\Request;
@ -42,6 +43,13 @@ class Index extends ApiCommon
public function fields()
{
$param = $this->param;
# 多公海高级筛选参数列表
if (!empty($param['types']) && $param['types'] == 'crm_customer_pool') {
$customerPoolLogic = new CustomerPoolLogic();
return resultArray(['data' => $customerPoolLogic->getAdvancedFilterFieldList()]);
}
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$fieldModel = model('Field');

@ -48,7 +48,6 @@ class Initialize extends ApiCommon
['type' => 4, 'name' => '日志'],
['type' => 5, 'name' => '项目管理'],
['type' => 6, 'name' => '日历'],
// ['type' => 7, 'name' => '知识库'],
];
return resultArray(['data' => $data]);
@ -65,6 +64,8 @@ class Initialize extends ApiCommon
*/
public function update(InitializeLogic $initializeLogic)
{
$userInfo = $this->userInfo;
if (empty($this->param['type']) || !is_array($this->param['type'])) return resultArray(['error' => '模块类型错误!']);
if (!empty($this->param['password']) && !$initializeLogic->verification($this->userInfo['id'], $this->param['password'])) {
@ -73,6 +74,9 @@ class Initialize extends ApiCommon
$initializeLogic->update($this->param['type']);
# 系统操作日志
SystemActionLog($userInfo['id'], 'admin_user','work_task', 1, 'update', '重置数据' , '', '','重置了数据');
return resultArray(['data' => $initializeLogic->log]);
}

@ -47,19 +47,34 @@ class Install extends Controller
*/
public function index()
{
$protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
if (strpos(request()->url(), "index.php") === false) {
$url = $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
header("Location:" . $url);
}
if (file_exists(CONF_PATH . "install.lock")) {
echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8'> <script>alert('请勿重复安装!');location.href='".$_SERVER["HTTP_HOST"]."';</script>";
echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8'> <script>alert('请勿重复安装!');location.href='".$protocol."://".$_SERVER["HTTP_HOST"]."';</script>";
die();
}
if (!file_exists(getcwd() . "/public/sql/5kcrm.sql")) {
echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8'> <script>alert('缺少必要的数据库文件!');location.href='".$_SERVER["HTTP_HOST"]."';</script>";
echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8'> <script>alert('缺少必要的数据库文件!');location.href='".$protocol."://".$_SERVER["HTTP_HOST"]."';</script>";
die();
}
return $this->fetch('index');
}
return $this->fetch('index');
}
public function step1()
{
if (strpos(request()->url(), "index.php") === false) {
$protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
$url = $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
header("Location:" . $url);
}
session('install_error',null);
$data = [];
$data['env'] = self::checkNnv();
@ -81,6 +96,11 @@ class Install extends Controller
echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8'> <script>alert('环境检测未通过,不能进行下一步操作!');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
die();
}
if (strpos(request()->url(), "index.php") === false) {
$protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
$url = $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
header("Location:" . $url);
}
$data['os'] = PHP_OS;
$data['php'] = phpversion();
$data['version'] = $this->version();
@ -352,13 +372,13 @@ INFO;
{
$items = [
'os' => ['操作系统', PHP_OS, '类Unix', 'ok'],
'php' => ['PHP版本', PHP_VERSION, '7.3 ( <em style="color: #888; font-size: 12px;">>= 5.6</em> )', 'ok','性能更佳'],
'php' => ['PHP版本', PHP_VERSION, '7.3 ( <em style="color: #888; font-size: 12px;">>= 7.0</em> )', 'ok','性能更佳'],
'gd' => ['gd', '开启', '开启', 'ok'],
'openssl' => ['openssl', '开启', '开启', 'ok'],
'pdo' => ['pdo', '开启', '开启', 'ok'],
];
session('install_error','');
if (substr($items['php'][1],0,3) < '5.6') {
if (substr($items['php'][1],0,3) < '7.0') {
$items['php'][3] = 'error';
session('install_error', true);
}

@ -24,7 +24,7 @@ class Log extends ApiCommon
{
$action = [
'permission' => [''],
'allow' => ['dataRecord', 'systemRecord', 'loginRecord']
'allow' => ['dataRecord', 'systemRecord', 'loginRecord','excelImport']
];
Hook::listen('check_auth',$action);
$request = Request::instance();
@ -45,6 +45,61 @@ class Log extends ApiCommon
*/
public function dataRecord(LogLogic $logLogic)
{
$this->param['startTime']= !empty($this->param['startTime'])?$this->param['startTime'].' 00:00:00':'';
$this->param['endTime']= !empty($this->param['endTime'])?$this->param['endTime'].' 23:59:59':'';
if(!empty($this->param['subModelLabels'])){
$this->param['modules']=$this->param['subModelLabels'];
}else{
switch ($this->param['model']){
case 'crm': //客户管理
$this->param['modules']=array(
'crm_leads' ,
'crm_customer',
'crm_pool' ,
'crm_contacts' ,
'crm_product' ,
'crm_business' ,
'crm_contract' ,
'crm_receivables' ,
'crm_visit' ,
'crm_invoice' ,
'crm_activity'
);
break;
case 'oa' : //办公管理
$this->param['modules']=array(
'oa_log' ,
'oa_event',
);
break;
case 'work' ://项目管理
$this->param['modules']=array(
'work_task' ,
'work',
);
break;
default :
$this->param['modules']=array(
'crm_leads' ,
'crm_customer',
'crm_pool' ,
'crm_contacts' ,
'crm_product' ,
'crm_business' ,
'crm_contract' ,
'crm_receivables' ,
'crm_visit' ,
'crm_invoice' ,
'crm_activity',
'oa_log' ,
'oa_event',
'work_task' ,
'work',
);
break;
}
}
$data['list'] = $logLogic->getRecordLogs($this->param);
$data['count'] = $logLogic->getRecordLogCount($this->param);
$data['modules'] = $logLogic->recordModules;
@ -63,6 +118,11 @@ class Log extends ApiCommon
*/
public function systemRecord(LogLogic $logLogic)
{
$this->param['startTime']= !empty($this->param['startTime'])?$this->param['startTime'].' 00:00:00':'';
$this->param['endTime']= !empty($this->param['endTime'])?$this->param['endTime'].' 23:59:59':'';
if(!empty($this->param['subModelLabels'])){
$this->param['modules']=$this->param['subModelLabels'];
}
$data['list'] = $logLogic->getSystemLogs($this->param);
$data['count'] = $logLogic->getSystemLogCount($this->param);
$data['modules'] = $logLogic->systemModules;
@ -79,8 +139,25 @@ class Log extends ApiCommon
*/
public function loginRecord(LogLogic $logLogic)
{
$this->param['startTime']= !empty($this->param['startTime'])?$this->param['startTime'].' 00:00:00':'';
$this->param['endTime']= !empty($this->param['endTime'])?$this->param['endTime'].' 23:59:59':'';
$data = $logLogic->getLoginRecord($this->param);
return resultArray(['data' => $data]);
}
/**
* 日志导出
*
* @param LogLogic $logLogic
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/8 0008 16:36
*/
public function excelImport()
{
$logLogic =new LogLogic;
$data = $logLogic->downExcel($this->param);
return $data;
}
}

@ -45,10 +45,7 @@ class Printing extends ApiCommon
*/
public function index(PrintingLogic $printingLogic)
{
$page = !empty($this->param['page']) ? $this->param['page'] : 1;
$limit = !empty($this->param['limit']) ? $this->param['limit'] : 15;
$data = $printingLogic->index($page, $limit);
$data = $printingLogic->index($this->param);
return resultArray(['data' => $data]);
}
@ -65,7 +62,6 @@ class Printing extends ApiCommon
if (empty($param['name'])) return resultArray(['error' => '缺少模板名称!']);
if (empty($param['type'])) return resultArray(['error' => '缺少模板类型!']);
if (empty($param['content'])) return resultArray(['error' => '缺少模板详情!']);
if (!$printingLogic->create($param)) return resultArray(['error' => '添加失败!']);
@ -103,8 +99,9 @@ class Printing extends ApiCommon
$param = $this->param;
if (empty($param['id'])) return resultArray(['error' => '缺少模板ID']);
if (isset($param['name']) && empty($param['name'])) return resultArray(['error' => '名称不能为空!']);
if (!$printingLogic->update($param)) return resultArray(['error' => '更新失败!']);
if ($printingLogic->update($param) === false) return resultArray(['error' => '更新失败!']);
return resultArray(['data' => '更新成功!']);
}
@ -159,7 +156,7 @@ class Printing extends ApiCommon
*/
public function field(PrintingLogic $printingLogic)
{
# 打印类型:1商机2合同3回款
# 打印类型:5商机6合同7回款
$type = !empty($this->param['type']) ? $this->param['type'] : 5;
$data = $printingLogic->getFields($type);

@ -8,6 +8,7 @@
namespace app\admin\controller;
use app\admin\controller\ApiCommon;
use app\admin\logic\PoolConfigLogic;
use think\Hook;
use think\Request;
@ -23,7 +24,7 @@ class Setting extends ApiCommon
{
$action = [
'permission'=>[''],
'allow'=>['']
'allow'=>['pool','setpool','readpool','changepool','deletepool','transferpool','customerlevel','poolfield']
];
Hook::listen('check_auth',$action);
$request = Request::instance();
@ -40,4 +41,139 @@ class Setting extends ApiCommon
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
}
/**
* 公海配置列表
*
* @param PoolConfigLogic $poolConfigLogic
* @author fanqi
* @since 2021-03-30
* @return \think\response\Json
*/
public function pool(PoolConfigLogic $poolConfigLogic)
{
$data = $poolConfigLogic->getPoolList($this->param);
return resultArray(['data' => $data]);
}
/**
* 设置公海规则
*
* @param
* @param PoolConfigLogic $poolConfigLogic 公海逻辑类
* @author fanqi
* @since 2021-03-29
* @return \think\response\Json
*/
public function setPool(PoolConfigLogic $poolConfigLogic)
{
$userInfo = $this->userInfo;
$param = $this->param;
$param['user_id'] = $userInfo['id'];
if ($poolConfigLogic->setPoolConfig($param) === false) return resultArray(['error' => $poolConfigLogic->error]);
return resultArray(['data' => '操作成功!']);
}
/**
* 公海配置详情
*
* @param PoolConfigLogic $poolConfigLogic
* @author fanqi
* @since 2021-03-30
* @return \think\response\Json
*/
public function readPool(PoolConfigLogic $poolConfigLogic)
{
$poolId = $this->param['pool_id'];
$data = $poolConfigLogic->readPool($poolId);
if ($data === false) return resultArray(['error' => $poolConfigLogic->error]);
return resultArray(['data' => $data]);
}
/**
* 变更公海配置状态
*
* @param PoolConfigLogic $poolConfigLogic
* @author fanqi
* @since 2021-03-30
* @return \think\response\Json
*/
public function changePool(PoolConfigLogic $poolConfigLogic)
{
if ($poolConfigLogic->changePoolStatus($this->param) === false) return resultArray(['error' => $poolConfigLogic->error]);
return resultArray(['data' => '操作成功!']);
}
/**
* 删除公海配置
*
* @param PoolConfigLogic $poolConfigLogic
* @author fanqi
* @since 2021-03-30
* @return \think\response\Json
*/
public function deletePool(PoolConfigLogic $poolConfigLogic)
{
$poolId = $this->param['pool_id'];
if ($poolConfigLogic->deletePool($poolId) === false) return resultArray(['error' => $poolConfigLogic->error]);
return resultArray(['data' => '操作成功!']);
}
/**
* 公海客户转移
*
* @param PoolConfigLogic $poolConfigLogic
* @author fanqi
* @since 2021-03-30
* @return \think\response\Json
*/
public function transferPool(PoolConfigLogic $poolConfigLogic)
{
$param = $this->param;
if ($poolConfigLogic->transferPool($param) === false) {
return resultArray(['error' => $poolConfigLogic->error]);
}
return resultArray(['data' => '操作成功!']);
}
/**
* 客户级别列表
*
* @param PoolConfigLogic $poolConfigLogic
* @author fanqi
* @since 2021-04-22
* @return \think\response\Json
*/
public function customerLevel(PoolConfigLogic $poolConfigLogic)
{
$data = $poolConfigLogic->getCustomerLevel();
return resultArray(['data' => $data]);
}
/**
* 公海字段
*
* @param PoolConfigLogic $poolConfigLogic
* @author fanqi
* @since 2021-04-29
* @return \think\response\Json
*/
public function poolField(PoolConfigLogic $poolConfigLogic)
{
$data = $poolConfigLogic->getPoolFieldList($this->param);
return resultArray(['data' => $data]);
}
}

@ -10,7 +10,7 @@ namespace app\admin\controller;
use think\Hook;
use think\Request;
use think\Db;
use app\admin\model\Structure;
class Structures extends ApiCommon
{
/**
@ -130,17 +130,25 @@ class Structures extends ApiCommon
if (!checkPerByAction('admin', 'users', 'structures_save')) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
}
$userInfo=$this->userInfo;
$structureModel = model('Structure');
$param = $this->param;
if(!$param['pid']){
resultArray(['error' => '请选择上级部门']);
}
$data = $structureModel->createData($param);
if (!$data) {
if(!$param['owner_user_id']){
resultArray(['error' => '请选择部门负责人']);
}
if ($structureModel->data($param)->allowField(true)->save()) {
$id = $structureModel->id;
# 添加记录
$content = '添加了部门:' . $param['name'];
SystemActionLog($userInfo['id'], 'admin_structure','structures', $id, 'save', $param['name'], '', '', $content);
return resultArray(['data' => '添加成功']);
}else{
return resultArray(['error' => $structureModel->getError()]);
}
return resultArray(['data' => '添加成功']);
}
}
/**
@ -155,7 +163,8 @@ class Structures extends ApiCommon
if (!checkPerByAction('admin', 'users', 'structures_update')) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
}
$userInfo=$this->userInfo;
$structureModel = model('Structure');
$param = $this->param;
$dataInfo = $structureModel->getDataByID($param['id']);
@ -165,7 +174,9 @@ class Structures extends ApiCommon
$data = $structureModel->updateDataById($param, $param['id']);
if (!$data) {
return resultArray(['error' => $structureModel->getError()]);
}
}
# 系统操作日志
SystemActionLog($userInfo['id'], 'admin_structure','structures', $param['id'], 'update', $param['name'], '', '','编辑了部门名称:'.$param['name']);
return resultArray(['data' => '编辑成功']);
}

@ -39,16 +39,23 @@ class System extends ApiCommon
public function save()
{
$param = $this->param;
$userInfo=$this->userInfo;
$field_name='';
$dataInfo=[];
if (isset($param['logo'])) {
$system_id=2;
$field_name='企业logo';
$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]);
}
if (isset($param['name'])) {
}elseif (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' => '操作成功!']);
}
}

@ -0,0 +1,122 @@
<?php
/**
* 更新sql包含安装
*
* @author fanqi
* @since 2021-05-08
*/
namespace app\admin\controller;
use think\Db;
use think\Exception;
class UpdateSql
{
/**
* 添加公海默认数据
*
* @author fanqi
* @since 2021-05-08
* @return bool
*/
static public function addPoolDefaultData()
{
# 员工ID
$userIds = db('admin_user')->column('id');
# 公海主数据
$poolData = [
'pool_name' => '系统默认公海',
'admin_user_ids' => ',1,',
'user_ids' => ','.implode(',', $userIds).',',
'department_ids' => '',
'status' => 1,
'before_owner_conf' => 0,
'before_owner_day' => 0,
'receive_conf' => 0,
'receive_count' => 0,
'remind_conf' => 0,
'remain_day' => 0,
'recycle_conf' => 1,
'create_user_id' => 1,
'create_time' => time()
];
# 公海规则数据
$poolRuleData = [
'pool_id' => 0,
'type' => 1,
'deal_handle' => 0,
'business_handle' => 0,
'level_conf' => 1,
'level' => json_encode([['level' => '所有客户', 'limit_day' => 30]]),
'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) {
$poolFieldData[] = [
'field_name' => $value['field'],
'name' => $value['name'],
'form_type' => $value['form_type'],
'is_hidden' => $value['is_hidden']
];
}
$poolFieldData[] = ['field_name' => 'address', 'name' => '省、市、区/县', 'form_type' => 'customer_address', 'is_hidden' => 0];
$poolFieldData[] = ['field_name' => 'detail_address', 'name' => '详细地址', 'form_type' => 'text', 'is_hidden' => 0];
$poolFieldData[] = ['field_name' => 'last_record', 'name' => '最后跟进记录', 'form_type' => 'text', 'is_hidden' => 0];
$poolFieldData[] = ['field_name' => 'last_time', 'name' => '最后跟进时间', 'form_type' => 'datetime', 'is_hidden' => 0];
$poolFieldData[] = ['field_name' => 'before_owner_user_id', 'name' => '前负责人', 'form_type' => 'user', 'is_hidden' => 0];
$poolFieldData[] = ['field_name' => 'into_pool_time', 'name' => '进入公海时间', 'form_type' => 'datetime', 'is_hidden' => 0];
$poolFieldData[] = ['field_name' => 'create_time', 'name' => '创建时间', 'form_type' => 'datetime', 'is_hidden' => 0];
$poolFieldData[] = ['field_name' => 'update_time', 'name' => '更新时间', 'form_type' => 'datetime', 'is_hidden' => 0];
$poolFieldData[] = ['field_name' => 'create_user_id', 'name' => '创建人', 'form_type' => 'user', 'is_hidden' => 0];
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;
});
Db::name('crm_customer_pool_field_setting')->insertAll($poolFieldData);
Db::commit();
return true;
} catch (Exception $e) {
Db::rollback();
return false;
}
}
/**
* 添加跟进记录的导入导出权限数据
*
* @author fanqi
* @since 2021-05-08
*/
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]);
}
if (!db('admin_rule')->where(['types' => 2, 'pid' => $activityPid, 'name' => 'excelExport'])->value('id')) {
db('admin_rule')->insert(['types' => 2, 'title' => '导出', 'name' => 'excelExport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]);
}
}
}

@ -18,15 +18,17 @@ use app\admin\model\User as UserModel;
use app\admin\logic\UserLogic;
use app\admin\model\Admin as AdminModel;
use app\crm\traits\StarTrait;
class Users extends ApiCommon
{
use StarTrait;
/**
* 用于判断权限
* @permission 无限制
* @allow 登录员工可访问
* @other 其他根据系统设置
**/
**/
public function _initialize()
{
$action = [
@ -52,38 +54,40 @@ class Users extends ApiCommon
'querylist',
'starlist',
'copyrole',
'subordinate'
'subordinate',
'countnumofuser',
'setuserdept'
]
];
Hook::listen('check_auth',$action);
Hook::listen('check_auth', $action);
$request = Request::instance();
$a = strtolower($request->action());
$a = strtolower($request->action());
if (!in_array($a, $action['permission'])) {
parent::_initialize();
}
}
}
/**
* 员工列表
* @param
* @param
* @return
*/
public function index()
{
{
$userModel = model('User');
$param = $this->param;
$param = $this->param;
$data = $userModel->getDataList($param);
return resultArray(['data' => $data]);
}
/**
* 员工详情
* @param
* @param
* @return
*/
public function read()
{
{
$userModel = model('User');
$param = $this->param;
$userInfo = $this->userInfo;
@ -92,30 +96,31 @@ class Users extends ApiCommon
if (!$data) {
return resultArray(['error' => $userModel->getError()]);
}
$data['serverUserInfo'] = $this->queryLoginUser();
$serverUserInfo = $this->queryLoginUser();
if (!empty($serverUserInfo)) $data['serverUserInfo'] = $serverUserInfo;
return resultArray(['data' => $data]);
}
/**
* 员工创建
* @param
* @param
* @return
*/
*/
public function save()
{
$userModel = model('User');
$param = $this->param;
$userInfo = $this->userInfo;
$userInfo = $this->userInfo;
$data = $userModel->createData($param);
if (!$data) {
return resultArray(['error' => $userModel->getError()]);
}
return resultArray(['data' => '添加成功']);
}
/**
* 员工编辑
* @param
* @param
* @return
*/
public function update()
@ -131,8 +136,8 @@ class Users extends ApiCommon
//权限判断
if (!checkPerByAction('admin', 'users', 'update')) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
}
unset($param['username']);
$data = $userModel->updateDataById($param, $param['id']);
@ -142,30 +147,30 @@ class Users extends ApiCommon
$param['userInfo'] = $userData;
$resSync = model('Sync')->syncData($param);
return resultArray(['data' => '编辑成功']);
}
//批量设置密码
public function updatePwd()
{
}
//批量设置密码
public function updatePwd()
{
//权限判断
if (!checkPerByAction('admin', 'users', 'update')) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
$param = $this->param;
if ($param['password'] && is_array($param['id'])) {
$userModel = model('User');
$ret = $userModel->updatePwdById($param);
if ($ret) {
return resultArray(['data'=>true]);
} else {
return resultArray(['error'=>$userModel->getError()]);
}
} else {
return resultArray(['error'=>'参数错误']);
}
}
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$param = $this->param;
if ($param['password'] && is_array($param['id'])) {
$userModel = model('User');
$ret = $userModel->updatePwdById($param);
if ($ret) {
return resultArray(['data' => true]);
} else {
return resultArray(['error' => $userModel->getError()]);
}
} else {
return resultArray(['error' => '参数错误']);
}
}
/**
* 员工状态
* @param status 0禁用,1启用,2禁止登陆,3未激活
@ -181,102 +186,114 @@ class Users extends ApiCommon
$ids = $param['id'];
}
//顶级管理员不能修改
foreach ($ids as $k=>$v) {
foreach ($ids as $k => $v) {
if ((int)$v == 1 && $param['status'] == '0') {
unset($ids[$k]);
}
}
$data = $userModel->enableDatas($ids, $param['status']);
$data = $userModel->enableDatas($ids, $param['status']);
if (!$data) {
return resultArray(['error' => $userModel->getError()]);
}
return resultArray(['data' => '操作成功']);
}
# 添加记录
if ($param['status'] == 0) {
$content = '禁用了:';
} elseif ($param['status'] == 1) {
$content = '激活了:';
}
$user = new ApiCommon();
$userInfo = $user->userInfo;
foreach ($ids as $key => $val) {
$dataInfo = db('admin_user')->where('id', $val)->find();
SystemActionLog($userInfo['id'], 'admin_user', 'employee', $val, 'update', '员工状态', '', '', $content . $dataInfo['realname']);
}
return resultArray(['data' => '操作成功']);
}
/**
* 获取权限范围内的员工数组
* @param
* @param
* @return
*/
public function getUserList()
{
$userModel = model('User');
$param = $this->param;
$by = $param['by'] ? : '';
$user_id = $param['user_id'] ? : '';
$by = $param['by'] ?: '';
$user_id = $param['user_id'] ?: '';
$where = [];
$belowIds = [];
if ($param['m'] && $param['c'] && $param['a']) {
if ($param['m'] == 'oa' && $param['c'] == 'task') {
$belowIds = getSubUserId(true, 1);
$belowIds = getSubUserId(true, 1);
} else {
$belowIds = $userModel->getUserByPer($param['m'], $param['c'], $param['a']);
}
$where['user.id'] = ['in',$belowIds];
$where['user.id'] = ['in', $belowIds];
} else {
if ($by == 'sub') {
$userInfo = $this->userInfo;
$adminIds = $userModel->getAdminId();
if (in_array($userInfo['id'],$adminIds)) {
if (in_array($userInfo['id'], $adminIds)) {
$belowIds = getSubUserId(true, 1);
} else {
//下属id
$belowIds = getSubUserId();
}
$where['user.id'] = ['in',$belowIds];
}
$where['user.id'] = ['in', $belowIds];
} elseif ($by == 'parent') {
if ($user_id == 1) {
$where['user.id'] = 0;
} else {
$unUserId[] = $user_id;
$subUserId = getSubUser($user_id);
$unUserId = $subUserId ? array_merge($subUserId,$unUserId) : $unUserId;
$unUserId = $subUserId ? array_merge($subUserId, $unUserId) : $unUserId;
}
$where['user.id'] = ['not in',$unUserId];
$where['user.id'] = ['not in', $unUserId];
} else {
$belowIds = getSubUserId(true, 1);
$where['user.id'] = ['in',$belowIds];
$where['user.id'] = ['in', $belowIds];
}
}
$userList = db('admin_user')
->alias('user')
->where($where)
->where('user.status>0 and user.type=1')
->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
->field('user.id,user.realname,user.thumb_img,structure.name as s_name')
->select();
->alias('user')
->where($where)
->where('user.status>0 and user.type=1')
->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
->field('user.id,user.realname,user.thumb_img,structure.name as s_name')
->select();
# 角色数据
$groupList = db('admin_access')->alias('access')
->join('__ADMIN_GROUP__ group', 'group.id = access.group_id', 'LEFT')
->field('group.id, group.title, access.user_id')->select();
->join('__ADMIN_GROUP__ group', 'group.id = access.group_id', 'LEFT')
->field('group.id, group.title, access.user_id')->select();
$groupArray = [];
foreach ($groupList AS $key => $value) {
foreach ($groupList as $key => $value) {
$groupArray[$value['user_id']]['roleId'][] = $value['id'];
$groupArray[$value['user_id']]['roleName'][] = $value['title'];
}
foreach ($userList as $k=>$v) {
$userList[$k]['username'] = $v['realname'];
foreach ($userList as $k => $v) {
$userList[$k]['username'] = $v['realname'];
$userList[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
# 员工新增角色ID和角色名称字段
$userList[$k]['roleId'] = !empty($groupArray[$v['id']]['roleId']) ? implode(',', $groupArray[$v['id']]['roleId']) : '';
$userList[$k]['roleName'] = !empty($groupArray[$v['id']]['roleName']) ? implode(',', $groupArray[$v['id']]['roleName']) : '';
$userList[$k]['roleId'] = !empty($groupArray[$v['id']]['roleId']) ? implode(',', $groupArray[$v['id']]['roleId']) : '';
$userList[$k]['roleName'] = !empty($groupArray[$v['id']]['roleName']) ? implode(',', $groupArray[$v['id']]['roleName']) : '';
# 单独处理admin管理员的角色ID和角色名称字段
if ($v['id'] == 1 && (empty($groupArray[$v['id']]['roleId']) || empty($groupArray[$v['id']]['roleName']))) {
$userList[$k]['roleId'] = '1';
$userList[$k]['roleId'] = '1';
$userList[$k]['roleName'] = '超级管理员角色';
}
}
return resultArray(['data' => $userList ? : []]);
return resultArray(['data' => $userList ?: []]);
}
/**
* 修改头像
* @param
* @param
* @return
*/
*/
public function updateImg()
{
$fileModel = model('File');
@ -285,41 +302,41 @@ class Users extends ApiCommon
//处理图片
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$param['file'] = request()->file('file');
$resImg = $fileModel->updateByField($param['file'], 'User', $param['id'], 'img', 'thumb_img', 150, 150);
if (!$resImg) {
return resultArray(['error' => $fileModel->getError()]);
}
return resultArray(['data' => '上传成功']);
}
/**
* 重置密码
* @param
* @param
* @return
*/
*/
public function resetPassword()
{
{
$param = $this->param;
$userInfo = $this->userInfo;
$userModel = model('User');
if (empty($param['new_pwd']) || empty($param['old_pwd'])) return resultArray(['error' => '密码不能为空!']);
if ($param['id'] && (int)$param['id'] !== $userInfo['id']) {
//权限判断
if (!checkPerByAction('admin', 'users', 'update')) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$user_id = $param['id'];
if (!$param['new_pwd']) {
$this->error = '请输入重置密码';
return false;
}
$userInfo = $userModel->getDataById($user_id);
if (user_md5($param['new_pwd'], $userInfo['salt'], $userInfo['username']) == $userInfo['password']) {
$this->error = '密码没改变';
@ -331,11 +348,13 @@ class Users extends ApiCommon
$syncData['user_id'] = $userInfo['id'];
$syncData['salt'] = $userInfo['salt'];
$syncData['password'] = user_md5($param['new_pwd'], $userInfo['salt'], $userInfo['username']);
$resSync = $syncModel->syncData($syncData);
$resSync = $syncModel->syncData($syncData);
# 添加记录
SystemActionLog($userInfo['id'], 'admin_user', 'employee', $userInfo['id'], 'update', $userInfo['realname'], '', '', '重置了密码:' . $userInfo['realname']);
return resultArray(['data' => '密码重置成功']);
} else {
return resultArray(['error' => '密码重置失败,请重试']);
}
}
} else {
$userModel = model('User');
$old_pwd = $param['old_pwd'];
@ -343,14 +362,14 @@ class Users extends ApiCommon
$data = $userModel->updatePaw($userInfo, $old_pwd, $new_pwd);
if (!$data) {
return resultArray(['error' => $userModel->getError()]);
}
return resultArray(['data' => $data]);
}
return resultArray(['data' => $data]);
}
}
/**
* 员工角色关系
* @param
* @param
* @return
*/
public function groups()
@ -358,8 +377,8 @@ class Users extends ApiCommon
//权限判断
if (!checkPerByAction('admin', 'groups', 'update')) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$param = $this->param;
if (!$param['users'] && !$param['structures']) {
return resultArray(['error' => '请选择员工']);
@ -373,7 +392,7 @@ class Users extends ApiCommon
if (is_array($param['structures'])) {
foreach ($param['structures'] as $v) {
$userArr[] = $userModel->getSubUserByStr($v);
}
}
}
if ($userArr) $userArr = call_user_func_array('array_merge', $userArr); //数组合并
if ($userArr && $param['users']) {
@ -385,24 +404,29 @@ class Users extends ApiCommon
}
$userIds = array_unique($userIds);
$groups = $param['groups'];
$accessModel = model('Access');
$accessModel = model('Access');
$resData = true;
foreach ($userIds as $k=>$v) {
$user_id = $this->userInfo;
foreach ($userIds as $k => $v) {
//角色员工关系处理
$res = $accessModel->userGroup($v, $param['groups']);
if (!$res) {
$resData = false;
}
}
$userInfo = Db::name('admin_user')->where('id', $v)->find();
$user_id=$this->userInfo;
SystemActionLog($user_id['id'], 'admin_user', 'employee', $v, 'update', $userInfo['realname'], '', '', '员工关联了角色:' . $userInfo['realname']);
}
// if ($resData == false) {
// return resultArray(['error' => '操作失败,请重试']);
// }
return resultArray(['data' => '创建成功']);
return resultArray(['data' => '创建成功']);
}
/**
* 员工角色关系(删除)
* @param
* @param
* @return
*/
public function groupsDel()
@ -410,8 +434,8 @@ class Users extends ApiCommon
//权限判断
if (!checkPerByAction('admin', 'groups', 'update')) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$param = $this->param;
if (!$param['user_id']) {
return resultArray(['error' => '请选择员工']);
@ -419,69 +443,70 @@ class Users extends ApiCommon
if (!$param['group_id']) {
return resultArray(['error' => '参数错误']);
}
# 员工至少保留一个角色
$count = db('admin_access')->where(['user_id' => $param['user_id']])->count();
if ($count == 1) return resultArray(['error' => '员工至少保留一个角色!']);
$res = db('admin_access')->where(['user_id' => $param['user_id'],'group_id' => $param['group_id']])->delete();
$res = db('admin_access')->where(['user_id' => $param['user_id'], 'group_id' => $param['group_id']])->delete();
if (!$res) {
return resultArray(['error' => '操作失败,请重试']);
return resultArray(['error' => '操作失败,请重试']);
}
return resultArray(['data' => '删除成功']);
return resultArray(['data' => '删除成功']);
}
/**
* [structureUserList 部门员工混合数据]
* @param
* @param
* @return
*/
*/
public function structureUserList()
{
$structure_list = db('admin_structure')->select();
$structureList = getSubObj(0, $structure_list, '', 1);
foreach ($structureList as $k=>$v) {
foreach ($structureList as $k => $v) {
$userList = [];
$userList = db('admin_user')->where(['structure_id' => $v['id'],'status' => array('in',['1','3'])])->field('id,realname')->select();
$userList = db('admin_user')->where(['structure_id' => $v['id'], 'status' => array('in', ['1', '3'])])->field('id,realname')->select();
$structureList[$k]['userList'] = $userList;
}
return $structureList;
}
//人资员工导入
public function tobeusers(){
$userModel = model('User');
$param = $this->param;
$flag = $userModel->beusers($param);
if ($flag) {
return resultArray(['data'=>$flag]);
} else {
return resultArray(['error'=>$userModel->getError()]);
}
}
//根据部门ID获取员工列表
public function userListByStructId()
{
$usermodel = model('User');
$param = $this->param;
$structure_id = $param['structure_id']?:'';
$ret = $usermodel->getUserListByStructureId($structure_id) ? : [];
return resultArray(['data'=>$ret]);
}
}
//人资员工导入
public function tobeusers()
{
$userModel = model('User');
$param = $this->param;
$flag = $userModel->beusers($param);
if ($flag) {
return resultArray(['data' => $flag]);
} else {
return resultArray(['error' => $userModel->getError()]);
}
}
//根据部门ID获取员工列表
public function userListByStructId()
{
$usermodel = model('User');
$param = $this->param;
$structure_id = $param['structure_id'] ?: '';
$ret = $usermodel->getUserListByStructureId($structure_id) ?: [];
return resultArray(['data' => $ret]);
}
/**
* 员工账号修改
* @param
* @param
* @return
*/
*/
public function usernameEdit()
{
//权限判断
if (!checkPerByAction('admin', 'users', 'update')) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$param = $this->param;
$userInfo = $this->userInfo;
//权限判断
@ -489,17 +514,17 @@ class Users extends ApiCommon
return resultArray(['error' => '管理员账号暂不能修改']);
}
$adminTypes = adminGroupTypes($userInfo['id']);
if (!in_array(3,$adminTypes) && !in_array(1,$adminTypes) && !in_array(2,$adminTypes)) {
if (!in_array(3, $adminTypes) && !in_array(1, $adminTypes) && !in_array(2, $adminTypes)) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
if (!$param['id'] || !$param['username'] || !$param['password']) {
return resultArray(['error' => '参数错误!']);
}
if (db('admin_user')->where(['id' => ['neq',$param['id']],'username' => $param['username']])->find()) {
if (db('admin_user')->where(['id' => ['neq', $param['id']], 'username' => $param['username']])->find()) {
return resultArray(['error' => '手机号码已存在!']);
}
$userData = db('admin_user')->where(['id' => $param['id']])->field('username,salt,password')->find();
$userData = db('admin_user')->where(['id' => $param['id']])->field('username,salt,password,realname')->find();
$data = [];
$data['username'] = $param['username'];
$data['password'] = user_md5($param['password'], $userData['salt'], $param['username']);
@ -509,12 +534,13 @@ class Users extends ApiCommon
if ($resSync) {
unset($data['userInfo']);
$res = db('admin_user')->where(['id' => $param['id']])->update($data);
SystemActionLog($userInfo['id'], 'admin_user', 'employee', $param['id'], 'update', $userData['realname'], '', '', '员工账号修改:' . $userData['realname']);
return resultArray(['data' => '修改成功!']);
} else {
return resultArray(['error' => '修改失败,请重试!']);
}
}
/**
* 登录记录
*/
@ -524,12 +550,12 @@ class Users extends ApiCommon
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$loginRecordModel = new LoginRecord();
$where = [];
getWhereUserByParam($where, 'create_user_id');
getWhereTimeByParam($where, 'create_time');
$limit = $this->param['limit'] ?: 15;
$data = $loginRecordModel
->where($where)
@ -547,24 +573,24 @@ class Users extends ApiCommon
],
]);
}
/**
* 员工导入模板下载
* @author Michael_xu
* @param string $save_path 本地保存路径 用于错误数据导出,在 Admin\Model\Excel::batchImportData()调用
* @return
* @author Michael_xu
*/
public function excelDownload($save_path = '')
{
$param = $this->param;
$userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel();
// 导出的字段列表
$field_list = UserModel::$import_field_list;
$excelModel->excelImportDownload($field_list, 'admin_user', $save_path);
}
/**
* 员工导入
*/
@ -580,16 +606,16 @@ class Users extends ApiCommon
$param['types'] = 'admin_user';
$file = request()->file('file');
$res = $excelModel->batchImportData($file, $param, $this);
$list=[];
$list[]=$excelModel->getError();
$item=$list[0];
$list = [];
$list[] = $excelModel->getError();
$item = $list[0];
if (!$res) {
return resultArray(['data' => $item]);
}
Cache::clear('user_info');
return resultArray(['data' => $item]);
}
/**
* 批量设置直属上级
*
@ -602,29 +628,29 @@ class Users extends ApiCommon
if (false === UserModel::checkUserGroup([1, 2, 3])) {
return resultArray(['error' => '没有该权限']);
}
$parent_id = (int) $this->param['parent_id'];
$parent_id = (int)$this->param['parent_id'];
$parent_user = UserModel::find($parent_id);
if (!$parent_user) {
return resultArray(['error' => '请选择直属上级']);
}
$user_id_list = (array) $this->param['id_list'];
$user_id_list = (array)$this->param['id_list'];
if (empty($user_id_list)) {
return resultArray(['error' => '请选择员工']);
}
if (in_array(1, $user_id_list)) {
return resultArray(['error' => '超级管理员不能设置上级']);
}
if (in_array($parent_id, $user_id_list)) {
return resultArray(['error' => '直属上级不能为员工自己']);
}
foreach ($user_id_list as $val) {
if (in_array($parent_id, getSubUserId(true, 0, (int) $val))) {
if (in_array($parent_id, getSubUserId(true, 0, (int)$val))) {
return resultArray(['error' => '直属上级不能是自己下属(包含下属的下属)']);
}
}
$a = new UserModel;
if ($a->where(['id' => ['IN', $user_id_list]])->update(['parent_id' => $parent_id])) {
Cache::clear('user_info');
@ -633,33 +659,36 @@ class Users extends ApiCommon
return resultArray(['error' => '员工直属上级设置失败' . $a->getError()]);
}
}
/**
* 通讯录列表
* @return mixed
*/
public function queryList(){
public function queryList()
{
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id']=$userInfo['id'];
$userLogic=new UserLogic();
$data=$userLogic->getDataList($param);
$param['user_id'] = $userInfo['id'];
$userLogic = new UserLogic();
$data = $userLogic->getDataList($param);
return resultArray(['data' => $data]);
}
/**
* 关注的通讯录列表
* @return mixed
*/
public function starList(){
public function starList()
{
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id']=$userInfo['id'];
$userLogic=new UserLogic();
$data=$userLogic->queryList($param);
$param['user_id'] = $userInfo['id'];
$userLogic = new UserLogic();
$data = $userLogic->queryList($param);
return resultArray(['data' => $data]);
}
/**
* 设置关注
*
@ -667,19 +696,19 @@ class Users extends ApiCommon
public function userStar()
{
$userInfo = $this->userInfo;
$userId = $userInfo['id'];
$userId = $userInfo['id'];
$targetId = $this->param['target_id'];
$type = $this->param['type'];
$type = $this->param['type'];
if (empty($userId) || empty($targetId) || empty($type)) return resultArray(['error' => '缺少必要参数!']);
if (!$this->setStar($type, $userId, $targetId)) {
return resultArray(['error' => '设置关注失败!']);
}
return resultArray(['data' => '设置关注成功!']);
}
/**
* 复制员工角色
*
@ -688,17 +717,16 @@ class Users extends ApiCommon
public function copyRole()
{
$param = $this->param;
if (empty($param['user_id']) && empty($param['structure_id'])) return resultArray(['error' => '请选择员工或部门!']);
if (empty($param['group_id'])) return resultArray(['error' => '请选择角色!']);
$userModel = new User();
if (!$userModel->copyRole($param)) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']);
}
/**
* 获取下属(全部层级)
*
@ -706,33 +734,79 @@ class Users extends ApiCommon
public function subordinate()
{
$userId = $this->userInfo['id'];
# 获取下属的ID
$subIds = getSubUserId(false, 0, $userId);
$data = Db::name('admin_user')->field(['id', 'realname', 'thumb_img as img'])->whereIn('id', $subIds)->select();
foreach ($data AS $key => $value) {
foreach ($data as $key => $value) {
$data[$key]['img'] = !empty($data[$key]['img']) ? getFullPath($data[$key]['img']) : '';
}
return resultArray(['data' => $data]);
}
/**
* 获取当前登录人信息
*
*/
*/
public function queryLoginUser()
{
$resData = [];
$wkcode = file_get_contents(CONF_PATH.'license.dat');
$wkcode = file_get_contents(CONF_PATH . 'license.dat');
if ($wkcode) {
$resCheckData = checkWkCode($wkcode);
if ($resCheckData) {
$resData = object_to_array(json_decode($resCheckData));
}
}
}
return $resData;
return $resData;
}
/**
* 批量重设部门
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/15 0015 16:37
*/
public function setUserDept()
{
//权限判断
// 仅允许超管,系统管理员,部门与员工管理员 导入
if (false === UserModel::checkUserGroup([1, 2, 3])) {
return resultArray(['error' => '没有该权限']);
}
$userModel = model('User');
$param = $this->param;
if (!is_array($param['id'])) {
$ids[] = $param['id'];
} else {
$ids = $param['id'];
}
$data = $userModel->setUserDept($ids, $param);
if (!$data) {
return resultArray(['error' => $userModel->getError()]);
}
# 添加记录
$userInfo = $this->userInfo;
foreach ($ids as $key => $val) {
$dataInfo = db('admin_user')->where('id', $val)->find();
SystemActionLog($userInfo['id'], 'admin_user', 'employee', $val, 'update', $dataInfo['realname'], '', '','重置了部门: ' . $dataInfo['realname']);
}
return resultArray(['data' => '操作成功']);
}
/**
* 员工分类后面跟的数据
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/24 0024 14:42
*/
public function countNumOfUser(){
$userModel = model('User');
$data=$userModel->countNumOfUser();
return resultArray(['data' => $data['list']]);
}
}

@ -85,10 +85,13 @@ class Work extends ApiCommon
*/
public function saveRole(WorkLogic $workLogic)
{
$userInfo=$this->userInfo;
if (empty($this->param['title'])) return resultArray(['error' => '请填写权限名称!']);
if (!$workLogic->saveRole($this->param)) return resultArray(['操作失败!']);
$data=$workLogic->saveRole($this->param);
if (!$data) return resultArray(['操作失败!']);
# 添加系统操作日志
SystemActionLog($userInfo['id'], 'admin_group','project', $data, 'save',$this->param['title'] , '', '','添加了项目管理权限:'.$this->param['title']);
return resultArray(['data' => '操作成功!']);
}
@ -122,8 +125,8 @@ class Work extends ApiCommon
{
if (empty($this->param['id'])) return resultArray(['error' => '请选择要编辑的权限角色!']);
if (empty($this->param['title'])) return resultArray(['error' => '请填写权限名称!']);
if ($workLogic->updateRole($this->param) === false) return resultArray(['error' => '操作失败!']);
$data=$workLogic->updateRole($this->param);
if (empty($data)) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']);
}

@ -125,7 +125,7 @@ class DailyRuleLogic
'userIds' => $param['userIds'],
'start_time' => $param['start_time'],
'end_time' => $param['end_time'],
'status' => $param['status']
'status' => $param['status']?:''
];
if (Db::name('admin_oalog_rule')->where('type', 2)->value('id')) {
@ -150,7 +150,7 @@ class DailyRuleLogic
'userIds' => $param['userIds'],
'start_time' => $param['start_time'],
'end_time' => $param['end_time'],
'status' => $param['status']
'status' => $param['status']?:''
];
if (Db::name('admin_oalog_rule')->where('type', 3)->value('id')) {
@ -178,8 +178,8 @@ class DailyRuleLogic
'userIds' => $day['userIds'],
'user' => $this->getUsers($day['userIds']),
'effective_day' => $day['effective_day'],
'start_time' => $day['start_time'],
'end_time' => $day['end_time']
'start_time' => $day['start_time']?:null,
'end_time' => $day['end_time']?:null
];
}
@ -201,8 +201,8 @@ class DailyRuleLogic
'userIds' => $week['userIds'],
'user' => $this->getUsers($week['userIds']),
'effective_day' => $week['effective_day'],
'start_time' => $week['start_time'],
'end_time' => $week['end_time']
'start_time' => $week['start_time']?:1,
'end_time' => $week['end_time']?:3
];
}
@ -224,8 +224,8 @@ class DailyRuleLogic
'userIds' => $month['userIds'],
'user' => $this->getUsers($month['userIds']),
'effective_day' => $month['effective_day'],
'start_time' => $month['start_time'],
'end_time' => $month['end_time']
'start_time' => $month['start_time']?:1,
'end_time' => $month['end_time']?:3
];
}

@ -12,6 +12,43 @@ use think\Db;
class FieldGrantLogic
{
private $except = [
'leads' => [
'name', 'email', 'source', 'mobile', 'telephone', 'detail_address', 'industry', 'level', 'next_time',
'remark', 'owner_user_id', 'last_record', 'create_user_id', 'create_time', 'update_time', 'last_time'
],
'customer' => [
'name', 'source', 'mobile', 'telephone', 'website', 'industry', 'level', 'next_time', 'remark', 'email',
'owner_user_id', 'last_record', 'create_user_id', 'create_time', 'update_time', 'last_time', 'obtain_time',
'deal_status', 'is_lock', 'pool_day'
],
'contacts' => [
'name', 'customer_id', 'mobile', 'telephone', 'email', 'post', 'decision', 'detail_address', 'next_time',
'remark', 'sex', 'owner_user_id', 'create_user_id', 'create_time', 'update_time', 'last_time', 'last_record'
],
'business' => [
'name', 'customer_id', 'money', 'deal_date', 'remark', 'status_id', 'type_id', 'owner_user_id',
'create_user_id', 'create_time', 'update_time', 'last_time', 'last_record'
],
'contract' => [
'name', 'num', 'customer_id', 'business_id', 'money', 'order_date', 'start_time', 'end_time', 'contacts_id',
'order_user_id', 'remark', 'owner_user_id', 'create_user_id', 'create_time', 'update_time', 'last_time',
'last_record', 'done_money', 'un_money', 'check_status'
],
'receivables' => [
'number', 'customer_id', 'contract_id', 'plan_id', 'return_time', 'money', 'return_type', 'remark',
'owner_user_id', 'create_user_id', 'create_time', 'update_time', 'check_status'
],
'product' => [
'name', 'category_id', 'unit', 'num', 'price', 'description', 'status', 'owner_user_id', 'create_user_id',
'create_time', 'update_time'
],
'visit' => [
'number', 'visit_time', 'owner_user_id', 'shape', 'customer_id', 'contacts_id', 'contract_id', 'satisfaction',
'feedback', 'create_user_id', 'create_time', 'update_time'
]
];
/**
* 字段授权列表
*
@ -43,20 +80,6 @@ class FieldGrantLogic
return !empty($data) ? $data : [];
}
/**
* 更新授权字段
*
* @param $grantId
* @param $content
* @return int|string
* @throws \think\Exception
* @throws \think\exception\PDOException
*/
public function update($grantId, $content)
{
return Db::name('admin_field_grant')->where('grant_id', $grantId)->update(['content' => serialize(array_values($content))]);
}
/**
* 添加字段授权信息
*
@ -76,7 +99,7 @@ class FieldGrantLogic
# 添加商机字段授权数据
$this->createBusinessFieldGrant($roleId);
# 添加合同字段授权数据
$this->createContractfieldGrant($roleId);
$this->createContractFieldGrant($roleId);
# 添加回款字段授权数据
$this->createReceivablesFieldGrant($roleId);
# 添加产品字段授权信息
@ -85,6 +108,20 @@ class FieldGrantLogic
$this->createVisitFieldGrant($roleId);
}
/**
* 更新授权字段
*
* @param $grantId
* @param $content
* @return int|string
* @throws \think\Exception
* @throws \think\exception\PDOException
*/
public function update($grantId, $content)
{
return Db::name('admin_field_grant')->where('grant_id', $grantId)->update(['content' => serialize(array_values($content))]);
}
/**
* 删除授权字段数据
*
@ -149,6 +186,9 @@ class FieldGrantLogic
$fieldBaseData = [];
$fieldList = Db::name('admin_field')->field(['name', 'field'])->where('types', $types)->select();
foreach ($fieldList AS $key => $value) {
# 排除掉固定字段
if (in_array($value['field'], $this->except[$typesArray[1]])) continue;
$fieldBaseData[$value['field']] = $value;
}
@ -168,9 +208,8 @@ class FieldGrantLogic
# 【处理删除:】没有在$fieldData找到说明自定义字段被删除则进行同步删除。
unset($content[(int)$k]);
} else {
# 【处理更新:】如果在$fieldData找到则进行同步更新。
$content[$k]['name'] = $fieldData[$v['field']]['name'];
$content[$k]['name'] = $fieldData[$v['field']]['name'];
$content[$k]['field'] = $fieldData[$v['field']]['field'];
# 删除$fieldData的数据方便统计新增的自定义字段。
@ -194,7 +233,6 @@ class FieldGrantLogic
}
}
# todo 暂时将数据库操作写在循环中!!!
Db::name('admin_field_grant')->where('grant_id', $value['grant_id'])->update(['content' => serialize(array_values($content))]);
}
@ -202,39 +240,51 @@ class FieldGrantLogic
}
/**
* 添加线索字段授权数据
* 处理线索字段授权数据
*
* @param $roleId
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @param int $roleId 角色ID
* @author fanqi
* @date 2021-03-22
*/
private function createLeadsFieldGrant($roleId)
{
$content = [];
# 固定字段
$content = [
['field' => 'name', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '线索名称'],
['field' => 'email', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '邮箱'],
['field' => 'source', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '线索来源'],
['field' => 'mobile', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '手机'],
['field' => 'telephone', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '电话'],
['field' => 'detail_address', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '地址'],
['field' => 'industry', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户行业'],
['field' => 'level', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户级别'],
['field' => 'next_time', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '下次联系时间'],
['field' => 'remark', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
['field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
['field' => 'last_record', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进记录'],
['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
['field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
['field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
['field' => 'last_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进时间'],
];
$leadsList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_leads')->select();
# 处理自定义字段
# 自定义字段
foreach ($leadsList AS $key => $value) {
if (in_array($value['field'], $this->except['leads'])) continue;
$content[] = [
'name' => $value['name'],
'field' => $value['field'],
'read' => 1,
'read_operation' => in_array($value['field'], ['name', 'next_time']) ? 0 : 1,
'read_operation' => 1,
'write' => 1,
'write_operation' => $value['field'] == 'next_time' ? 0 : 1,
'write_operation' => 1,
'is_diy' => 1
];
}
# 处理固定字段
$content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '最后跟进记录', 'field' => 'record', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
Db::name('admin_field_grant')->insert([
'role_id' => $roleId,
'module' => 'crm',
@ -246,44 +296,55 @@ class FieldGrantLogic
}
/**
* 添加客户字段授权数据
* 处理客户字段授权数据
*
* @param $roleId
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @param int $roleId 角色ID
* @author fanqi
* @date 2021-03-22
*/
private function createCustomerFieldGrant($roleId)
{
$content = [];
# 固定字段
$content = [
['field' => 'name', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户名称'],
['field' => 'source', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户来源'],
['field' => 'mobile', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '手机'],
['field' => 'telephone', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '电话'],
['field' => 'website', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '网址'],
['field' => 'industry', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户行业'],
['field' => 'level', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户级别'],
['field' => 'next_time', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '下次联系时间'],
['field' => 'remark', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
['field' => 'email', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '邮箱'],
['field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
['field' => 'last_record', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进记录'],
['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
['field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
['field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
['field' => 'last_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进时间'],
['field' => 'obtain_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人获取客户时间'],
['field' => 'deal_status', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '成交状态'],
['field' => 'is_lock', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '锁定状态'],
['field' => 'pool_day', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '距进入公海天数'],
];
$customerList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_customer')->select();
# 处理自定义字段
# 自定义字段
foreach ($customerList AS $key => $value) {
if (in_array($value['field'], $this->except['customer'])) continue;
$content[] = [
'name' => $value['name'],
'field' => $value['field'],
'read' => 1,
'read_operation' => in_array($value['field'], ['name', 'deal_status']) ? 0 : 1,
'read_operation' => 1,
'write' => 1,
'write_operation' => $value['field'] == 'deal_status' ? 0 : 1,
'write_operation' => 1,
'is_diy' => 1
];
}
# 处理固定字段
$content[] = ['name' => '合同编号', 'field' => 'contract', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
$content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0];
$content[] = ['name' => '最后跟进记录', 'field' => 'record', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
$content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
$content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
$content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
$content[] = ['name' => '最后跟进时间', 'field' => 'record_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
$content[] = ['name' => '负责人获取客户时间', 'field' => 'deal_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
$content[] = ['name' => '成交状态', 'field' => 'deal_status', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0];
$content[] = ['name' => '锁定状态', 'field' => 'is_lock', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
$content[] = ['name' => '距进入公海天数', 'field' => 'pool_day', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
Db::name('admin_field_grant')->insert([
'role_id' => $roleId,
'module' => 'crm',
@ -295,38 +356,51 @@ class FieldGrantLogic
}
/**
* 添加联系人字段授权数据
* 处理联系人字段授权数据
*
* @param $roleId
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @param int $roleId 角色ID
* @author fanqi
* @date 2021-03-22
*/
private function createContactsFieldGrant($roleId)
{
$content = [];
# 固定字段
$content = [
['field' => 'name', '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' => 'mobile', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '手机'],
['field' => 'telephone', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '电话'],
['field' => 'email', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '邮箱'],
['field' => 'post', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '职务'],
['field' => 'decision', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '是否关键决策人'],
['field' => 'detail_address', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '地址'],
['field' => 'next_time', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '下次联系时间'],
['field' => 'remark', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
['field' => 'sex', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '性别'],
['field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
['field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
['field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
['field' => 'last_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进时间'],
];
$contactsList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_contacts')->select();
# 处理自定义字段
# 自定义字段
foreach ($contactsList AS $key => $value) {
if (in_array($value['field'], $this->except['contacts'])) continue;
$content[] = [
'name' => $value['name'],
'field' => $value['field'],
'read' => 1,
'read_operation' => in_array($value['field'], ['name', 'next_time']) ? 0 : 1,
'read_operation' => 1,
'write' => 1,
'write_operation' => $value['field'] == 'next_time' ? 0 : 1,
'write_operation' => 1,
'is_diy' => 1
];
}
# 处理固定字段
$content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
Db::name('admin_field_grant')->insert([
'role_id' => $roleId,
'module' => 'crm',
@ -338,39 +412,47 @@ class FieldGrantLogic
}
/**
* 添加商机字段授权数据
* 处理商机字段授权数据
*
* @param $roleId
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @param int $roleId 角色ID
* @author fanqi
* @date 2021-03-22
*/
private function createBusinessFieldGrant($roleId)
{
$content = [];
# 固定字段
$content = [
['field' => 'name', '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' => 'money', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '商机金额'],
['field' => 'deal_date', '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' => '备注'],
['field' => 'status_id', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '商机阶段'],
['field' => 'type_id', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '商机状态组'],
['field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
['field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
['field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
['field' => 'last_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进时间'],
];
$BusinessList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_business')->select();
# 处理自定义字段
# 自定义字段
foreach ($BusinessList AS $key => $value) {
if (in_array($value['field'], $this->except['business'])) continue;
$content[] = [
'name' => $value['name'],
'field' => $value['field'],
'read' => 1,
'read_operation' => in_array($value['field'], ['customer_id', 'type_id', 'status_id']) == '' ? 0 : 1,
'read_operation' => 1,
'write' => 1,
'write_operation' => in_array($value['field'], ['customer_id', 'type_id', 'status_id']) ? 0 : 1,
'write_operation' => 1,
'is_diy' => 1
];
}
# 处理固定字段
$content[] = ['name' => '整单折扣', 'field' => 'discount_rate', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
$content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
Db::name('admin_field_grant')->insert([
'role_id' => $roleId,
'module' => 'crm',
@ -382,43 +464,55 @@ class FieldGrantLogic
}
/**
* 添加合同字段授权数据
* 处理合同字段授权数据
*
* @param $roleId
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @param int $roleId 角色ID
* @author fanqi
* @date 2021-03-22
*/
private function createContractfieldGrant($roleId)
private function createContractFieldGrant($roleId)
{
$content = [];
# 固定字段
$content = [
['field' => 'name', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同名称'],
['field' => 'num', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同编号'],
['field' => 'customer_id', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户名称'],
['field' => 'business_id', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '商机名称'],
['field' => 'money', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同金额'],
['field' => 'order_date', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '下单时间'],
['field' => 'start_time', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同开始时间'],
['field' => 'end_time', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同结束时间'],
['field' => 'contacts_id', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户签约人'],
['field' => 'order_user_id', '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' => '备注'],
['field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
['field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
['field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
['field' => 'last_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进时间'],
['field' => 'last_record', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进记录'],
['field' => 'done_money', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '已收款金额'],
['field' => 'un_money', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '未收款金额'],
['field' => 'check_status', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '审核状态'],
];
$contractList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_contract')->select();
# 处理自定义字段
# 自定义字段
foreach ($contractList AS $key => $value) {
if (in_array($value['field'], $this->except['contract'])) continue;
$content[] = [
'name' => $value['name'],
'field' => $value['field'],
'read' => 1,
'read_operation' => $value['field'] == 'num' ? 0 : 1,
'read_operation' => 1,
'write' => 1,
'write_operation' => 1,
'is_diy' => 1
];
}
# 处理固定字段
$content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '最后跟进记录', 'field' => 'record', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '最后跟进记录', 'field' => 'record_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '已收款金额', 'field' => 'received', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '未收款金额', 'field' => 'uncollected', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '审核状态', 'field' => 'check_status', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
Db::name('admin_field_grant')->insert([
'role_id' => $roleId,
'module' => 'crm',
@ -430,21 +524,38 @@ class FieldGrantLogic
}
/**
* 添加回款字段授权数据
* 处理回款字段授权数据
*
* @param $roleId
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @param int $roleId 角色ID
* @author fanqi
* @date 2021-03-22
*/
private function createReceivablesFieldGrant($roleId)
{
$content = [];
# 固定字段
$content = [
['field' => 'number', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回款编号'],
['field' => 'customer_id', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户名称'],
['field' => 'contract_id', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同编号'],
['field' => 'plan_id', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '期数'],
['field' => 'return_time', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回款日期'],
['field' => 'money', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回款金额'],
['field' => 'return_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' => '备注'],
['field' => 'contract_money', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '合同金额'],
['field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
['field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
['field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
['field' => 'check_status', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '审核状态'],
];
$receivablesList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_receivables')->select();
# 处理自定义字段
# 自定义字段
foreach ($receivablesList AS $key => $value) {
if (in_array($value['field'], $this->except['receivables'])) continue;
$content[] = [
'name' => $value['name'],
'field' => $value['field'],
@ -456,14 +567,6 @@ class FieldGrantLogic
];
}
# 处理固定字段
$content[] = ['name' => '合同金额', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '审核状态', 'field' => 'check_status', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
Db::name('admin_field_grant')->insert([
'role_id' => $roleId,
'module' => 'crm',
@ -475,44 +578,46 @@ class FieldGrantLogic
}
/**
* 添加产品字段授权信息
* 处理产品字段授权信息
*
* @param $roleId
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @param int $roleId 角色ID
* @author fanqi
* @date 2021-03-22
*/
private function createProductFieldGrant($roleId)
{
$content = [];
# 固定字段
$content = [
['field' => 'name', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '产品名称'],
['field' => 'category_id', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '产品类型'],
['field' => 'unit', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '产品单位'],
['field' => 'num', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '产品编码'],
['field' => 'price', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '价格'],
['field' => 'description', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '产品描述'],
['field' => 'status', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '是否上下架'],
['field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
['field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
['field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
];
$productList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_product')->select();
# 处理自定义字段
# 自定义字段
foreach ($productList AS $key => $value) {
$readOperation = 1;
$writeOperation = 1;
if (in_array($value['field'], ['name', 'category_id', 'unit', 'price', 'status'])) $readOperation = 0;
if (in_array($value['field'], ['status'])) $writeOperation = 0;
if (in_array($value['field'], $this->except['product'])) continue;
$content[] = [
'name' => $value['name'],
'field' => $value['field'],
'read' => 1,
'read_operation' => $readOperation,
'read_operation' => 1,
'write' => 1,
'write_operation' => $writeOperation,
'write_operation' => 1,
'is_diy' => 1
];
}
# 处理固定字段
$content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
Db::name('admin_field_grant')->insert([
'role_id' => $roleId,
'module' => 'crm',
@ -524,21 +629,35 @@ class FieldGrantLogic
}
/**
* 添加回访字段授权信息
* 处理回访字段授权信息
*
* @param $roleId
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @param int $roleId
* @author fanqi
* @date 2021-03-22
*/
private function createVisitFieldGrant($roleId)
{
$content = [];
$visitList = Db::name('admin_field')->field(['name', 'field'])->where(['type' => 'crm_visit', 'operating' => 0])->select();
$content = [
['field' => 'number', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回访编号'],
['field' => 'visit_time', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回访时间'],
['field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '回访人'],
['field' => 'shape', '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' => 'contacts_id', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '联系人'],
['field' => 'contract_id', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '合同编号'],
['field' => 'satisfaction', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户满意度'],
['field' => 'feedback', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户反馈'],
['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
['field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
['field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
];
$visitList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_visit')->select();
# 处理自定义字段
foreach ($visitList AS $key => $value) {
if (in_array($value['field'], $this->except['visit'])) continue;
$content[] = [
'name' => $value['name'],
'field' => $value['field'],
@ -550,21 +669,6 @@ class FieldGrantLogic
];
}
# 处理固定字段
$content[] = ['name' => '回访编号', 'field' => 'number', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
$content[] = ['name' => '回访形式', 'field' => 'shape', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
$content[] = ['name' => '客户满意度', 'field' => 'satisfaction', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
$content[] = ['name' => '回访时间', 'field' => 'visit_time', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
$content[] = ['name' => '客户名称', 'field' => 'customer_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '联系人', 'field' => 'contacts_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '合同编号', 'field' => 'contract_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '客户反馈', 'field' => 'feedback', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
$content[] = ['name' => '回访人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
$content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '编辑时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
$content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
Db::name('admin_field_grant')->insert([
'role_id' => $roleId,
'module' => 'crm',

@ -8,6 +8,7 @@
namespace app\admin\logic;
use app\admin\controller\UpdateSql;
use think\Db;
use think\Exception;
@ -275,6 +276,32 @@ class InitializeLogic
# ------ 重置联系人数据 END ------ #
# ------ 重置公海数据 START ------ #
# 清除公海主数据并重置自增ID
Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool");
# 清除公海字段数据并重置自增ID
Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool_field_setting");
# 清除公海用户自定义字段样式数据并重置自增ID
Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool_field_style");
# 清除公海操作记录数据并重置自增ID
Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool_record");
# 清除公海关联数据并重置自增ID
Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool_relation");
# 清除公海规则数据并重置自增ID
Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool_rule");
# 添加公海默认数据
UpdateSql::addPoolDefaultData();
# ------ 重置公海数据 END ------ #
# ------ 重置客户数据 START ------ #
# 获取客户附件ID
@ -355,15 +382,10 @@ class InitializeLogic
# ------ 清除数据操作日志数据 END ------ #
# ------ 清除模板打印记录数据 START ------ #
# ------ 清除客户配置表(锁定、拥有)数据 START ------ #
Db::query("TRUNCATE TABLE ".$prefix."crm_customer_config");
# ------ 清除模板打印记录数据 END ------ #
# ------ 清除模板打印记录数据 START ------ #
Db::query("TRUNCATE TABLE ".$prefix."crm_printing_record");
# ------ 清除模板打印记录数据 END ------ #
# ------ 清除客户配置表(锁定、拥有)数据 END ------ #
# ------ 清除导入数据记录表 START ------ #
Db::name('admin_import_record')->where(['type' => ['like', 'crm_%']])->delete();
@ -400,7 +422,7 @@ class InitializeLogic
# ------ 清除跟客户模块有关的管理数据表 END ------ #
# ------ 清除自动编号数据 START ------ #
# ------ 重置自动编号数据 START ------ #
$time = time();
Db::query("TRUNCATE TABLE ".$prefix."crm_number_sequence");
Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (1, 1, 1, 'HT', null, null, null, null, ".$time.", 1, null, 0, 1)");
@ -415,7 +437,7 @@ class InitializeLogic
Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (10, 1, 2, 'yyyyMMdd', null, null, null, null, ".$time.", 1, null, 0, 4)");
Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (11, 2, 1, 'FP', null, null, null, null, ".$time.", 1, null, 0, 4)");
Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (12, 3, 3, 1, 1, 1, 1, ".$time.", ".$time.", 1, null, 0, 4)");
# ------ 清除自动编号数据 END ------ #
# ------ 重置自动编号数据 END ------ #
# ------ 设置跟进记录常用语 START ------ #
@ -435,6 +457,12 @@ class InitializeLogic
# ------ 设置跟进记录常用语 END ------ #
# ------ 清除打印相关数据 START ------ #
Db::query("TRUNCATE TABLE ".$prefix."admin_printing_data");
Db::query("TRUNCATE TABLE ".$prefix."crm_printing_record");
# ------ 清除打印相关数据 END ------ #
# ------ 删除审批记录 START ------ #
Db::name('admin_examine_record')->whereLike('types', 'crm%')->delete();
Db::query("ALTER TABLE ".$prefix."admin_examine_record AUTO_INCREMENT = 1");
@ -830,6 +858,12 @@ class InitializeLogic
// # 重置自增ID
// Db::query("ALTER TABLE ".$prefix."task AUTO_INCREMENT = 1");
# 清除项目排序数据
Db::query("TRUNCATE TABLE ".$prefix."work_order");
# 清除标签排序数据
Db::query("TRUNCATE TABLE ".$prefix."work_lable_order");
# 清除项目数据
Db::query("TRUNCATE TABLE ".$prefix."work");

@ -31,11 +31,10 @@ class LogLogic
'crm_visit' => '回访',
'crm_invoice' => '回款',
'oa_log' => '办公日志',
'oa_examine' => '办公审批',
'work_task' => '任务',
'work' => '项目',
'label' => '标签',
'calendar' => '日历'
'oa_event' => '日程',
'crm_activity' => '跟进记录',
];
public $systemModules = [
@ -47,19 +46,53 @@ class LogLogic
'approval' => '审批流程管理',
'workbench' => '工作台',
'project' => '项目管理',
'customer' => '客户管理'
'customer' => '客户管理',
'work_task' => '其他设置'
];
public $systemAction=[
'admin_oalog_rule'=>'日志',
'admin_group'=>'角色',
'crm_leads' => '线索',
'crm_customer' => '客户',
'crm_pool' => '客户公海',
'crm_contacts' => '联系人',
'crm_product' => '产品',
'crm_business' => '商机',
'crm_contract' => '合同',
'crm_receivables' => '回款',
'crm_visit' => '回访',
'crm_invoice' => '回款',
'oa_log' => '办公日志',
'oa_examine' => '办公审批',
'crm_config' => '客户管理系统设置',
'crm_number_sequence' => '业绩目标',
'admin_structure' => '部门',
'admin_config' => '应用管理',
'work_task' => '其他设置'
];
/**
* 日志记录中的行为所对应的中文名称
*
* @var string[]
*/
private $action = [
'index' => '查看数据',
'save' => '添加数据',
'update' => '编辑数据',
'delete' => '删除数据'
'delete' => '删除数据',
'excel' => '导入数据',
'excelexport' => '导出数据',
'lock' => '锁定',
'islock' => '解锁',
'status' => '更改成交状态',
'receive' => '领取',
'transfer' => '转移',
'teamSave' => '添加团队成员',
'distribute' => '分配',
'up' => '上架',
'down' => '下架',
'recover' => '归档恢复',
'archiveData' => '归档',
'copy' => '复制',
];
private $loginType = [
'成功', '密码错误', '账号禁用'
@ -73,20 +106,34 @@ class LogLogic
*/
public function getLoginRecord($param)
{
$loginRecordModel = new LoginRecord();
$limit = !empty($param['limit']) ? $param['limit'] : 15;
$data = $loginRecordModel->where(function ($query) use ($param) {
if (!empty($param['startTime'])) $query->where('create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('create_time', '<=', strtotime($param['endTime']));
if (!empty($param['userIds'])) $query->whereIn('create_user_id', $param['userIds']);
})->order('id', 'desc')->paginate($limit)->each(function ($value) {
$value['username'] = $value->create_user_info['realname'];
$value['type'] = $this->loginType[$value['type']];
})->toArray();
return ['list' => $data['data'], 'count' => $data['total']];
$res= db('admin_login_record')
->alias('login')
->join('__ADMIN_USER__ user','user.id=login.create_user_id','LEFT')
->where(function ($query) use ($param) {
if (!empty($param['startTime'])) $query->where('login.create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('login.create_time', '<=', strtotime($param['endTime']));
if (!empty($param['userIds'])) $query->whereIn('login.create_user_id', $param['userIds']);
})
->field('login.*,user.realname as username')
->page($param['page'],$param['limit'])
->order('login.id', 'desc')
->select();
foreach ($res as $k =>$v){
$res[$k]['create_time']=!empty($v['create_time'])?date('Y-m-d H:i:s',$v['create_time']):null;
$res[$k]['type']=$this->loginType[$v['type']];
}
$total= db('admin_login_record')
->alias('login')
->join('__ADMIN_USER__ user','user.id=login.create_user_id','LEFT')
->where(function ($query) use ($param) {
if (!empty($param['startTime'])) $query->where('login.create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('login.create_time', '<=', strtotime($param['endTime']));
if (!empty($param['userIds'])) $query->whereIn('login.create_user_id', $param['userIds']);
})->count();
$data=[];
$data['list']=$res;
$data['dataCount']=$total;
return $data;
}
@ -102,15 +149,19 @@ class LogLogic
*/
public function getSystemLogs($param)
{
$data = SystemLog::with(['toAdminUser'])
$data = db('admin_system_log')
->alias('system')
->join('__ADMIN_USER__ user','user.id=system.user_id','LEFT')
->where(function ($query) use ($param) {
if (!empty($param['startTime'])) $query->where('create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('create_time', '<=', strtotime($param['endTime']));
if (!empty($param['modules'])) $query->whereIn('modules', $param['modules']);
if (!empty($param['userIds'])) $query->whereIn('user_id', $param['userIds']);
})->limit(($param['page'] - 1) * $param['limit'])->order('log_id', 'desc')->select();
return $this->setSystemData($data);
if (!empty($param['startTime'])) $query->where('system.create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('system.create_time', '<=', strtotime($param['endTime']));
if (!empty($param['modules'])) $query->whereIn('system.module_name', $param['modules']);
if (!empty($param['userIds'])) $query->whereIn('system.user_id', $param['userIds']);
})
->page($param['page'], $param['limit'])
->field('system.log_id,system.target_name,system.create_time,system.client_ip,system.module_name,system.content,system.target_name,system.action_name,system.controller_name,user.realname')
->order('system.log_id', 'desc')->select();
return $this->setSystemData($data);
}
/**
@ -140,15 +191,18 @@ class LogLogic
*/
public function getRecordLogs($param)
{
$data = OperationLog::with(['toAdminUser'])
$data = db('admin_operation_log')
->alias('operation')
->join('__ADMIN_USER__ user','user.id=operation.user_id','LEFT')
->where(function ($query) use ($param) {
if (!empty($param['startTime'])) $query->where('create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('create_time', '<=', strtotime($param['endTime']));
if (!empty($param['modules'])) $query->whereIn('module', $param['modules']);
if (!empty($param['userIds'])) $query->whereIn('user_id', $param['userIds']);
if (!empty($param['startTime'])) $query->where('operation.create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('operation.create_time', '<=', strtotime($param['endTime']));
if (!empty($param['modules'])) $query->whereIn('operation.module', arrayToString($param['modules']));
if (!empty($param['userIds'])) $query->whereIn('operation.user_id', $param['userIds']);
})
->limit(($param['page'] - 1) * $param['limit'])->order('log_id', 'desc')->select();
->field('operation.*,user.realname')
->page($param['page'], $param['limit'])
->order('operation.log_id', 'desc')->select();
return $this->setRecordData($data);
}
@ -160,12 +214,15 @@ class LogLogic
*/
public function getRecordLogCount($param)
{
return OperationLog::where(function ($query) use ($param) {
if (!empty($param['startTime'])) $query->where('create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('create_time', '<=', strtotime($param['endTime']));
if (!empty($param['modules'])) $query->whereIn('module', $param['module']);
if (!empty($param['userIds'])) $query->whereIn('user_id', $param['userIds']);
})->count();
return db('admin_operation_log')
->alias('operation')
->join('__ADMIN_USER__ user','user.id=operation.user_id','LEFT')
->where(function ($query) use ($param) {
if (!empty($param['startTime'])) $query->where('operation.create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('operation.create_time', '<=', strtotime($param['endTime']));
if (!empty($param['modules'])) $query->whereIn('operation.module', arrayToString($param['modules']));
if (!empty($param['userIds'])) $query->whereIn('operation.user_id', $param['userIds']);
})->count();
}
/**
@ -181,11 +238,15 @@ class LogLogic
foreach ($data AS $key => $value) {
$result[] = [
'log_id' => $value['log_id'],
'source_name' => $value['source_name'],
'source_name' => $value['target_name'],
'create_time' => date('Y-m-d H:i:s', $value['create_time']),
'ip' => $value['client_ip'],
'module' => $this->recordModules[$value['module']],
'content' => $value['content']
'action' => in_array('crm',explode('_',$value['module']))==1?
'客户管理':(in_array('oa',explode('_',$value['module']))==1?'办公管理':'项目管理'),
'content' => $value['content'],
'user_name' => $value['realname'],
'action_name' => $this->action[$value['action_name']],
];
}
@ -193,7 +254,7 @@ class LogLogic
}
/**
* 组装数据操作日志数据
* 组装系统操作数据操作日志数据
*
* @param $data
* @return mixed
@ -201,18 +262,181 @@ class LogLogic
private function setSystemData($data)
{
$result = [];
foreach ($data AS $key => $value) {
$result[] = [
'log_id' => $value['log_id'],
'source_name' => $value['source_name'],
'source_name' => $value['target_name'],
'create_time' => date('Y-m-d H:i:s', $value['create_time']),
'ip' => $value['client_ip'],
'module' => $this->systemModules[$value['module']],
'content' => $value['content']
'action' => $this->systemModules[$value['module_name']],
'content' => $value['content'],
'user_name' => $value['realname'],
'action_name' => $this->action[$value['action_name']],
'module' => '后台管理',
'action_down' => $this->recordModules[$value['controller_name']]?:'',
];
}
return $result;
}
/**
* 导出方法
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/8 0008 16:37
*/
public function downExcel($param){
$excelModel = new \app\admin\model\Excel();
$file_name='sysLogs';
$field_list=[];
$type='';
$action=$param['action'];
unset($param['action']);
unset($param['page']);
unset($param['limit']);
$param['startTime']= !empty($param['startTime'])?$param['startTime'].' 00:00:00':'';
$param['endTime']= !empty($param['endTime'])?$param['endTime'].' 23:59:59':'';
switch ($action){
case 'getSystemLogs':
$type='系统日志';
$field_list = [
'0' => ['name' => '用户', 'field' => 'user_name'],
'1' => ['name' => '时间', 'field' => 'create_time'],
'2' => ['name' => 'ip地址', 'field' => 'ip'],
'3' => ['name' => '模块', 'field' => 'module'],
'4' => ['name' => '子模块', 'field' => 'action'],
'5' => ['name' => '行为', 'field' => 'action_name'],
'6' => ['name' => '对象', 'field' => 'source_name'],
'7' => ['name' => '操作详情', 'field' => 'content'],
];
$modules = $this->systemModules;
if(!empty($param['subModelLabels'])){
$param['modules']=$param['subModelLabels'];
}
$list = db('admin_system_log')
->alias('system')
->join('__ADMIN_USER__ user','user.id=system.user_id','LEFT')
->where(function ($query) use ($param) {
if (!empty($param['startTime'])) $query->where('system.create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('system.create_time', '<=', strtotime($param['endTime']));
if (!empty($param['modules'])) $query->whereIn('system.module_name', $param['modules']);
if (!empty($param['userIds'])) $query->whereIn('system.user_id', $param['userIds']);
})
->field('system.log_id,system.target_name,system.create_time,system.client_ip,system.module_name,system.content,system.target_name,system.action_name,system.controller_name,user.realname')
->order('system.log_id', 'desc')->select();
$data=$this->setSystemData($list);
break;
case 'getRecordLogs':
$type='系统日志';
$field_list = [
'0' => ['name' => '用户', 'field' => 'user_name'],
'1' => ['name' => '时间', 'field' => 'create_time'],
'2' => ['name' => 'ip地址', 'field' => 'ip'],
'3' => ['name' => '模块', 'field' => 'action'],
'4' => ['name' => '子模块', 'field' => 'module'],
'5' => ['name' => '行为', 'field' => 'action_name'],
'6' => ['name' => '对象', 'field' => 'source_name'],
'7' => ['name' => '操作详情', 'field' => 'content'],
];
if(!empty($param['subModelLabels'])){
$param['modules']=$param['subModelLabels'];
}else{
switch ($param['model']){
case 'crm': //客户管理
$param['modules']=array(
'crm_leads' ,
'crm_customer',
'crm_pool' ,
'crm_contacts' ,
'crm_product' ,
'crm_business' ,
'crm_contract' ,
'crm_receivables' ,
'crm_visit' ,
'crm_invoice' ,
'crm_activity'
);
break;
case 'oa' : //办公管理
$param['modules']=array(
'oa_log' ,
'oa_event',
);
break;
case 'work' ://项目管理
$param['modules']=array(
'work_task' ,
'work',
);
break;
default :
$param['modules']=array(
'crm_leads' ,
'crm_customer',
'crm_pool' ,
'crm_contacts' ,
'crm_product' ,
'crm_business' ,
'crm_contract' ,
'crm_receivables' ,
'crm_visit' ,
'crm_invoice' ,
'crm_activity',
'oa_log' ,
'oa_event',
'work_task' ,
'work',
);
break;
}
}
$list = db('admin_operation_log')
->alias('operation')
->join('__ADMIN_USER__ user','user.id=operation.user_id','LEFT')
->where(function ($query) use ($param) {
if (!empty($param['startTime'])) $query->where('operation.create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('operation.create_time', '<=', strtotime($param['endTime']));
if (!empty($param['modules'])) $query->whereIn('operation.module', arrayToString($param['modules']));
if (!empty($param['userIds'])) $query->whereIn('operation.user_id', $param['userIds']);
})
->field('operation.*,user.realname')
->order('operation.log_id', 'desc')->select();
$data=$this->setRecordData($list);
break;
case 'getLoginRecord':
$type='登陆日志';
$field_list = [
'0' => ['name' => '用户', 'field' => 'username'],
'1' => ['name' => '时间', 'field' => 'create_time'],
'2' => ['name' => 'ip地址', 'field' => 'ip'],
'3' => ['name' => '登陆地点', 'field' => 'address'],
'4' => ['name' => '设备类型', 'field' => 'remark'],
'5' => ['name' => '终端内核', 'field' => 'browser'],
'6' => ['name' => '平台', 'field' => 'os'],
'7' => ['name' => '成功', 'field' => 'type'],
];
$res = db('admin_login_record')
->alias('login')
->join('__ADMIN_USER__ user','user.id=login.create_user_id','LEFT')
->where(function ($query) use ($param) {
if (!empty($param['startTime'])) $query->where('login.create_time', '>=', strtotime($param['startTime']));
if (!empty($param['endTime'])) $query->where('login.create_time', '<=', strtotime($param['endTime']));
if (!empty($param['userIds'])) $query->whereIn('login.create_user_id', $param['userIds']);
})
->field('login.*,user.realname as username')
->order('login.id', 'desc')
->select();
foreach ($res as $k =>$v){
$res[$k]['create_time']=!empty($v['create_time'])?date('Y-m-d H:i:s',$v['create_time']):null;
$res[$k]['type']=$this->loginType[$v['type']];
}
$data=$res;
break;
}
return $excelModel->biExportExcel($file_name, $field_list, $type, $data);
}
}

@ -127,7 +127,7 @@ class MessageLogic
}
}
$data = [];
$data['page']['list'] = $list;
$data['page']['list'] = array_values($list);
$data['page']['dataCount'] = $dataCount ?: 0;
if ($param['page'] != 1 && ($param['page'] * $param['limit']) >= $dataCount) {
$data['page']['firstPage'] = false;

@ -0,0 +1,481 @@
<?php
namespace app\admin\logic;
use PDOStatement;
use think\Collection;
use think\Db;
class PoolConfigLogic
{
public $error = '操作失败!';
/**
* 公海配置列表
*
* @param array $param page 页码limit 每页条数
* @author fanqi
* @since 2021-03-30
* @return array
*/
public function getPoolList($param)
{
$page = !empty($param['page']) ? $param['page'] : 1;
$limit = !empty($param['limit']) ? $param['limit'] : 15;
$count = db('crm_customer_pool')->count();
# 公海列表
$list = db('crm_customer_pool')->field([
'pool_id', 'pool_name', 'admin_user_ids', 'user_ids', 'department_ids', 'status'
])->limit(($page - 1) * $limit, $limit)->select();
# 统计公海下的客户数量
$customerData = [];
$customerList = db('crm_customer_pool_relation')->field(['pool_id', 'count(customer_id) AS customer_count'])->group('pool_id')->select();
foreach ($customerList AS $key => $value) {
$customerData[$value['pool_id']] = $value['customer_count'];
}
foreach ($list AS $key => $value) {
# 公海管理员
$adminUserIds = trim($value['admin_user_ids'], ',');
$adminUserNames = db('admin_user')->whereIn('id', $adminUserIds)->column('realname');
# 公海成员
$userIds = trim($value['user_ids'], ',');
$userNames = db('admin_user')->whereIn('id', $userIds)->column('realname');
# 部门
$structureIds = trim($value['department_ids'], ',');
$structureNames = db('admin_structure')->whereIn('id', $structureIds)->column('name');
# 公海成员
$poolMembers = array_merge($structureNames, $userNames);
$list[$key]['admin_user_names'] = implode(',', $adminUserNames);
$list[$key]['user_names'] = implode(',', array_unique($poolMembers));
$list[$key]['customer_count'] = !empty($customerData[$value['pool_id']]) ? $customerData[$value['pool_id']] : 0;
}
return ['count' => $count, 'list' => !empty($list) ? $list : []];
}
/**
* 设置多公海配置
*
* @param $param
* @author fanqi
* @since 2021-03-30
* @return bool
*/
public function setPoolConfig($param)
{
if (empty($param['pool_name'])) {
$this->error = '请填写公海名称!';
return false;
}
if (!empty($param['pool_name']) && mb_strlen($param['pool_name']) > 100) {
$this->error = '公海名称最多只能输入100个字符';
return false;
}
if (empty($param['admin_user_ids'])) {
$this->error = '请选择公海管理员!';
return false;
}
if (empty($param['user_ids']) && empty($param['department_ids'])) {
$this->error = '请选择公海成员!';
return false;
}
if (!empty($param['recycle_conf']) && empty($param['rule'])) {
$this->error = '请设置回收规则!';
return false;
}
$repeatWhere['pool_name'] = $param['pool_name'];
if (!empty($param['pool_id'])) $repeatWhere['pool_id'] = ['neq', $param['pool_id']];
if (db('crm_customer_pool')->where($repeatWhere)->value('pool_id')) {
$this->error = '公海名称重复';
return false;
}
$poolData = [
'pool_name' => $param['pool_name'],
'admin_user_ids' => ',' . $param['admin_user_ids'] . ',',
'user_ids' => ',' . $param['user_ids'] . ',',
'department_ids' => !empty($param['department_ids']) ? ',' . $param['department_ids'] . ',' : '',
'status' => 1,
'before_owner_conf' => $param['before_owner_conf'],
'before_owner_day' => $param['before_owner_day'],
'receive_conf' => $param['receive_conf'],
'receive_count' => $param['receive_count'],
'remind_conf' => $param['remind_conf'],
'remain_day' => $param['remain_day'],
'recycle_conf' => $param['recycle_conf'],
'create_user_id' => $param['user_id'],
'create_time' => time()
];
Db::startTrans();
try {
if (!empty($param['pool_id'])) {
# 编辑
$poolId = $param['pool_id'];
Db::name('crm_customer_pool')->where('pool_id', $poolId)->update($poolData);
} else {
# 创建
$poolId = Db::name('crm_customer_pool')->insert($poolData, false, true);
}
# 公海字段
$fieldData = $this->getPoolField($param['field'], $poolId);
if (!empty($fieldData)) {
Db::name('crm_customer_pool_field_setting')->where('pool_id', $poolId)->delete();
Db::name('crm_customer_pool_field_setting')->insertAll($fieldData);
}
# 公海规则
$ruleData = $this->getPoolRule($param['rule'], $poolId);
if (!empty($ruleData)) {
Db::name('crm_customer_pool_rule')->where('pool_id', $poolId)->delete();
Db::name('crm_customer_pool_rule')->insertAll($ruleData);
}
Db::commit();
return true;
} catch (\Exception $e) {
Db::rollback();
$this->error = '创建公海失败!';
return false;
}
}
/**
* 公海配置详情
*
* @param int $poolId 公海ID
* @author fanqi
* @since 2021-03-30
* @return array|bool
*/
public function readPool($poolId)
{
$data = db('crm_customer_pool')->where('pool_id', $poolId)->find();
if (empty($data['pool_id'])) {
$this->error = '没有查询到数据!';
return false;
}
# 时间格式
$data['create_time'] = date('Y-m-d H:i:s', $data['create_time']);
# 公海管理员
$adminUserIds = trim($data['admin_user_ids'], ',');
$data['admin_user_ids'] = $adminUserIds;
$data['admin_user_info'] = db('admin_user')->field(['id', 'realname', 'thumb_img'])->whereIn('id', $adminUserIds)->select();
foreach ($data['admin_user_info'] AS $key => $value) {
$data['admin_user_info'][$key]['thumb_img'] = getFullPath($value['thumb_img']);
}
# 公海成员
$userIds = trim($data['user_ids'], ',');
$data['user_ids'] = $userIds;
$data['user_info'] = db('admin_user')->field(['id', 'realname', 'thumb_img'])->whereIn('id', $userIds)->select();
foreach ($data['user_info'] AS $key => $value) {
$data['user_info'][$key]['thumb_img'] = getFullPath($value['thumb_img']);
}
# 公海部门
$departmentIds = trim($data['department_ids'], ',');
$data['department_ids'] = $departmentIds;
$data['department_info'] = db('admin_structure')->field(['id', 'name'])->whereIn('id', $departmentIds)->select();
# 公海字段
$data['field'] = db('crm_customer_pool_field_setting')->where('pool_id', $data['pool_id'])->select();
# 公海规则
$data['rule'] = db('crm_customer_pool_rule')->where('pool_id', $data['pool_id'])->select();
foreach ($data['rule'] AS $key => $value) {
if (!empty($value['level'])) {
$data['rule'][$key]['level'] = json_decode($value['level'], true);
$data['rule'][$key]['level_setting'] = json_decode($value['level'], true);
}
}
# 客户数量
$data['customer_count'] = db('crm_customer_pool_relation')->where('pool_id', $poolId)->count();
return $data;
}
/**
* 变更公海配置状态
*
* @param array $param pool_id 公海ID, status 状态1启用、0停用
* @author fanqi
* @since 2021-03-30
* @return false|int|string
*/
public function changePoolStatus($param)
{
$poolId = $param['pool_id'];
$status = $param['status'];
if ($status == 0 && db('crm_customer_pool_relation')->where('pool_id', $poolId)->count() > 0) {
$this->error = '公海内有客户,不能停用!';
return false;
}
if ($status == 0 && db('crm_customer_pool')->where(['pool_id' => ['neq', $poolId], 'status' => 1])->count() < 1) {
$this->error = '至少要开启一个公海!';
return false;
}
return db('crm_customer_pool')->where('pool_id', $poolId)->update(['status' => $status]);
}
/**
* 删除公海配置
*
* @param int $poolId 公海ID
* @author fanqi
* @since 2021-03-30
* @return bool
*/
public function deletePool($poolId)
{
if (db('crm_customer_pool_relation')->where('pool_id', $poolId)->count() > 0) {
$this->error = '公海内有客户,不能删除!';
return false;
}
if (db('crm_customer_pool')->where(['pool_id' => ['neq', $poolId], 'status' => 1])->count() < 1) {
$this->error = '至少要保留一个开启的公海!';
return false;
}
Db::startTrans();
try {
# 删除公海规则数据
Db::name('crm_customer_pool_rule')->where('pool_id', $poolId)->delete();
# 删除公海字段数据
Db::name('crm_customer_pool_field_setting')->where('pool_id', $poolId)->delete();
# 删除用户保存的公海字段数据
Db::name('crm_customer_pool_field_style')->where('pool_id', $poolId)->delete();
# 删除公海数据
Db::name('crm_customer_pool')->where('pool_id', $poolId)->delete();
Db::commit();
return true;
} catch (\Exception $e) {
Db::rollback();
$this->error = '删除公海配置失败!';
return false;
}
}
/**
* 转移公海客户
*
* @param array $param source_pool_id 源公海IDtarget_pool_id 目标公海ID
* @author fanqi
* @since 2021-03-30
* @return bool
*/
public function transferPool($param)
{
if (empty($param['source_pool_id']) || empty($param['target_pool_id'])) {
$this->error = '缺少源ID或目标ID';
return false;
}
# 源
$sourceCustomerIds = Db::name('crm_customer_pool_relation')->where('pool_id', $param['source_pool_id'])->column('customer_id');
# 目标
$targetCustomerIds = Db::name('crm_customer_pool_relation')->where('pool_id', $param['target_pool_id'])->column('customer_id');
# 差异
$diffCustomerIds = array_diff($sourceCustomerIds, $targetCustomerIds);
$data = [];
foreach ($diffCustomerIds AS $key => $value) {
$data[] = [
'customer_id' => $value,
'pool_id' => $param['target_pool_id']
];
}
Db::startTrans();
try {
Db::name('crm_customer_pool_relation')->where('pool_id', $param['source_pool_id'])->delete();
if (!empty($data)) Db::name('crm_customer_pool_relation')->insertAll($data);
Db::commit();
return true;
} catch (\Exception $e) {
Db::rollback();
$this->error = '转移失败!';
return false;
}
}
/**
* 获取客户级别列表
*
* @author fanqi
* @since 2021-04-22
* @return array
*/
public function getCustomerLevel()
{
$setting = db('admin_field')->where(['types' => 'crm_customer', 'field' => 'level'])->value('setting');
$data = explode(chr(10), $setting);
return !empty($data) ? $data : [];
}
/**
* 获取公海字段列表
*
* @param array $param pool_id 公海ID
* @author fanqi
* @since 2021-04-29
* @return bool|PDOStatement|string|Collection
*/
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();
} else {
$data = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden'])->where(['types' => 'crm_customer'])->select();
$address = [
'field' => 'address',
'name' => '省、市、区/县',
'form_type' => 'customer_address',
'is_hidden' => 0
];
$detailAddress = [
'field' => 'detail_address',
'name' => '详细地址',
'form_type' => 'text',
'is_hidden' => 0
];
$lastRecord = [
'field' => 'last_record',
'name' => '最后跟进记录',
'form_type' => 'text',
'is_hidden' => 0
];
$lastTime = [
'field' => 'last_time',
'name' => '最后跟进时间',
'form_type' => 'datetime',
'is_hidden' => 0
];
$beforeOwnerUser = [
'field' => 'before_owner_user_id',
'name' => '前负责人',
'form_type' => 'user',
'is_hidden' => 0
];
$intoPoolTime = [
'field' => 'into_pool_time',
'name' => '进入公海时间',
'form_type' => 'datetime',
'is_hidden' => 0
];
$createTime = [
'field' => 'create_time',
'name' => '创建时间',
'form_type' => 'datetime',
'is_hidden' => 0
];
$updateTime = [
'field' => 'update_time',
'name' => '更新时间',
'form_type' => 'datetime',
'is_hidden' => 0
];
$createUser = [
'field' => 'create_user_id',
'name' => '创建人',
'form_type' => 'user',
'is_hidden' => 0
];
array_push($data, $address, $detailAddress, $lastRecord, $lastTime, $createTime, $updateTime, $createUser, $beforeOwnerUser, $intoPoolTime);
return $data;
}
}
/**
* 处理公海规则数据
*
* @param array $rules 规则数据
* @param int $poolId 公海ID
* @author fanqi
* @since 2021-03-30
* @return array
*/
private function getPoolRule($rules, $poolId)
{
$result = [];
foreach ($rules AS $key => $value) {
$result[] = [
'pool_id' => $poolId,
'type' => $value['type'],
'deal_handle' => $value['deal_handle'],
'business_handle' => $value['business_handle'],
'level_conf' => $value['level_conf'],
'level' => json_encode($value['level']),
'limit_day' => !empty($value['limit_day']) ? $value['limit_day'] : 0
];
}
return $result;
}
/**
* 处理公海字段数据
*
* @param array $fields 字段列表
* @param int $poolId 公海ID
* @author fanqi
* @since 2021-03-30
* @return array
*/
private function getPoolField($fields, $poolId)
{
$result = [];
foreach ($fields AS $key => $value) {
$result[] = [
'pool_id' => $poolId,
'name' => $value['name'],
'field_name' => $value['field'],
'form_type' => $value['form_type'],
'is_hidden' => $value['is_hidden']
];
}
return $result;
}
}

@ -16,20 +16,27 @@ class PrintingLogic
/**
* 打印模板列表
*
* @param $page
* @param $limit
* @param array $param : int $page 页码; int $limit 每页记录条数; string $type 打印模板类型
* @author fanqi
* @date 2021-03-26
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function index($page, $limit)
public function index($param)
{
$page = !empty($param['page']) ? $param['page'] : 1;
$limit = !empty($param['limit']) ? $param['limit'] : 500;
$where = !empty($param['type']) ? ['type' => $param['type']] : [];
$result = [];
$type = [1 => '商机', 2 => '合同', 3 => '回款'];
$type = [5 => '商机', 6 => '合同', 7 => '回款'];
$field = ['id', 'name', 'type', 'user_name', 'create_time', 'update_time'];
$count = Db::name('admin_printing')->count();
$data = Db::name('admin_printing')->field($field)->order('id', 'desc')->limit(($page - 1) * $limit, $limit)->select();
$count = Db::name('admin_printing')->where($where)->count();
$data = Db::name('admin_printing')
->field($field)
->where($where)
->order('id', 'desc')
->limit(($page - 1) * $limit, $limit)
->select();
foreach ($data AS $key => $value) {
$result[] = [
@ -63,7 +70,8 @@ class PrintingLogic
'user_name' => $userName,
'name' => $param['name'],
'type' => $param['type'],
'content' => htmlspecialchars($param['content']),
'content' => json_encode(['data' => $param['content']]),
// 'content' => htmlspecialchars($param['content']),
'create_time' => time(),
'update_time' => time()
];
@ -81,7 +89,9 @@ class PrintingLogic
{
$content = Db::name('admin_printing')->where('id', $id)->value('content');
return ['id' => $id, 'content' => htmlspecialchars_decode($content)];
$contentArray = json_decode($content, true);
return ['id' => $id, 'content' => $contentArray['data']];
}
/**
@ -94,7 +104,7 @@ class PrintingLogic
*/
public function update($param)
{
if (!empty($param['content'])) $param['content'] = htmlspecialchars($param['content']);
if (!empty($param['content'])) $param['content'] = json_encode(['data' => $param['content']]);
return Db::name('admin_printing')->update($param);
}
@ -149,7 +159,7 @@ class PrintingLogic
/**
* 获取打印模板需要的字段
*
* @param $type 1商机2合同3回款
* @param $type 5商机6合同7回款
* @return array[]
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
@ -160,31 +170,26 @@ class PrintingLogic
$result = [];
switch ($type) {
case 1:
case 5:
$result['business'] = $this->getBusinessFields();
$result['customer'] = $this->getCustomerFields();
$result['product'] = $this->getProductFields();
$result['customer'] = $this->getCustomerFields(5);
$result['product'] = $this->getProductFields(5);
break;
case 2:
$result['contract'] = $this->getContractFields();
$result['customer'] = $this->getCustomerFields();
case 6:
$result['contract'] = $this->getContractFields(6);
$result['customer'] = $this->getCustomerFields(6);
$result['contacts'] = $this->getContactsFields();
$result['product'] = $this->getProductFields();
$result['product'] = $this->getProductFields(6);
break;
case 3:
$result['receivables'] = $this->getReceivablesFields();
$result['contract'] = $this->getContractFields();
case 7:
$result['receivables'] = $this->getReceivablesFields(7);
$result['contract'] = $this->getContractFields(7);
break;
default:
$result['business'] = $this->getBusinessFields();
$result['customer'] = $this->getCustomerFields();
$result['product'] = $this->getProductFields();
$result['contract'] = $this->getContractFields();
$result['contacts'] = $this->getContactsFields();
$result['receivables'] = $this->getReceivablesFields();
$result[] = [];
}
return $result;
@ -231,7 +236,7 @@ class PrintingLogic
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
private function getCustomerFields()
private function getCustomerFields($type)
{
$result = [];
@ -239,7 +244,8 @@ class PrintingLogic
# 处理自定义字段
foreach ($customerList AS $key => $value) {
if (in_array($value['field'], ['next_time', 'remark'])) continue;
if (in_array($value['field'], ['next_time'])) continue;
if (in_array($type, [5, 6]) && in_array($value['field'], ['deal_status'])) continue;
$result[] = [
'name' => $value['name'],
@ -247,6 +253,12 @@ class PrintingLogic
];
}
# 处理固定字段
if (in_array($type, [5, 6])) {
$result[] = ['name' => '详细地址', 'field' => 'address'];
$result[] = ['name' => '区域', 'field' => 'detail_address'];
}
return $result;
}
@ -258,7 +270,7 @@ class PrintingLogic
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
private function getProductFields()
private function getProductFields($type)
{
$result = [];
@ -266,7 +278,8 @@ class PrintingLogic
# 处理自定义字段
foreach ($productList AS $key => $value) {
if ($value['field'] == 'status') continue;
if (in_array($value['field'], ['status'])) continue;
if (in_array($type, [5, 6]) && in_array($value['field'], ['description'])) continue;
$result[] = [
'name' => $value['name'],
@ -280,6 +293,7 @@ class PrintingLogic
$result[] = ['name' => '折扣', 'field' => 'discount'];
$result[] = ['name' => '整单折扣', 'field' => 'discount_rate'];
$result[] = ['name' => '合计', 'field' => 'subtotal'];
$result[] = ['name' => '产品总金额', 'field' => 'total_price'];
return $result;
}
@ -292,7 +306,7 @@ class PrintingLogic
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
private function getContractFields()
private function getContractFields($type)
{
$result = [];
@ -300,19 +314,23 @@ class PrintingLogic
# 处理自定义字段
foreach ($contractList AS $key => $value) {
if (in_array($type, [6, 7]) && in_array($value['field'], ['customer_id'])) continue;
if ($type == 7 && in_array($value['field'], ['business_id'])) continue;
$result[] = [
'name' => $value['name'],
'field' => $value['field']
];
}
# 处理固定字段
$result[] = ['name' => '负责人', 'field' => 'owner_user_id'];
$result[] = ['name' => '创建人', 'field' => 'create_user_id'];
$result[] = ['name' => '创建日期', 'field' => 'create_time'];
$result[] = ['name' => '更新日期', 'field' => 'update_time'];
$result[] = ['name' => '已收款金额', 'field' => 'received'];
$result[] = ['name' => '未收款金额', 'field' => 'uncollected'];
if (!in_array($type, [7])) {
$result[] = ['name' => '负责人', 'field' => 'create_user_id'];
$result[] = ['name' => '创建人', 'field' => 'owner_user_id'];
$result[] = ['name' => '创建日期', 'field' => 'create_time'];
$result[] = ['name' => '更新日期', 'field' => 'update_time'];
$result[] = ['name' => '已收款金额', 'field' => 'done_money'];
$result[] = ['name' => '未收款金额', 'field' => 'uncollected_money'];
}
return $result;
}
@ -352,7 +370,7 @@ class PrintingLogic
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
private function getReceivablesFields()
private function getReceivablesFields($type)
{
$result = [];
@ -360,6 +378,9 @@ class PrintingLogic
# 处理自定义字段
foreach ($receivablesList AS $key => $value) {
if (in_array($value['field'], ['contract_id'])) continue;
if (in_array($type, [7]) && in_array($value['field'], ['contract_id'])) continue;
$result[] = [
'name' => $value['name'],
'field' => $value['field']

@ -8,6 +8,7 @@
namespace app\admin\logic;
use app\admin\controller\ApiCommon;
use think\Db;
class WorkLogic
@ -58,8 +59,8 @@ class WorkLogic
$param['type'] = 0;
$param['types'] = 7;
$param['system'] = 0;
return Db::name('admin_group')->insert($param);
$data=Db::name('admin_group')->insertGetId($param);
return $data;
}
/**
@ -90,7 +91,18 @@ class WorkLogic
*/
public function updateRole($param)
{
return Db::name('admin_group')->update($param);
$res=Db::name('admin_group')->where('id',$param['id'])->find();
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']);
return $data;
}
}
/**
@ -103,9 +115,9 @@ class WorkLogic
*/
public function deleteRole($id)
{
$system = Db::name('admin_group')->where('id', $id)->value('system');
$system = Db::name('admin_group')->where('id', $id)->find();
if (!empty($system)) return ['status' => false, 'error' => '不允许删除系统默认角色!'];
if (!empty($system['system'])) return ['status' => false, 'error' => '不允许删除系统默认角色!'];
if (!Db::name('admin_group')->where('id', $id)->delete()) return ['status' => false, 'error' => '操作失败!'];
@ -115,7 +127,10 @@ class WorkLogic
db('work')->where('group_id', $id)->update(['group_id' => $readOnlyId]); # 处理公开项目的权限
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']);
return ['status' => true];
}
}

@ -37,7 +37,17 @@ class Config extends Common
{
$data = [];
$data['status'] = $param['status'] ? : '0';
$dataInfo=db('admin_config')->where('id',$param['id'])->find();
$user_id=$param['user_id'];
unset($param['user_id']);
if ($this->where(['id' => $id])->update($data)) {
# 修改记录
if($param['status']==0){
$data='停用了'.$dataInfo['name'];
}else{
$data='启用了'.$dataInfo['name'];
}
SystemActionLog($user_id,'admin_config','application',$id,'update','应用管理','','',$data);
return true;
}
$this->error = '操作失败';

@ -6,6 +6,7 @@
// +----------------------------------------------------------------------
namespace app\admin\model;
use app\admin\controller\ApiCommon;
use think\Db;
use app\admin\model\Common;
use think\Request;
@ -52,7 +53,7 @@ class ExamineFlow extends Common
$list = $list_view
->page($request['page'], $request['limit'])
->field('examine_flow.*,user.realname,user.thumb_img')
->order('examine_flow.update_time', 'desc')
->order('examine_flow.status desc,examine_flow.update_time desc')
->select();
foreach ($list as $k=>$v) {
$list[$k]['user_ids_info'] = $userModel->getListByStr($v['user_ids']);

@ -55,16 +55,22 @@ class ExamineRecord extends Common
}
$result = [];
# 获取创建者信息(业务审批)
if (in_array($param['types'], ['crm_contract', 'crm_receivables', 'crm_invoice'])) {
$model = db($param['types']);
$primaryKey = null;
if ($param['types'] == 'crm_contract') $primaryKey = 'contract_id';
if ($param['types'] == 'crm_receivables') $primaryKey = 'receivables_id';
if ($param['types'] == 'crm_invoice') $primaryKey = 'invoice_id';
# 获取创建者信息(办公审批)
if ($param['types'] == 'oa_examine' && !empty($param['is_record'])) {
$info = db('oa_examine')->field(['create_time', 'create_user_id'])->where('examine_id', $param['types_id'])->find();
$userInfo = $userModel->getUserById($info['create_user_id']);
$info = $model->field(['create_time', 'owner_user_id'])->where($primaryKey, $param['types_id'])->find();
$userInfo = $userModel->getUserById($info['owner_user_id']);
$result[] = [
'check_date' => date('Y-m-d H:i:s', $info['create_time']),
'check_time' => $info['create_time'],
'check_user_id' => $info['create_user_id'],
'check_user_id' => $info['owner_user_id'],
'check_user_id_info' => $userInfo,
'content' => '',
'flow_id' => 0,
@ -75,23 +81,20 @@ class ExamineRecord extends Common
'types' => $param['types'],
'types_id' => $param['types_id']
];
}
# 获取创建者信息(业务审批)
if (in_array($param['types'], ['crm_contract', 'crm_receivables', 'crm_invoice']) && !empty($param['is_record'])) {
$model = db($param['types']);
$primaryKey = null;
if ($param['types'] == 'crm_contract') $primaryKey = 'contract_id';
if ($param['types'] == 'crm_receivables') $primaryKey = 'receivables_id';
if ($param['types'] == 'crm_invoice') $primaryKey = 'invoice_id';
$info = $model->field(['create_time', 'owner_user_id'])->where($primaryKey, $param['types_id'])->find();
$userInfo = $userModel->getUserById($info['owner_user_id']);
}else{
unset($param['action']);
# 获取创建者信息(办公审批)
$info = db('oa_examine')->field(['create_time', 'create_user_id','update_time,check_status'])->where('examine_id', $param['types_id'])->find();
$userInfo = $userModel->getUserById($info['create_user_id']);
#撤销之后修改再次审批 审批流程过滤之前的审批记录
if($info['check_status']<2){
$param['check_time']=['>',$info['update_time']?:$info['create_time']];
}
$result[] = [
'check_date' => date('Y-m-d H:i:s', $info['create_time']),
'check_time' => $info['create_time'],
'check_user_id' => $info['owner_user_id'],
'check_user_id' => $info['create_user_id'],
'check_user_id_info' => $userInfo,
'content' => '',
'flow_id' => 0,
@ -102,9 +105,13 @@ class ExamineRecord extends Common
'types' => $param['types'],
'types_id' => $param['types_id']
];
}
unset($param['is_record']);
# 多次撤销使用 只显示最后一次撤销数据条件 is_end 0
$param['is_end']=0;
$list = db('admin_examine_record')->where($param)->order('check_time asc')->select();
foreach ($list as $k=>$v) {
$list[$k]['check_user_id_info'] = $userModel->getUserById($v['check_user_id']);

@ -320,11 +320,11 @@ class ExamineStep extends Common
//创建人或负责人或管理员有撤销权限
//if ($dataInfo['create_user_id'] == $check_user_id || $dataInfo['owner_user_id'] == $check_user_id || in_array($check_user_id, $admin_user_ids)) {
if ($dataInfo['create_user_id'] == $check_user_id || $dataInfo['owner_user_id'] == $check_user_id) {
if (!in_array($dataInfo['check_status'],['2','3','4'])) {
if (!in_array($dataInfo['check_status'],['2','3','4','6'])) {
$is_recheck = 1;
}
}
if (in_array($check_user_id, stringToArray($dataInfo['check_user_id'])) && !in_array($dataInfo['check_status'],['2','3','4'])) {
if (in_array($check_user_id, stringToArray($dataInfo['check_user_id'])) && !in_array($dataInfo['check_status'],['2','3','4','6'])) {
$is_check = 1;
}
@ -468,21 +468,22 @@ class ExamineStep extends Common
$where['types_id'] = $types_id;
$where['is_end'] = 0;
$recordList = $examineRecordModel->getDataList($where);
$typeInfo = $this->getDataByTypes($types, $types_id);
$dataInfo = $typeInfo['dataInfo'];
$createUserInfo = $userModel->getUserById($dataInfo['create_user_id']);
$userList[0]['userInfo'] = $createUserInfo;
$userList[0]['type'] = 3; //创建
$userList[0]['time'] = $dataInfo['update_time'] ? : '';
//type 0失败1通过2撤销3创建4待审核5未提交
$i = 1;
foreach ($recordList as $k=>$v) {
$userList[$i]['userInfo'] = $userModel->getUserById($v['check_user_id']);
$userList[$i]['type'] = $v['status'];
$userList[$i]['time'] = $v['check_time'];
$i++;
$i = 0;
if(empty($recordList)){
$createUserInfo = $userModel->getUserById($dataInfo['create_user_id']);
$userList[0]['userInfo'] = $createUserInfo;
$userList[0]['type'] = 3; //创建
$userList[0]['time'] = $dataInfo['update_time'] ? : '';
}else{
foreach ($recordList as $k=>$v) {
$userList[$i]['userInfo'] = $userModel->getUserById($v['check_user_id']);
$userList[$i]['type'] = $v['status'];
$userList[$i]['time'] = $v['check_time'];
$i++;
}
}
if ($dataInfo['check_status'] <= 1 && $dataInfo['check_user_id']) {
$check_user_id_arr = stringToArray($dataInfo['check_user_id']);
@ -502,11 +503,11 @@ class ExamineStep extends Common
//创建人或负责人或管理员有撤销权限
// if ($dataInfo['create_user_id'] == $check_user_id || $dataInfo['owner_user_id'] == $check_user_id || in_array($check_user_id, $admin_user_ids)) {
if ($dataInfo['create_user_id'] == $check_user_id || $dataInfo['owner_user_id'] == $check_user_id) {
if (!in_array($dataInfo['check_status'],['2','3','4','5'])) {
if (!in_array($dataInfo['check_status'],['2','3','4','5','6'])) {
$is_recheck = 1;
}
}
if (in_array($check_user_id, stringToArray($dataInfo['check_user_id'])) && !in_array($dataInfo['check_status'],['2','3','4','5'])) {
if (in_array($check_user_id, stringToArray($dataInfo['check_user_id'])) && !in_array($dataInfo['check_status'],['2','3','4','5','6'])) {
$is_check = 1;
}

@ -13,7 +13,7 @@ use app\work\model\Task;
use com\PseudoQueue as Queue;
use think\Cache;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\cache\driver\Redis;
class Excel extends Common
{
/**
@ -72,7 +72,7 @@ class Excel extends Common
public function excelImportDownload($field_list, $types, $save_path = '')
{
$fieldModel = new \app\admin\model\Field();
//实例化主文件
$objPHPExcel = new Spreadsheet();
$objProps = $objPHPExcel->getProperties(); // 设置excel文档的属性
@ -86,7 +86,7 @@ class Excel extends Common
$objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet
$objActSheet = $objPHPExcel->getActiveSheet();
$objActSheet->setTitle('导入模板' . date('Y-m-d', time())); //设置sheet的标题
//存储Excel数据源到其他工作薄
$objPHPExcel->createSheet();
$subObject = $objPHPExcel->getSheet(1);
@ -121,11 +121,13 @@ class Excel extends Common
}
} else {
$objActSheet->getColumnDimension($this->stringFromColumnIndex($k))->setWidth(20); //设置单元格宽度
if ($field['form_type'] == 'select' || $field['form_type'] == 'checkbox' || $field['form_type'] == 'radio' || $field['form_type'] == 'category') {
if ($field['form_type'] == 'select' || $field['form_type'] == 'checkbox' || $field['form_type'] == 'radio' || $field['form_type'] == 'category' || $field['form_type']=='user') {
//产品类别
if ($field['form_type'] == 'category' && $field['types'] == 'crm_product') {
$setting = db('crm_product_category')->order('pid asc')->column('name');
} else {
} elseif($field['form_type']=='user' && $field['field'] == 'owner_user_id') {
$setting = db('admin_user')->order('id asc')->column('realname');
}else{
$setting = $field['setting'] ?: [];
}
$select_value = implode(',', $setting);
@ -554,16 +556,16 @@ 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");
vendor("phpexcel.PHPExcel.Writer.Excel5");
@ -647,10 +649,16 @@ 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);
}
$field_list = array_map(function ($val) {
if (method_exists($val, 'toArray')) {
return $val->toArray();
@ -659,6 +667,40 @@ 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);
@ -675,6 +717,7 @@ 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']
@ -725,20 +768,31 @@ class Excel extends Common
// 数据重复时的处理方式 0跳过 1覆盖
$config = $param['config'] ?: 0;
// 默认数据
$default_data = [
'create_user_id' => $param['create_user_id'],
'owner_user_id' => $param['owner_user_id'],
'create_time' => time(),
'update_time' => time(),
];
if(!empty($param['pool_id'])){
//公海导入
$default_data = [
'create_user_id' => $param['create_user_id'],
'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, '请使用最新导入模板');
$error_data_func($val, '请使用最新导入模板1');
}
$objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
$objWriter->save($error_path);
@ -833,22 +887,26 @@ class Excel extends Common
$old_data_id_list = $dataModel->whereOr($unique_where)->column($db_id);
}
}
#下次升级
// if(empty($param['pool_id'])){
// $user_id=db('admin_user')->where('realname',$val[2])->value('id');
// $data['owner_user_id']=$user_id?: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 ($old_data_id_list) {
// 是否覆盖
if (!empty($old_data_id_list) && empty($param['pool_id'])) {
if ($config) {
$data = array_merge($data, $default_data);
$data['user_id'] = $param['create_user_id'];
$data['update_time'] = time();
$data['create_user_id'] = $param['create_user_id'];
$data['update_time'] = time();
$dataModel->startTrans();
try {
$up_success_count = 0;
foreach ($old_data_id_list as $id) {
if ($types == 'crm_customer') {
$owner = db('crm_customer')->where(['name' => $data['name']])->find();
if (!empty($owner) && $owner['owner_user_id'] == 0) {
$temp_error = $owner['name'] . ' ' . '公海数据,无覆盖权限';
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;
}
@ -886,11 +944,21 @@ 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 {
$data = array_merge($data, $default_data);
if (!$resData = $dataModel->createData($data)) {
$error_data_func($val, $dataModel->getError());
if ($types == 'crm_customer') {
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);
if (!$resData = $dataModel->createData($data)) {
$error_data_func($val, $dataModel->getError());
}
}
}
}
@ -933,6 +1001,7 @@ class Excel extends Common
'error' => $error
]);
// 执行完成
$redis= new Redis();
if ($done >= $total) {
// 出队
$queue->dequeue();
@ -955,6 +1024,9 @@ class Excel extends Common
'user_id' => $user_id,
'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
]);
Cache::rm('item');
Cache::rm('excel_item');
Cache::set('item', 1, config('import_cache_time'));
Cache::set('excel_item', serialize($this->error), config('import_cache_time'));
} else {
@ -969,6 +1041,8 @@ class Excel extends Common
$excelData['config'] = $config;
$excelData['owner_user_id'] = $user_id;
$excelData['base'] = 'batchImportData';
Cache::rm('item');
Cache::rm('excel');
Cache::set('item', 0, config('import_cache_time'));
Cache::set('excel', $excelData, config('import_cache_time'));
}
@ -1701,8 +1775,8 @@ class Excel extends Common
}
// 将标题名称通过fputcsv写到文件句柄
fputcsv($fp, $title_cell);
$export_data = $callback(0);
foreach ($export_data as $item) {
// $export_data = $callback(0);
foreach ($callback as $item) {
$rows = [];
foreach ($field_list as $rule) {
$rows[] = $item[$rule['field']];
@ -1727,7 +1801,7 @@ class Excel extends Common
*
* @author Ymob
*/
public function batchTaskImportData($file,$field_list, $param, $controller = null)
public function batchTaskImportData($file, $field_list, $param, $controller = null)
{
// 导入模块
$types = $param['types'];
@ -1892,8 +1966,8 @@ class Excel extends Common
// return false;
}
// 开始行 +3 跳过表头
$start_row = ($page - 1) * $page_size + 3;
// 开始行 +2 跳过表头
$start_row = ($page - 1) * $page_size + 2;
// 结束行
$end_row = $start_row + $page_size - 1;
if ($end_row > $max_row) {
@ -2075,12 +2149,13 @@ class Excel extends Common
$objActSheet = $objPHPExcel->getActiveSheet(0);
$objPHPExcel->getActiveSheet()->mergeCells('A1:' . $cellKey[count($field_list) - 1] . '1');//合并单元格(如果要拆分单元格是需要先合并再拆分的,否则程序会报错)
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $title);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(18);//所有单元格(行)默认高度
$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(16);
$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::VERTICAL_CENTER);
$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);
$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');
@ -2088,10 +2163,12 @@ class Excel extends Common
foreach ($field_list as $k => $v) {
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellKey[$k] . $topNumber, $v['name']);//设置表头数据
$objPHPExcel->getActiveSheet()->freezePane($cellKey[$k] . ($topNumber + 1));//冻结窗口
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getFont()->setBold(true);//设置是否加粗
$objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_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()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
$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);
if ($v[3] > 0)//大于0表示需要设置宽度
{
$objPHPExcel->getActiveSheet()->getColumnDimension($cellKey[$k])->setWidth($v[3]);//设置列宽度
@ -2153,12 +2230,13 @@ class Excel extends Common
$objActSheet = $objPHPExcel->getActiveSheet(0);
$objPHPExcel->getActiveSheet()->mergeCells('A1:' . $cellKey[count($field_list) - 1] . '1');//合并单元格(如果要拆分单元格是需要先合并再拆分的,否则程序会报错)
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $title);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(18);//所有单元格(行)默认高度
$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(16);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
$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::VERTICAL_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');
@ -2166,11 +2244,13 @@ class Excel extends Common
foreach ($field_list as $k => $v) {
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellKey[$k] . $topNumber, $v['name']);//设置表头数据
$objPHPExcel->getActiveSheet()->freezePane($cellKey[$k] . ($topNumber + 1));//冻结窗口
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
$objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getFont()->setBold(true);//设置是否加粗
$objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
$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()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
if ($v[3] > 0)//大于0表示需要设置宽度
{
@ -2189,8 +2269,8 @@ class Excel extends Common
$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()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_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::HORIZONTAL_LEFT);
$objPHPExcel->getActiveSheet()->setCellValue($cellKey[$key] . ($k + 1 + $topNumber), $item[$rule['field']]);
}
}
@ -2233,25 +2313,28 @@ class Excel extends Common
$objActSheet = $objPHPExcel->getActiveSheet(0);
$objPHPExcel->getActiveSheet()->mergeCells('A1:M1');//合并单元格(如果要拆分单元格是需要先合并再拆分的,否则程序会报错)
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $title);
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(18);//所有单元格(行)默认高度
$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
// 设置字体
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(16);
$objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$objActSheet->getStyle('A1:M1')->getFont()->getColor()->setARGB('FF000000');
$objActSheet->getStyle('A1:M1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
//处理表头
$objPHPExcel->getActiveSheet()->freezePane('A2');//冻结窗口
// 设置字体为
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
$objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);//设置是否加粗
$objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
$objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//垂直居中
$objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//文字居中
$objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//文字居中
$objActSheet->getStyle('A2:M2')->getFont()->getColor()->setARGB('FF000000');
$objActSheet->getStyle('A2:M2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
@ -2299,6 +2382,7 @@ class Excel extends Common
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); //excel5为xls格式excel2007为xlsx格式
$objWriter->save('php://output');
}
/**
* 运行中
* @param $param
@ -2319,7 +2403,7 @@ class Excel extends Common
} elseif ($param == 1) {
$data = '';
}
return $data;
}
@ -2377,4 +2461,466 @@ class Excel extends Common
return $data;
}
/**
* 跟进记录导入
* @param $file 文件
* @param $param 数据
* @param $field_list 导入字段
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/9 0009 16:31
*/
public function ActivityImport($file,$field_list,$param,$controller = null)
{
// 导入模块
$types = $param['types'];
if (!in_array($types, $this->types_arr)) {
$this->error = '参数错误!';
$queue->dequeue();
return false;
}
// 采用伪队列 允许三人同时导入数据
$queue = new Queue(self::IMPORT_QUEUE, 30000);
$import_queue_index = input('import_queue_index');
// 队列任务ID
if (!$import_queue_index) {
if (!$import_queue_index = $queue->makeTaskId()) {
$this->error = $queue->error;
$queue->dequeue();
return false;
}
} else {
if (!$queue->setTaskId($import_queue_index)) {
$this->error = $queue->error;
$queue->dequeue();
return false;
}
}
// 取消导入
if ($param['page'] == -1) {
@unlink(UPLOAD_PATH . $param['temp_file']);
$this->error = [
'msg' => '导入已取消',
'page' => -1
];
if ($param['error']) {
$this->error['error_file_path'] = 'temp/' . $param['error_file'];
} else {
@unlink(TEMP_DIR . $param['error_file']);
}
$temp = $queue->cache('last_import_cache');
(new ImportRecord())->createData([
'type' => $types,
'total' => $temp['total'],
'done' => $temp['done'],
'cover' => $temp['cover'],
'error' => $temp['error'],
'error_data_file_path' => $temp['error'] ? 'temp/' . $error_data_file_name : ''
]);
$queue->dequeue();
return true;
}
if (!empty($file) || $param['temp_file']) {
// 导入初始化 上传文件
if (!empty($file)) {
$save_name = $this->upload($file);
if ($save_name === false) {
$queue->dequeue();
return false;
}
} else {
$save_name = $param['temp_file'];
}
// 文件类型
$ext = pathinfo($save_name, PATHINFO_EXTENSION);
// 文件路径
$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;
}
// 加载类库
vendor("phpexcel.PHPExcel");
vendor("phpexcel.PHPExcel.Writer.Excel5");
vendor("phpexcel.PHPExcel.Writer.Excel2007");
vendor("phpexcel.PHPExcel.IOFactory");
// 错误数据临时文件路径 错误数据开始行数
if ($param['error_file']) {
$error_path = TEMP_DIR . $param['error_file'];
$error_row = $param['error'] + 3;
$cover = $param['cover'] ?: 0;
} else {
// 生成临时文件名称
$error_path = tempFileName($ext);
// 将导入模板保存至临时路径
$controller->excelDownload($error_path);
$error_row = 3;
$cover = 0;
}
// 错误数据临时文件名称 相对于临时目录
$error_data_file_name = \substr($error_path, strlen(TEMP_DIR));
// 加载错误数据文件
$err_PHPExcel = \PHPExcel_IOFactory::load($error_path);
$error_sheet = $err_PHPExcel->setActiveSheetIndex(0);
/**
* 添加错误数据到临时文件
*
* @param array $data 原数据
* @param string $error 错误原因
* @return void
*/
$error_data_func = function ($data, $error) use ($error_sheet, &$error_row) {
foreach ($data as $key => $val) {
// 第一列为错误原因 所以+1
$error_col = \PHPExcel_Cell::stringFromColumnIndex($key + 1);
$error_sheet->setCellValue($error_col . $error_row, $val);
}
$error_sheet->setCellValue('A' . $error_row, $error);
$error_sheet->getStyle('A' . $error_row)->getFont()->getColor()->setARGB('FF000000');
$error_sheet->getStyle('A' . $error_row)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFFF0000');
$error_row++;
};
// 加载导入数据文件
$objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
$objRender->setReadDataOnly(true);
$ExcelObj = $objRender->load($save_path);
// 指定工作表
$sheet = $ExcelObj->getSheet(0);
// 总行数
$max_row = $sheet->getHighestRow();
// 最大列数
$max_col_num = count($field_list) - 1;
$max_col_num += 3 * array_count_values(array_column($field_list, 'form_type'))['map_address'];
$max_col = \PHPExcel_Cell::stringFromColumnIndex($max_col_num);
// 每次导入条数
$page_size = 100;
// 当前页码
$page = ((int)$param['page']) ?: 1;
// 数据总数
$total = $max_row - 2;
// 总页数
$max_page = ceil($total / $page_size);
if ($page > $max_page) {
// $this->error = 'page参数错误';
// @unlink($save_path);
// $queue->dequeue();
// return false;
}
// 开始行 +3 跳过表头
$start_row = ($page - 1) * $page_size + 3;
// 结束行
$end_row = $start_row + $page_size - 1;
if ($end_row > $max_row) {
$end_row = $max_row;
}
// 读取数据
$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;
break;
case 'crm_contract':
$db = db('crm_contract');
$db_id = 'contract_id';
$activity_type=6;
break;
case 'crm_leads' :
$dataModel = new \app\crm\model\Leads();
$db = db('crm_leads');
$db_id = 'leads_id';
$activity_type=1;
break;
case 'crm_customer' :
$dataModel = new \app\crm\model\Customer();
$db = db('crm_customer');
$db_id = 'customer_id';
$fieldParam['form_type'] = ['not in', ['file', 'form', 'user', 'structure']];
$activity_type=2;
break;
case 'crm_contacts' :
$dataModel = new \app\crm\model\Contacts();
$db = db('crm_contacts');
$db_id = 'contacts_id';
$activity_type=3;
break;
}
// 开始导入数据
foreach ($dataList as $val) {
$fk = 0;
$data = [];
foreach ($field_list as $field) {
$temp_value = trim($val[$fk]);
// 特殊字段特殊处理
// $temp_value = $this->handleData($temp_value, $field);
$data[$field['field']] = $temp_value;
if ($temp_value == '') {
if ($field['is_null']) {
$not_null_field[] = $field['name'];
}
$empty_count++;
}
$fk++;
}
if (!empty($not_null_field)) {
$error_data_func($val, implode(', ', $not_null_field) . '不能为空');
continue;
}
if ($empty_count == count($field_list)) {
$error_data_func($val, '空行');
continue;
}
$activityLogic = new \app\crm\logic\ActivityLogic();
$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].'不存在');
continue;
}
if (empty($userData)) {
$error_data_func($val, '管理员'.$val[1].'不存在');
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);
$data['user_id']=$userData;
$data['activity_type_id'] = $customerData;
$data['activity_type'] = $activity_type;
unset($data['create_user_id']);
if (!$resData = $activityLogic->save($data)) {
$error_data_func($val, $dataModel->getError());
}
}
}
// 完成数(已导入数)
$done = ($page - 1) * $page_size + count($dataList);
if ($page == $max_page) {
$done = $total;
}
// 错误数
$error = $error_row - 3;
// 错误数据文件保存
$objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
$objWriter->save($error_path);
$this->error = [
// 数据导入文件临时路径
'temp_file' => $save_name,
// 错误数据文件路径
'error_file' => $error_data_file_name,
// 文件总计条数
'total' => $total,
// 已完成条数
'done' => $done,
// 覆盖
'cover' => $cover,
// 错误数据写入行号
'error' => $error,
// 下次页码
'page' => $page + 1,
// 导入任务ID
'import_queue_index' => $import_queue_index
];
$queue->cache('last_import_cache', [
'total' => $total,
'done' => $done,
'cover' => $cover,
'error' => $error
]);
// 执行完成
if ($done >= $total) {
// 出队
$queue->dequeue();
// 错误数据文件路径
$this->error['error_file_path'] = 'temp/' . $error_data_file_name;
// 删除导入文件
@unlink($save_path);
// 没有错误数据时,删除错误文件
if ($error == 0) {
@unlink($error_path);
}
(new ImportRecord())->createData([
'type' => $types,
'total' => $total,
'done' => $done,
'cover' => $cover,
'error' => $error,
'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
]);
Cache::set('item', 1, config('import_cache_time'));
Cache::set('excel_item', serialize($this->error), config('import_cache_time'));
} else {
$excelData['cover'] = $cover;
$excelData['page'] = $page + 1;
$excelData['types'] = $types;
$excelData['temp_file'] = $save_name;
$excelData['error_file'] = $error_data_file_name;
$excelData['create_user_id'] = $param['create_user_id'];
$excelData['import_queue_index'] = $import_queue_index;
$excelData['total'] = $total;
$excelData['done'] = $done;
$excelData['error'] = $error;
$excelData['base'] = 'ActivityImport';
Cache::set('item', 0, config('import_cache_time'));
Cache::set('excel', $excelData, config('import_cache_time'));
}
return true;
} else {
$this->error = '请选择导入文件';
$queue->dequeue();
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');
}
}
}

@ -45,13 +45,15 @@ class Field extends Model
'field' => 'last_record',
'name' => '最后跟进记录',
'form_type' => 'text',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'last_time',
'name' => '最后跟进时间',
'form_type' => 'datetime',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
],
'crm_customer' => [
@ -59,25 +61,29 @@ class Field extends Model
'field' => 'last_record',
'name' => '跟进记录',
'form_type' => 'text',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'last_time',
'name' => '最后跟进时间',
'form_type' => 'datetime',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'address',
'name' => '省、市、区/县',
'form_type' => 'customer_address',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'detail_address',
'name' => '详细地址',
'form_type' => 'text',
'width' => ''
'width' => '',
'is_hidden' => 0,
]
],
'crm_contacts' => [
@ -85,13 +91,15 @@ class Field extends Model
'field' => 'last_record',
'name' => '跟进记录',
'form_type' => 'text',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'last_time',
'name' => '最后跟进时间',
'form_type' => 'datetime',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
],
'crm_business' => [
@ -99,13 +107,15 @@ class Field extends Model
'field' => 'last_record',
'name' => '跟进记录',
'form_type' => 'text',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'last_time',
'name' => '最后跟进时间',
'form_type' => 'datetime',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
],
'crm_contract' => [
@ -113,31 +123,36 @@ class Field extends Model
'field' => 'check_status',
'name' => '审核状态',
'form_type' => 'text',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'last_record',
'name' => '跟进记录',
'form_type' => 'text',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'last_time',
'name' => '最后跟进时间',
'form_type' => 'datetime',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'done_money',
'name' => '已回款',
'form_type' => 'floatnumber',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'un_money',
'name' => '未回款',
'form_type' => 'floatnumber',
'width' => ''
'width' => '',
'is_hidden' => 0,
]
],
'crm_receivables' => [
@ -145,13 +160,15 @@ class Field extends Model
'field' => 'check_status',
'name' => '审核状态',
'form_type' => 'text',
'width' => ''
'width' => '',
'is_hidden' => 0,
],
[
'field' => 'contract_money',
'name' => '合同金额',
'form_type' => 'floatnumber',
'width' => ''
'width' => '',
'is_hidden' => 0,
]
]
@ -211,6 +228,16 @@ class Field extends Model
return false;
}
# 公海数据
$poolList = [];
$poolData = [];
if ($types == 'crm_customer') {
$poolList = db('crm_customer_pool')->column('pool_id');
}
# 用户自定义字段
$userFields = db('admin_user_field')->field(['id', 'datas'])->where('types', $types)->select();
$error_message = [];
$i = 0;
foreach ($param as $k => $data) {
@ -270,9 +297,21 @@ class Field extends Model
} else {
$resField = $this->data($data)->allowField(true)->save();
}
# 处理公海字段数据
if ($types == 'crm_customer') {
foreach ($poolList AS $k1 => $poolId) {
$poolData[] = [
'pool_id' => $poolId,
'name' => $data['name'],
'field_name' => $data['field'],
'form_type' => $data['form_type'],
'is_hidden' => 1
];
}
}
if ($types !== 'oa_examine') {
if ($resField) {
actionLog($this->field_id, '', '', ''); //操作日志
$this->tableName = $types;
$maxlength = '255';
$defaultvalue = $data['default_value'] ? "DEFAULT '" . $data['default_value'] . "'" : "DEFAULT NULL";
@ -324,12 +363,30 @@ class Field extends Model
$this->where(['field_id' => $this->field_id])->delete();
$error_message[] = $data['name'] . ',添加失败';
}
# 处理用户自定义字段数据
if ($resData !== false && !empty($userFields)) {
foreach ($userFields AS $key => $value) {
$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']);
}
}
} else {
$error_message[] = $data['name'] . ',添加失败';
}
}
}
}
# 更新用户自定义字段
if (!empty($userFields)) {
foreach ($userFields AS $key => $value) {
db('admin_user_field')->where('id', $value['id'])->update(['datas' => $value['datas']]);
}
}
# 更新公海字段
if (!empty($poolData)) {
db('crm_customer_pool_field_setting')->insertAll($poolData);
}
if ($error_message) {
$this->error = implode(';', $error_message);
return false;
@ -374,13 +431,21 @@ class Field extends Model
* @return [array]
* @author Michael_xu
*/
public function updateDataById($param)
public function updateDataById($param, $types = '')
{
$error_message = [];
if (!is_array($param)) {
$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) {
$oldData[$value['field']] = $value['name'];
}
}
$i = 0;
foreach ($param as $data) {
$i++;
@ -419,7 +484,11 @@ class Field extends Model
$resField = db('admin_field')->where(['field_id' => $field_id])->update($data);
if ($dataInfo['types'] !== 'oa_examine') {
if ($resField) {
actionLog($field_id); //操作日志
# 更新公海字段
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']]);
}
//actionLog($field_id); //操作日志
$this->tableName = $dataInfo['types'];
$maxlength = '255';
$defaultvalue = $data['default_value'] ? "DEFAULT '" . $data['default_value'] . "'" : "DEFAULT NULL";
@ -486,11 +555,13 @@ class Field extends Model
* @param $types 分类
* @author Michael_xu
*/
public function delDataById($ids)
public function delDataById($ids, $types = '')
{
if (!is_array($ids)) {
$ids[] = $ids;
}
# 删除公海字段的条件
$poolWhere = [];
$delMessage = [];
foreach ($ids as $id) {
$dataInfo = [];
@ -545,12 +616,19 @@ class Field extends Model
$resScene = $sceneModel->updateData($data, $val['scene_id']);
}
}
# 处理删除公海字段的条件
if (!empty($types) && $types == 'crm_customer' && !empty($dataInfo['field'])) $poolWhere[] = $dataInfo['field'];
} else {
$delMessage[] = $dataInfo['name'] . ',删除失败';
}
}
}
}
# 删除公海字段
if (!empty($poolWhere)) {
db('crm_customer_pool_field_setting')->whereIn('field_name', $poolWhere)->delete();
}
return $delMessage ? implode(';', $delMessage) : '';
}
@ -623,7 +701,7 @@ class Field extends Model
$types = 'crm_customer_pool';
}
if ($param['action'] == 'excel') {
$map['form_type'] = array('not in', ['file', 'form', 'user', 'structure']);
$map['form_type'] = array('not in', ['file', 'form','deal_status']);//删除了过滤structure user字段类型数据 添加deal_status
} elseif ($param['action'] == 'index') {
$map['form_type'] = array('not in', ['file', 'form']);
}
@ -631,9 +709,7 @@ class Field extends Model
$order = 'order_id asc, field_id asc';
if ($param['action'] == 'index' || $param['action'] == 'pool') {
$field_list = $this->getIndexFieldConfig($types, $param['user_id']);
// $order = new \think\db\Expression('field(field_id,'..')');
foreach ($field_list as $k => $v) {
# 处理字段授权
$field_list[$k]['writeStatus'] = 1;
if (!$userLevel && $param['module'] == 'crm' && !empty($grantData[$param['types']])) {
@ -650,8 +726,63 @@ class Field extends Model
}
}
# 客户模块增加锁定状态、距进入公海天数字段
if (!$userLevel && $param['types'] == 'crm_customer' && !empty($grantData[$param['types']])) {
$poolDayStatus = getFieldGrantStatus('pool_day', $grantData[$param['types']]);
if (!empty($poolDayStatus['read'])) {
$field_list[] = [
'field' => 'pool_day',
'name' => '距进入公海天数',
'form_type' => 'text',
'writeStatus' => 0,
'fieldName' => 'pool_day'
];
}
$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
];
}
}
if ($userLevel) {
$field_list[] = [
'field' => 'pool_day',
'name' => '距进入公海天数',
'form_type' => 'text',
'writeStatus' => 0,
'fieldName' => 'pool_day'
];
$field_list[] = [
'field' => "is_lock",
'fieldName' => "is_lock",
'form_type' => "text",
'name' => "锁定状态",
'writeStatus' => 0
];
}
} else {
$field_list = $this->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();
$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();
# 详情页面增加负责人字段
if ($param['action'] == 'read' && !in_array($param['types'], ['crm_visit', 'crm_product','oa_examine'])) {
$field_list[] = [
'field' => 'owner_user_id',
'name' => '负责人',
'form_type' => 'user',
'writeStatus' => 0,
'fieldName' => 'owner_user_name',
'value' => $dataInfo['owner_user_name'],
];
}
//客户
if (in_array($param['types'], ['crm_customer'])) {
@ -693,17 +824,17 @@ class Field extends Model
$status = getFieldGrantStatus($v['field'], $grantData[$param['types']]);
# 查看权限
if ($status['read'] == 0) {
if (empty($status['read'])) {
unset($field_list[(int)$k]);
continue;
}
# 编辑权限
$field_list[$k]['writeStatus'] = $status['write'];
if ($param['action'] != 'save') $field_list[$k]['writeStatus'] = $status['write'];
}
# (联系人,商机,合同,回款,回访)关联其他模块的字段在详情页面不允许修改;创建人、负责人不允许修改
if ($param['action'] == 'read' && in_array($v['field'], ['customer_id', 'business_id', 'contacts_id', 'contract_id', 'create_user_id', 'owner_user_id'])) {
if ($param['action'] == 'read' && in_array($v['field'], ['customer_id', 'business_id', 'contacts_id', 'contract_id', 'create_user_id', 'owner_user_id', 'plan_id'])) {
$field_list[$k]['writeStatus'] = 0;
}
@ -978,18 +1109,32 @@ class Field extends Model
}
/**
* [validateField 自定义字段验证规则]
* @param
* @author Michael_xu
* 自定义字段验证规则
* @param string $types 类型crm_customer crm_business ...
* @param int $types_id 自定义表types_id
* @param string $action 操作save update
* @return array
*/
public function validateField($types, $types_id = 0)
public function validateField($types, $types_id = 0, $action = 'save')
{
$apiCommon = new ApiCommon();
$userId = $apiCommon->userInfo['id'];
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
$unField = ['update_time', 'create_time', 'create_user_id', 'owner_user_id'];
$fieldList = $this->where(['types' => ['in', ['', $types]], 'types_id' => $types_id, 'field' => ['not in', $unField], 'form_type' => ['not in', ['checkbox', 'user', 'structure', 'file']]])->field('field,name,form_type,is_unique,is_null,max_length')->select();
$validateArr = [];
$rule = [];
$message = [];
foreach ($fieldList as $field) {
# 字段授权
if (!$userLevel && !empty($grantData[$types])) {
$status = getFieldGrantStatus($field['field'], $grantData[$types]);
# 没有字段查看权限或者编辑时没有字段修改权限就跳过验证
if (empty($status['read']) || ($action != 'save' && empty($status['write']))) continue;
}
$rule_value = '';
$scene_value = '';
@ -1532,25 +1677,33 @@ class Field extends Model
}
/**
* 获取发票高级搜索字段
* 处理字段别名、权限
*
* @return array[]
* @param int $userId 用户ID
* @param string $types 模块类型
* @param string $action 行为
* @param array $data 字段数据
* @author fanqi
* @since 2021-04-06
* @return array
*/
private function getInvoiceSearch()
public function resetField($userId, $types, $action, $data)
{
return [
['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' => '负责人']
];
}
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
public function resetField($types, $data)
{
foreach ($data AS $key => $value) {
# 处理字段授权
if (!$userLevel && !empty($grantData[$types])) {
$status = getFieldGrantStatus($value['field'], $grantData[$types]);
# 查看权限
if ($status['read'] == 0) {
unset($data[(int)$key]);
continue;
}
}
switch ($value['field']) {
case 'create_user_id' :
$data[$key]['fieldName'] = 'create_user_name';
@ -1592,185 +1745,76 @@ class Field extends Model
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 ($types == 'crm_leads') {
// foreach ($data as $key => $value) {
// switch ($value['field']) {
// case 'create_user_id' :
// $data[$key]['fieldName'] = 'create_user_name';
// break;
// case 'owner_user_id' :
// $data[$key]['fieldName'] = 'owner_user_name';
// break;
// default :
// $data[$key]['fieldName'] = $value['field'];
// }
// }
// }
# 客户
// if ($types == 'crm_customer') {
// foreach ($data as $key => $value) {
// switch ($value['field']) {
// case 'create_user_id' :
// $data[$key]['fieldName'] = 'create_user_name';
// break;
// case 'owner_user_id' :
// $data[$key]['fieldName'] = 'owner_user_name';
// break;
// default :
// $data[$key]['fieldName'] = $value['field'];
// }
// }
// }
# 联系人
// if ($types == 'crm_contacts') {
// foreach ($data as $key => $value) {
// switch ($value['field']) {
// case 'customer_id' :
// $data[$key]['fieldName'] = 'customer_name';
// break;
// case 'create_user_id' :
// $data[$key]['fieldName'] = 'create_user_name';
// break;
// case 'owner_user_id' :
// $data[$key]['fieldName'] = 'owner_user_name';
// break;
// default :
// $data[$key]['fieldName'] = $value['field'];
// }
// }
// }
# 商机
// if ($types == 'crm_business') {
// foreach ($data as $key => $value) {
// switch ($value['field']) {
// case 'customer_id' :
// $data[$key]['fieldName'] = 'customer_name';
// break;
// case 'type_id' :
// $data[$key]['fieldName'] = 'type_id_info';
// break;
// case 'status_id' :
// $data[$key]['fieldName'] = 'status_id_info';
// break;
// case 'create_user_id' :
// $data[$key]['fieldName'] = 'create_user_name';
// break;
// case 'owner_user_id' :
// $data[$key]['fieldName'] = 'owner_user_name';
// break;
// default :
// $data[$key]['fieldName'] = $value['field'];
// }
// }
// }
# 合同
// if ($types == 'crm_contract') {
// foreach ($data as $key => $value) {
// switch ($value['field']) {
// case 'customer_id' :
// $data[$key]['fieldName'] = 'customer_name';
// break;
// case 'business_id' :
// $data[$key]['fieldName'] = 'business_name';
// break;
// case 'contacts_id' :
// $data[$key]['fieldName'] = 'contacts_name';
// break;
// case 'order_user_id' :
// $data[$key]['fieldName'] = 'order_user_name';
// break;
// case 'create_user_id' :
// $data[$key]['fieldName'] = 'create_user_name';
// break;
// case 'owner_user_id' :
// $data[$key]['fieldName'] = 'owner_user_name';
// break;
// default :
// $data[$key]['fieldName'] = $value['field'];
// }
// }
// }
# 回款
// if ($types == 'crm_receivables') {
// foreach ($data as $key => $value) {
// switch ($value['field']) {
// case 'customer_id' :
// $data[$key]['fieldName'] = 'customer_name';
// break;
// case 'contract_id' :
// $data[$key]['fieldName'] = 'contract_num';
// break;
// case 'create_user_id' :
// $data[$key]['fieldName'] = 'create_user_name';
// break;
// case 'owner_user_id' :
// $data[$key]['fieldName'] = 'owner_user_name';
// break;
// case 'plan_id' :
// $data[$key]['fieldName'] = 'plan_id_info';
// break;
// default :
// $data[$key]['fieldName'] = $value['field'];
// }
// }
// }
# 回访
// if ($types == 'crm_visit') {
// foreach ($data as $key => $value) {
// switch ($value['field']) {
// case 'customer_id' :
// $data[$key]['fieldName'] = 'customer_name';
// break;
// case 'owner_user_id' :
// $data[$key]['fieldName'] = 'owner_user_name';
// $data[$key]['name'] = '回访人';
// break;
// case 'contacts_id' :
// $data[$key]['fieldName'] = 'contacts_name';
// break;
// case 'contract_id' :
// $data[$key]['fieldName'] = 'contract_number';
// break;
// case 'create_user_id' :
// $data[$key]['fieldName'] = 'create_user_name';
// break;
// default :
// $data[$key]['fieldName'] = $value['field'];
// }
// }
// }
# 产品
// if ($types == 'crm_product') {
// foreach ($data as $key => $value) {
// switch ($value['field']) {
// case 'category_id' :
// $data[$key]['fieldName'] = 'category_name';
// break;
// case 'create_user_id' :
// $data[$key]['fieldName'] = 'create_user_name';
// break;
// case 'owner_user_id' :
// $data[$key]['fieldName'] = 'owner_user_name';
// break;
// default :
// $data[$key]['fieldName'] = $value['field'];
// }
// }
// }
# 详情中不显示产品类别、回款期数
if ($action == 'read' && in_array($value['field'], ['category_id'])) {
unset($data[(int)$key]);
}
}
return $data;
}
/**
* 获取公海自定义字段数据
*
* @param $poolId
* @param $dataInfo
* @return bool|\PDOStatement|string|\think\Collection
*/
public function getPoolFieldData($poolId, $dataInfo)
{
$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) {
# 字段值
$poolFields[$key]['value'] = !empty($dataInfo[$value['field']]) ? $dataInfo[$value['field']] : '';
# 处理别名
switch ($value['field']) {
case 'create_user_id' :
$poolFields[$key]['fieldName'] = 'create_user_name';
$poolFields[$key]['value'] = !empty($dataInfo['create_user_id_info']) ? [$dataInfo['create_user_id_info']] : '';
break;
case 'before_owner_user_id' :
$poolFields[$key]['fieldName'] = 'before_owner_user_name';
$poolFields[$key]['value'] = !empty($dataInfo['before_owner_user_id_info']) ? [$dataInfo['before_owner_user_id_info']] : '';
break;
default :
$poolFields[$key]['fieldName'] = $value['field'];
}
if (in_array($value['form_type'], ['user', 'structure']) && !in_array($value['field'], ['create_user_id', 'owner_user_id', 'before_owner_user_id'])) {
$poolFields[$key]['fieldName'] = $value['field_name'] . '_name';
}
# 系统字段
if (in_array($value['field'], ['last_record', 'create_user_id', 'create_time', 'update_time', 'last_time', 'before_owner_user_id'])) {
$poolFields[$key]['system'] = 1;
} else {
$poolFields[$key]['system'] = 0;
}
}
return $poolFields;
}
/**
* 获取发票高级搜索字段
*
* @return array[]
*/
private function getInvoiceSearch()
{
return [
['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' => '负责人']
];
}
/**
* 获取产品父类层级(不包含自身)
*

@ -7,6 +7,7 @@
namespace app\admin\model;
use app\admin\controller\ApiCommon;
use app\admin\model\Common;
class Group extends Common
@ -85,9 +86,11 @@ class Group extends Common
//项目模块下角色
$param['type'] = 0;
}
$userInfo=new ApiCommon();
$user_id=$userInfo->userInfo;
$flag = $this->insertGetId($param);
if ($flag) {
return $flag;
return $flag;
} else {
$this->error = '操作失败';
return false;
@ -122,7 +125,10 @@ class Group extends Common
}
$flag = $this->where('id = '.$group_id)->update($param);
if ($flag) {
return true;
$user=new ApiCommon();
$user_id=$user->userInfo;
SystemActionLog($user_id['id'], 'admin_group','role', $group_id, 'update', $dataInfo['title'], '', '','编辑了:'.$dataInfo['title']);
return true;
} else {
$this->error = '操作失败';
return false;
@ -143,7 +149,11 @@ class Group extends Common
}
$flag = $this->where('id = '.$group_id)->delete();
if ($flag) {
return true;
# 系统操作记录
$user=new ApiCommon();
$user_id=$user->userInfo;
SystemActionLog($user_id['id'], 'admin_group','role', $group_id, 'update', $dataInfo['title'], '', '','删除了角色:'.$dataInfo['title']);
return true;
} else {
$this->error = '删除失败';
return false;

@ -50,10 +50,11 @@ class LoginRecord extends Common
/**
* 添加登录记录
*
* todo 登录设备暂时不加 数据表字段未加。
* @param int $type
* @param int $platform 登录设备
*/
public function createRecord($type = 0)
public function createRecord($platform='',$type = 0)
{
$data = [];
$data['type'] = $type;
@ -62,7 +63,13 @@ class LoginRecord extends Common
$data['ip'] = (new Scan())->get_client_ip();
$data['os'] = getOS();
$data['browser'] = getBrowser();
# todo登录设备暂时不加 数据表字段未加
// $platform=['_mobile'=>'手机','_ding'=>'钉钉','_wechat'=>'微信','_wxwork'=>'企业微信'];
// if(empty($platform)){
// $data['device']='网页';
// }else{
// $data['device']=$platform[$platform];
// }
$ip_address = getAddressById($data['ip']);
$data['address'] = $ip_address['country'];

@ -161,6 +161,10 @@ class Message extends Common
* 退出合同团队
*/
const CONTRACT_END = 30;
/**
* 移除团队成员
*/
const TEAM_END = 31;
/**
* 消息类型
@ -266,6 +270,9 @@ class Message extends Common
30 => [
'template' => '{from_user} 退出了您合同 {title} 的团队。',
],
31 => [
'template' => '将{from_user} 移除了您 {title} 的团队。',
],
];
/**

@ -58,6 +58,8 @@ class Scene extends Common
'name' => $v['name'],
'type' => $v['type']
];
if (!empty($v['start'])) $sceneData[$k]['start'] = $v['start'];
if (!empty($v['end'])) $sceneData[$k]['end'] = $v['end'];
}
}
if (!empty($sceneData)) $param['data'] = $sceneData;
@ -122,8 +124,8 @@ class Scene extends Common
foreach ($data as $key=>$val) {
$setting = $newFieldList[$key]['setting'];
$data[$key]['setting'] = $setting;
if ($val['form_type'] == 'user' && $val['value']) {
$userInfo = $userModel->getUserById($val['value']);
if ($val['form_type'] == 'user' && !empty($val['value'][0])) {
$userInfo = $userModel->getUserById($val['value'][0]);
$data[$key]['setting']['realname'] = $userInfo['realname'];
$data[$key]['setting']['id'] = $userInfo['id'];
}
@ -192,7 +194,7 @@ class Scene extends Common
$this->error = '场景名称必填';
return false;
}
if ($this->where(['scene_id'=>['neq',$id],'types'=>$types,'user_id'=>$user_id,'name'=>$param['name']])->find()) {
if ($this->where(['scene_id' => ['neq', $id], 'types' => $param['types'], 'user_id' => $user_id,'name' => $param['name']])->find()) {
$this->error = '场景名称已存在';
return false;
}
@ -207,6 +209,8 @@ class Scene extends Common
'name' => $v['name'],
'type' => $v['type']
];
if (!empty($v['start'])) $sceneData[$k]['start'] = $v['start'];
if (!empty($v['end'])) $sceneData[$k]['end'] = $v['end'];
}
}
if (!empty($sceneData)) $param['data'] = $sceneData;

@ -7,6 +7,7 @@
namespace app\admin\model;
use app\admin\controller\ApiCommon;
use app\admin\model\Common;
use think\Db;
@ -31,7 +32,11 @@ class Structure extends Common
if ($type == 'tree') {
$tree = new \com\Tree();
$data = $tree->list_to_tree($data, 'id', 'pid', 'child', 0, true, array(''));
}
}
foreach ($data as $k=>$v){
$data[$k]['owner_user_name']=foreachData('admin_structure',$v['owner_user_id'])?:null;
}
return $data;
}
@ -85,7 +90,12 @@ class Structure extends Common
$this->error = '删除失败';
return false;
} else {
return true;
$apiCommon = new ApiCommon();
$userInfo = $apiCommon->userInfo;
$content='删除了部门:'.$dataInfo['name'];
# 添加记录
SystemActionLog($userInfo['id'], 'admin_structure','structures', $id,'delete', $dataInfo['name'], '', '', $content);
return true;
}
}

@ -7,6 +7,7 @@
namespace app\admin\model;
use app\admin\controller\ApiCommon;
use think\Db;
use app\admin\model\Common;
use com\verify\HonrayVerify;
@ -107,6 +108,8 @@ class User extends Common
*/
public function getDataList($request)
{
$structure_status=$request['isNeedChild'];
unset($request['isNeedChild']);
$request = $this->fmtRequest( $request );
$fieldarray = ['search','group_id','structure_id','status','type','page','limit','pageType'];
$map = $request['map'] ? : [];
@ -127,10 +130,15 @@ class User extends Common
// $map['user.id'] = array('neq', 1);
if($map['structure_id']){
//获取部门下员工列表
$str_ids = structureList($map['structure_id'],'');
$new_str_ids = rtrim($str_ids,',');
$map['user.structure_id'] = ['in',$new_str_ids]; //$map['structure_id'];
if($structure_status==1){
$str_ids = structureList($map['structure_id'],'');
$new_str_ids = rtrim($str_ids,',');
$map['user.structure_id'] = ['in',$new_str_ids]; //$map['structure_id'];
}else{
$map['user.structure_id']=['in',$map['structure_id']];
}
}
$structureData=db('admin_structure')->where('id',$map['structure_id'])->value('owner_user_id');
unset($map['structure_id']);
if ($map['status'] || $map['group_id']) {
if ($map['status'] != 3) {
@ -187,11 +195,20 @@ class User extends Common
$list[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
$list[$k]['s_name'] = !empty($v['s_name']) ? $v['s_name'] : '';
$list[$k]['structure_id'] = !empty($v['structure_id']) ? $v['structure_id'] : '';
}
if($v['id']==1){
$list[$k]['userIdentity']=0;
}elseif($v['id']==$structureData){
$list[$k]['userIdentity']=1;
}else{
$list[$k]['userIdentity']=2;
}
}
//二位数组排序
$last_names = array_column($list,'userIdentity');
array_multisort($last_names,SORT_ASC,$list);
$data = [];
$data['list'] = $list;
$data['dataCount'] = $dataCount;
return $data;
}
@ -261,6 +278,10 @@ class User extends Common
if(db('admin_user')->where('username',$param['username'])->find()){
$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'])) {
@ -268,6 +289,20 @@ class User extends Common
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)){
}else{
$name= $param['realname'].$j;
break ;
}
}
$param['realname']= $name;
}else{
$param['realname']= $param['realname'];
}
// 验证
$validate = validate($this->name);
if (!$validate->check($param)) {
@ -311,8 +346,12 @@ class User extends Common
$this->commit();
$param['user_id'] = $data['user_id'];
$resSync = $syncModel->syncData($param);
return true;
$resSync = $syncModel->syncData($param);
# 添加记录
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'admin_user','employee', $user_id, 'save', $param['realname'], '', '','新增用户:'.$param['realname']);
return true;
} catch(\Exception $e) {
$this->rollback();
$this->error = '添加失败';
@ -355,13 +394,15 @@ class User extends Common
*/
public function updateDataById($param, $id)
{
$user=new ApiCommon();
$user_id=$user->userInfo;
if ($param['user_id']) {
//修改个人信息
$data['email'] = $param['email'];
$data['sex'] = $param['sex'];
// $data['mobile'] = $param['username'];
if (db('admin_user')->where(['username' => $param['username'],'id' => ['neq',$param['user_id']]])->find()) {
$userInfo=db('admin_user')->where(['username' => $param['username'],'id' => ['neq',$param['user_id']]])->find();
if ($userInfo) {
$this->error = '手机号已存在';
return false;
}
@ -370,7 +411,8 @@ class User extends Common
$data['post'] = $param['post'];
$flag = $this->where(['id' => $param['user_id']])->update($data);
if ($flag==0 || $flag==1) {
return true;
SystemActionLog($user_id['id'],'admin_user', 'employee', $param['user_id'], 'update', $param['realname'], '', '','编辑了:'.$param['realname']);
return true;
} else {
$this->error = '保存失败';
return false;
@ -421,8 +463,8 @@ class User extends Common
$this->allowField(true)->save($param, ['id' => $id]);
$this->commit();
Cache::rm('user_info' . $id);
// $data['mobile'] = $param['username'];
SystemActionLog($user_id['id'], 'admin_user','employee', $id, 'update', $userInfo['realname'], '', '','编辑了:'.$userInfo['realname']);
// $data['mobile'] = $param['username'];
$data['email'] = $param['email'];
$data['sex'] = $param['sex'];
$data['update_time'] = time();
@ -504,8 +546,8 @@ class User extends Common
$login_record->createRecord(LoginRecord::TYPE_USER_BANNED);
return false;
}
$login_record->createRecord(LoginRecord::TYPE_SUCCESS);
$platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
$login_record->createRecord($platform,LoginRecord::TYPE_SUCCESS);
// 获取菜单和权限
$dataList = $this->getMenuAndRule($userInfo['id']);
@ -528,7 +570,6 @@ class User extends Common
// $info['_AUTH_LIST_'] = $dataList['rulesList'];
$info['authKey'] = $authKey;
$platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
//删除旧缓存
if (Cache::get('Auth_'.$userInfo['authkey'].$platform)) {
Cache::rm('Auth_'.$userInfo['authkey'].$platform);
@ -596,12 +637,17 @@ class User extends Common
$resSync = $syncModel->syncData($syncData);
$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']);
// 重新设置缓存
session_start();
$cache['userInfo'] = $userInfo;
$cache['authKey'] = user_md5($userInfo['username'].$userInfo['password'].session_id(), $userInfo['salt']);
cache('Auth_'.$cache['authKey'], null);
cache('Auth_'.$cache['authKey'], $cache, $loginExpire);
return $cache['authKey'];//把auth_key传回给前端
}
$this->error = '修改失败';
@ -613,21 +659,29 @@ 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();;
$userInfo = db('admin_user')->where(['id' => $value])->find();
$salt = substr(md5(time()),0,4);
$temp['salt'] = $salt;
$temp['password']= $password = user_md5($param['password'], $salt, $userInfo['username']);
$flag = $flag && Db::name('AdminUser')->where('id ='.$value)->update($temp);
$syncData = [];
$syncData = [];
$syncData['user_id'] = $value;
$syncData['salt'] = $salt;
$syncData['password'] = $password;
$resSync = $syncModel->syncData($syncData);
}
if ($flag) {
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']);
}
return $flag;
} else {
$this->error ='修改失败,请稍后重试';
@ -733,9 +787,16 @@ class User extends Common
if (in_array('calendar', $adminConfig)) {
$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');
if (!empty($poolStatus)) $authList['crm']['pool'] = ['index' => true];
$ret['authList'] = $this->resetAuthorityFiled($authList);
$res['manage']=$rules;
$res['manage'] = $rules;
return $ret;
}
@ -756,24 +817,10 @@ class User extends Common
$authList['crm']['customer']['nearbyCustomer'] = $authList['crm']['customer']['nearby'];
unset($authList['crm']['customer']['nearby']);
}
# 公海权限
$authList['crm']['customer']['pool'] = !empty($authList['crm']['pool']['index']);;
# 跟进记录
$authList['crm']['followRecord'] = $authList['crm']['activity'];
# 公海
if (isset($authList['crm']['customer']['pool'])) {
$authList['crm']['pool']['index'] = $authList['crm']['customer']['pool'] ? true : false;
}
if (isset($authList['crm']['customer']['distribute'])) {
$authList['crm']['pool']['distribute'] = $authList['crm']['customer']['distribute'] ? true : false;
}
if (isset($authList['crm']['customer']['receive'])) {
$authList['crm']['pool']['receive'] = $authList['crm']['customer']['receive'] ? true : false;
}
if (isset($authList['crm']['customer']['poolexcelexport'])) {
$authList['crm']['pool']['excelexport'] = $authList['crm']['customer']['poolexcelexport'] ? true : false;
}
if (isset($authList['crm']['customer']['pooldelete'])) {
$authList['crm']['pool']['delete'] = $authList['crm']['customer']['pooldelete'] ? true : false;
}
# 合同
if (isset($authList['crm']['contract']['discard'])) {
$authList['crm']['contract']['discard'] = false;
@ -789,14 +836,6 @@ class User extends Common
unset($authList['work']['work']);
unset($authList['work']['task']);
unset($authList['work']['taskclass']);
# 跟进记录
if (!empty($authList['crm']['record']['index'])) {
$authList['crm']['followRecord']['delete'] = true;
$authList['crm']['followRecord']['read'] = true;
$authList['crm']['followRecord']['save'] = true;
$authList['crm']['followRecord']['update'] = true;
}
unset($authList['crm']['record']);
# admin:system
if (!empty($authList['admin']['system']['index'])) {
$authList['admin']['system']['read'] = $authList['admin']['system']['index'];
@ -853,9 +892,9 @@ class User extends Common
unset($authList['admin']['examine_flow']);
}
# admin:printing
if (!empty($authList['admin']['printing'])) {
$authList['admin']['print'] = $authList['admin']['printing'];
unset($authList['admin']['printing']);
if (!empty($authList['admin']['crm']['printing'])) {
$authList['admin']['crm']['print'] = $authList['admin']['crm']['printing'];
unset($authList['admin']['crm']['printing']);
}
# admin:work
if (!empty($authList['admin']['work']['work'])) {
@ -863,8 +902,19 @@ class User extends Common
unset($authList['admin']['work']['work']);
}
# admin:log
unset($authList['admin']['loginrecord']);
unset($authList['admin']['log']);
if (isset($authList['admin']['adminlog']['loginlog'])) {
$authList['admin']['adminLog']['loginLog'] = $authList['admin']['adminlog']['loginlog'];
unset($authList['admin']['adminlog']['loginlog']);
}
if (isset($authList['admin']['adminlog']['actionrecord'])) {
$authList['admin']['adminLog']['actionRecord'] = $authList['admin']['adminlog']['actionrecord'];
unset($authList['admin']['adminlog']['actionrecord']);
}
if (isset($authList['admin']['adminlog']['systemlog'])) {
$authList['admin']['adminLog']['systemLog'] = $authList['admin']['adminlog']['systemlog'];
unset($authList['admin']['adminlog']['systemlog']);
}
unset($authList['admin']['adminlog']);
# admin:initialize
if (!empty($authList['admin']['initialize'])) {
$authList['admin']['init']['initData'] = $authList['admin']['initialize']['update'];
@ -1032,7 +1082,7 @@ class User extends Common
'structure.name' => 'structure_name',
'structure.id' => 'structure_id'
])
->cache('user_info' . $id, null, 'user_info')
// ->cache('user_info' . $id, null, 'user_info')
->find();
$data['img'] = $data['img'] ? getFullPath($data['img']) : '';
$data['thumb_img'] = $data['thumb_img'] ? getFullPath($data['thumb_img']) : '';
@ -1088,7 +1138,7 @@ class User extends Common
$list = $this
->alias('user')
->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
->where(['user.id' => ['in', $id]])->field('user.id,username,img,thumb_img,realname,parent_id,structure.name as structure_name,structure.id as structure_id')->select();
->where(['user.id' => ['in', $ids]])->field('user.id,username,img,thumb_img,realname,parent_id,structure.name as structure_name,structure.id as structure_id')->select();
return $list ? : [];
}
@ -1241,7 +1291,7 @@ class User extends Common
{
$user_id = $user_id ?: self::userInfo('id');
if (empty($group_list))
return !!Access::where(['user_id' => $user_id, 'group_id' => ['IN', $group]])->value('user_id');
return !!Access::where(['user_id' => $user_id, 'group_id' => ['IN', $group_list]])->value('user_id');
}
/**
@ -1311,7 +1361,12 @@ 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) {
$userInfo=Db::name('admin_user')->where('id', $value)->find();
SystemActionLog($user_id['id'], 'admin_user','employee', $value, 'update', $userInfo['realname'], '', '','编辑员工角色:'.$userInfo['realname']);
}
return true;
} catch (\Exception $e) {
Db::rollback();
@ -1319,4 +1374,64 @@ class User extends Common
return false;
}
}
/**
* 重设部门
* @param array $ids 用户id
* @param $param 部门id
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/24 0024 14:05
*
*/
public function setUserDept($ids = [],$param)
{
if (empty($ids)) {
$this->error = '参数错误';
return false;
}
foreach ($ids as $v){
$data['id']=$v;
$data['structure_id']=$param['structure_id'];
$flag=foreachData('',$data);
}
if ($flag) {
return $flag;
} else {
$this->error ='修改失败,请稍后重试';
return false;
}
}
/**
* 员工分类总数
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/24 0024 14:42
*/
public function countNumOfUser(){
//全部
// $data['allUserCount']=$this->count();
// //未激活
// $data['inactiveCount']=$this->where('status',2)->count();
// //激活
// $data['activateCount']=$this->where('status',1)->count();
// //停用
// $data['disableCount']=$this->where('status',0)->count();
// //新增
// $data['addNewlyCount']=$this->where('create_time','gt',strtotime('-1 week'))->count();
$time=strtotime('-1 week');
$list=db('admin_user')->field([
'count(id) as allUserCount,
count(case status when 2 then id else null end) as inactiveCount,
count(case status when 1 then id else null end) as activateCount,
count(case status when 0 then id else null end) as disableCount,
count(case when create_time >' .$time.' then id else null end) as addNewlyCount
'
])->select();
$data=[];
$data['list']=$list;
return $data;
}
}

@ -139,6 +139,8 @@ class UserField extends Model
*/
public function getDataList($types, $user_id)
{
$grantData = getFieldGrantData($user_id);
$userLevel = isSuperAdministrators($user_id);
$fieldArr = (new Field)->getFieldList($types);
$fieldList = [];
$field_list = [];
@ -166,14 +168,14 @@ class UserField extends Model
if (empty($v['is_hide'])) {
$valueList[] = $k;
$value_list[$a]['field'] = $k;
$value_list[$a]['width'] = $v['width'];
$value_list[$a]['name'] = $field_list[$k]['name'];
$value_list[$a]['field'] = $k;
$value_list[$a]['width'] = $v['width'];
$value_list[$a]['name'] = $field_list[$k]['name'];
$a++;
} else {
$hideList[] = $k;
$hide_list[$b]['field'] = $k;
$hide_list[$b]['width'] = $v['width'];
$hide_list[$b]['width'] = $v['width'];
$hide_list[$b]['name'] = $field_list[$k]['name'];
$b++;
}
@ -192,9 +194,31 @@ class UserField extends Model
$hide_list = [];
}
# 处理显示列的字段授权
foreach ($value_list AS $key => $value) {
if (!$userLevel && !empty($grantData[$types])) {
foreach ($grantData[$types] AS $k => $v) {
$status = getFieldGrantStatus($value['field'], $grantData[$types]);
if (empty($status['read'])) unset($value_list[(int)$key]);
}
}
}
# 处理隐藏列的字段授权
foreach ($hide_list AS $key => $value) {
if (!$userLevel && !empty($grantData[$types])) {
foreach ($grantData[$types] AS $k => $v) {
$status = getFieldGrantStatus($value['field'], $grantData[$types]);
if (empty($status['read'])) unset($hide_list[(int)$key]);
}
}
}
$data = [];
$data['value_list'] = $value_list ? : []; //展示列
$data['hide_list'] = $hide_list ? : []; //隐藏列
$data['value_list'] = array_values($value_list) ? : []; //展示列
$data['hide_list'] = array_values($hide_list) ? : []; //隐藏列
if ($types == 'crm_visit') {
foreach ($data['value_list'] AS $key => $value) {

@ -84,8 +84,8 @@ class Customer extends ApiCommon
if ($param['type']) {
$timeArr = getTimeByType($param['type']);
$param['start_time'] = $timeArr[0];
$param['end_time'] = $timeArr[1];
$param['start_time'] = date('y-m-d 00:00:00',$timeArr[0]);
$param['end_time'] = date('y-m-d 23:59:59',$timeArr[1]);
} else {
if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
if (!empty($param['end_time'])) $param['end_time'] =$param['end_time'] . ' 23:59:59';
@ -482,7 +482,6 @@ class Customer extends ApiCommon
*/
public function pool()
{
$actionRecordModel = new \app\bi\model\ActionRecord();
$userModel = new \app\admin\model\User();
$adminModel = new \app\admin\model\Admin();
$param = $this->param;
@ -497,29 +496,45 @@ class Customer extends ApiCommon
if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
if (!empty($param['end_time'])) $param['end_time'] = strtotime($param['end_time'] . ' 23:59:59');
$time = getTimeArray($param['start_time'], $param['end_time']);
$sql = $actionRecordModel
->field([
"FROM_UNIXTIME(`create_time`, '{$time['time_format']}')" => 'type',
'SUM(CASE WHEN `content` = "将客户放入公海" THEN 1 ELSE 0 END)' => 'put_in',
'SUM(CASE WHEN `content` = "领取了客户" THEN 1 ELSE 0 END)' => 'receive'
])
->where([
'user_id' => ['IN', !empty($userIds) ? $userIds : '9999999999'],
'create_time' => ['BETWEEN', $time['between']],
'content' => ['IN', ['将客户放入公海', '领取了客户']]
])
->group('type')
->fetchSql()
->select();
// $sql = db('crm_customer_pool_record')
// ->field([
// "FROM_UNIXTIME(`create_time`, '{$time['time_format']}')" => 'time',
// 'SUM(CASE WHEN `type` = 2 THEN 1 ELSE 0 END)' => 'put_in',
// 'SUM(CASE WHEN `type` = 1 THEN 1 ELSE 0 END)' => 'receive'
// ])
// ->where([
// 'user_id' => ['IN', !empty($userIds) ? $userIds : 0],
// 'create_time' => ['BETWEEN', $time['between']],
// ])
// ->group('time')
// ->fetchSql()
// ->select();
$prefix = config('database.prefix');
$ids = !empty($userIds) ? implode(',', $userIds) : 0;
$sql = "SELECT
FROM_UNIXTIME( `create_time`, '%Y-%m' ) AS `time`,
SUM( CASE WHEN `type` = 2 THEN 1 ELSE 0 END ) AS `put_in`,
SUM( CASE WHEN `type` = 1 THEN 1 ELSE 0 END ) AS `receive`
FROM
(SELECT * FROM `".$prefix."crm_customer_pool_record` GROUP BY `customer_id`, `type`) AS `record`
WHERE
`user_id` IN ( ".$ids." ) AND `create_time` BETWEEN ".$time['between'][0]." AND ".$time['between'][1]."
GROUP BY `time`";
$res = queryCache($sql);
$res = array_column($res, null, 'type');
foreach ($time['list'] as &$val) {
$val['put_in'] = (int)$res[$val['type']]['put_in'];
$val['receive'] = (int)$res[$val['type']]['receive'];
$res = array_column($res, null, 'time');
$result = [];
foreach ($time['list'] AS $key => $value) {
$result[] = [
'type' => $value['type'],
'start_time' => $value['start_time'],
'end_time' => $value['end_time'],
'put_in' => !empty($res[$value['type']]['put_in']) ? (int)$res[$value['type']]['put_in'] : 0,
'receive' => !empty($res[$value['type']]['receive']) ? (int)$res[$value['type']]['receive'] : 0
];
}
return resultArray(['data' => $time['list']]);
return resultArray(['data' => $result]);
}
/**
@ -554,81 +569,79 @@ class Customer extends ApiCommon
$whereArr = $adminModel->getWhere($param, '', $perUserIds); //统计条件
$userIds = $whereArr['userIds'];
$between_time = $whereArr['between_time'];
$sql = CustomerModel::field([
'COUNT(*)' => 'customer_num',
'owner_user_id'
])
->where([
'create_time' => ['BETWEEN', $between_time],
'owner_user_id' => ['IN', !empty($userIds) ? $userIds : '9999999999']
])
->group('owner_user_id')
->fetchSql()
->select();
$customer_num_list = queryCache($sql);
$customer_num_list = array_column($customer_num_list, null, 'owner_user_id');
$configModel = new \app\crm\model\ConfigData();
$configInfo = $configModel->getData();
$paramPool = [];
$paramPool['config'] = $configInfo['config'] ? : 0;
$paramPool['follow_day'] = $configInfo['follow_day'] ? : 0;
$paramPool['deal_day'] = $configInfo['deal_day'] ? : 0;
$paramPool['remind_config'] = $configInfo['remind_config'] ? : 0;
$customer_list='';
$action_record_list='';
if($paramPool['config']==1){
$sql = $CustomerModel
->alias('customer')
->field([
'customer.create_user_id as user_id' ,
'COUNT(customer.customer_id) as put_in'
])
->group('user_id')
->where($CustomerModel->getWhereByPool())
->where([
'create_time' => ['BETWEEN', $between_time],
'create_user_id' => ['IN', $userIds],
])
->fetchSql()
->select();
$customer_list = queryCache($sql);
$customer_list = array_column($customer_list, null, 'user_id');
// $sql = db('crm_customer_pool_record')
// ->field([
// 'user_id',
// 'SUM(CASE WHEN `type` = 2 THEN 1 ELSE 0 END)' => 'put_in',
// 'SUM(CASE WHEN `type` = 1 THEN 1 ELSE 0 END)' => 'receive'
// ])
// ->group('user_id')
// ->where([
// 'create_time' => ['BETWEEN', $between_time],
// 'user_id' => ['IN', !empty($userIds) ? $userIds : 0]
// ])
// ->fetchSql()
// ->select();
$prefix = config('database.prefix');
$ids = !empty($userIds) ? implode(',', $userIds) : 0;
$sql = "SELECT
`user_id`,
SUM( CASE WHEN `type` = 2 THEN 1 ELSE 0 END ) AS `put_in`,
SUM( CASE WHEN `type` = 1 THEN 1 ELSE 0 END ) AS `receive`
FROM
(SELECT * FROM `".$prefix."crm_customer_pool_record` GROUP BY `customer_id`, `type`) AS `record`
WHERE
`create_time` BETWEEN ".$between_time[0]." AND ".$between_time[1]." AND `user_id` IN ( ".$ids." )
GROUP BY `user_id`";
$poolRecord = queryCache($sql);
$recordData = [];
foreach ($poolRecord AS $key => $value) {
$recordData[$value['user_id']] = [
'put_in' => $value['put_in'],
'receive' => $value['receive']
];
}
$sql = $actionRecordModel
->field([
'user_id',
'SUM(CASE WHEN `content` = "将客户放入公海" THEN 1 ELSE 0 END)' => 'put_in',
'SUM(CASE WHEN `content` = "领取了客户" THEN 1 ELSE 0 END)' => 'receive'
])
->group('user_id')
->where([
'create_time' => ['BETWEEN', $between_time],
'user_id' => ['IN', $userIds],
'content' => ['IN', ['将客户放入公海', '领取了客户']],
'types' => 'crm_customer',
])
->fetchSql()
->select();
$action_record_list = queryCache($sql);
$action_record_list = array_column($action_record_list, null, 'user_id');
// $action_record_list = array_column($action_record_list, null, 'user_id');
# 部门列表
$structureData = [];
$structureList = db('admin_structure')->select();
foreach ($structureList AS $key => $value) {
$structureData[$value['id']] = $value['name'];
}
# 员工列表
$userList = db('admin_user')->field(['id', 'realname', 'structure_id'])->whereIn('id', $userIds)->select();
$res = [];
$receiveCount = 0; # 领取公海客户总数
$putInCount = 0; # 进入公海客户总数
foreach ($userIds as $val) {
$item['put'] = !empty($customer_list[$val]['put_in'])?(int)$customer_list[$val]['put_in']:0;
$item['put_in'] = !empty($customer_list[$val]['put_in']) ? $item['put'] : (int)$action_record_list[$val]['put_in'] + $item['put'];
$item['receive'] = !empty($action_record_list[$val]['receive']) ? (int)$action_record_list[$val]['receive'] : 0;
$item['customer_num'] = !empty($customer_num_list[$val]['customer_num']) ? (int)$customer_num_list[$val]['customer_num'] : 0;
$user_info = $userModel->getUserById($val);
$item['realname'] = $user_info['realname'];
$item['username'] = $user_info['structure_name'];
foreach ($userList as $val) {
$item['put'] = !empty($recordData[$val['id']]['put_in']) ? (int)$recordData[$val['id']]['put_in'] : 0;
$item['put_in'] = !empty($recordData[$val['id']]['put_in']) ? (int)$recordData[$val['id']]['put_in'] : 0;
$item['receive'] = !empty($recordData[$val['id']]['receive']) ? (int)$recordData[$val['id']]['receive'] : 0;
$item['customer_num'] = 0;
$item['realname'] = $val['realname'];
$item['username'] = !empty($structureData[$val['structure_id']]) ? $structureData[$val['structure_id']] : '';
$res[] = $item;
$receiveCount += $item['receive'];
$putInCount += $item['put_in'];
}
// foreach ($userIds as $val) {
// $item['put'] = !empty($customer_list[$val]['put_in'])?(int)$customer_list[$val]['put_in']:0;
// $item['put_in'] = !empty($customer_list[$val]['put_in']) ? $item['put'] : (int)$action_record_list[$val]['put_in'] + $item['put'];
// $item['receive'] = !empty($action_record_list[$val]['receive']) ? (int)$action_record_list[$val]['receive'] : 0;
// $item['customer_num'] = !empty($customer_num_list[$val]['customer_num']) ? (int)$customer_num_list[$val]['customer_num'] : 0;
// $user_info = $userModel->getUserById($val);
// $item['realname'] = $user_info['realname'];
// $item['username'] = $user_info['structure_name'];
// $res[] = $item;
//
// $receiveCount += $item['receive'];
// $putInCount += $item['put_in'];
// }
$result = ['list' => $res, 'total' => ['realname' => '总计', 'receive' => $receiveCount, 'put_in' => $putInCount]];

@ -89,7 +89,7 @@ class Examine extends ApiCommon
$where = [];
$where['create_user_id'] = $user_id;
$where['check_status'] = 2;
$where['check_status'] = ['neq',4];
$where['create_time'] = $create_time;
$where['category_id'] = $category_id;
$sumData = 0;
@ -122,7 +122,7 @@ class Examine extends ApiCommon
unset($where['create_time']);
unset($where['create_user_id']);
unset($where['create_user_id']);
// $where['check_status'] = 'all';
$where['check_status'] = 'all';
$where['page'] = $param['page'];
$where['limit'] = $param['limit'];
$where['user_id'] = $user_id;

@ -25,7 +25,7 @@ class Product extends ApiCommon
{
$action = [
'permission' => [''],
'allow' => ['statistics', 'productcategory', 'excelexport']
'allow' => ['statistics', 'productcategory', 'excelexport','listproduct']
];
Hook::listen('check_auth', $action);
$request = Request::instance();
@ -65,7 +65,7 @@ class Product extends ApiCommon
}
return resultArray(['data' => $list]);
}
/**
* 产品分类销量分析
*
@ -99,50 +99,23 @@ class Product extends ApiCommon
{
$param = $this->param;
$list = $this->statistics($param);
$data = [];
$subtotalCount = [];
$sumCount = [];
$item = [];
$res = [];
foreach ($list as &$val) {
$res[] = $val['product_id'];
$data[$val['product_id']][] = $val;
}
$res = array_unique($res);
foreach ($res as $e) {
$unm = 0;
$subtotal = 0;
foreach ($list as $v) {
if ($e == $v['product_id']) {
$unm += $v['num'];
$subtotal += $v['subtotal'];
$sumCount[$e] = $unm;
$subtotalCount[$e] = (float)$subtotal;
}
}
$item[$e][] = [
'type' => '',
'category_id_info' => '',
'product_name' => '',
'contract_num' => '',
'realname' => '',
'name' => '',
'price' => '合计',
'num' => $sumCount[$e],
'subtotal' => $subtotalCount[$e],
];
}
$items = [];
foreach ($data as $key => $value) {
$items[] = array_merge($data[$key], $item[$key]);
}
foreach ($items as $u) {
foreach ($u as $d) {
$field[] = $d;
}
}
$excelLogic = new ExcelLogic();
$data = $excelLogic->productExcel($param, $field);
$data = $excelLogic->productExcel($param, $list['list']);
return $data;
}
/**
* 产品销量列表
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/20 0020 16:16
*/
public function listProduct(){
$param = $this->param;
$productModel = new \app\crm\model\Product();
if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
if (!empty($param['end_time'])) $param['end_time'] = $param['end_time'] . ' 23:59:59';
$list = $productModel->listProduct($param);
return resultArray(['data' => $list]);
}
}

@ -134,7 +134,7 @@ class Ranking extends ApiCommon
if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
if (!empty($param['end_time'])) $param['end_time'] = $param['end_time'] . ' 23:59:59';
$whereArr = $this->com($param, 'contract');
$whereArr['check_status'] = 2;
// $whereArr['check_status'] = 2;
//导出使用
if (!empty($param['excel_type'])) {

@ -182,12 +182,9 @@ class ExcelLogic
$field_list = [
'0' => ['name' => '产品分类', 'field' => 'category_id_info'],
'1' => ['name' => '产品名称', 'field' => 'product_name'],
'2' => ['name' => '合同编号', 'field' => 'contract_num'],
'3' => ['name' => '负责人', 'field' => 'realname'],
'4' => ['name' => '客户名称', 'field' => 'contract_name'],
'5' => ['name' => '销售单价', 'field' => 'price'],
'6' => ['name' => '数量', 'field' => 'num'],
'7' => ['name' => '订单产品小计', 'field' => 'subtotal'],
'2' => ['name' => '合同数', 'field' => 'contract_product_sum'],
'3' => ['name' => '数量合计', 'field' => 'product_sum'],
'4' => ['name' => '订单产品小计', 'field' => 'contract_money'],
];
$type = '产品销售情况统计';
$excelModel = new \app\admin\model\Excel();

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

@ -15,6 +15,7 @@ use think\Lang;
use think\helper\Time;
use com\IpLocation;
use app\crm\traits\DataTime;
/**
* 对象 转 数组
*
@ -56,7 +57,7 @@ function array_to_object($arr)
/**
* 返回对象
* @param $array 响应数据
* @param array $array 响应数据
*/
function resultArray($array)
{
@ -135,7 +136,7 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
//查询自定义字段模块多选字段类型
$check_field_arr = [];
//特殊字段
//过滤系统参数
$unset_arr = ['page', 'limit', 'order_type', 'order_field'];
if (!is_array($array)) {
@ -163,7 +164,7 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
}
if ($v['form_type'] == 'date') {
if (!empty($v['start'])) $v['start'] = date('Y-m-d', $v['start']);
if (!empty($v['end'])) $v['end'] = date('Y-m-d', $v['end']);
if (!empty($v['end'])) $v['end'] = date('Y-m-d', $v['end']);
}
# 创建人、负责人、回访人(非自定义字段)
// if ($v['form_type'] == 'user' && in_array($k, ['create_user_id', 'owner_user_id'])) {
@ -173,7 +174,7 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
if (($v['form_type'] == 'user' && !in_array($k, ['create_user_id', 'owner_user_id'])) || $v['form_type'] == 'structure') {
if ($v['condition'] == 'is') $v['condition'] = 'contains';
if ($v['condition'] == 'isNot') {
return "(".$c.$k." not like ',%".$v['value'][0]."%,' OR ".$c.$k." is null)";
return "(" . $c . $k . " not like ',%" . $v['value'][0] . "%,' OR " . $c . $k . " is null)";
}
}
# 处理多选字段的精确搜索
@ -181,10 +182,10 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
if ($v['condition'] == 'is' && count($v['value']) == 1) $v['value'][0] = ',' . $v['value'][0] . ',';
if ($v['condition'] == 'is' && count($v['value']) > 1) {
$checkboxLike = '';
foreach ($v['value'] AS $kk => $vv) {
$checkboxLike .= $c.$k." like "."',%".$vv."%,' AND ";
foreach ($v['value'] as $kk => $vv) {
$checkboxLike .= $c . $k . " like " . "',%" . $vv . "%,' AND ";
}
return "(".$checkboxLike."LENGTH(".$c.$k.") = LENGTH('".arrayToString($v['value'])."'))";
return "(" . $checkboxLike . "LENGTH(" . $c . $k . ") = LENGTH('" . arrayToString($v['value']) . "'))";
}
}
if ($types == 'contract' && !empty($v['value'])) {
@ -195,9 +196,9 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
break;
case 'contacts_id' :
$contactsIds = [];
foreach ($v['value'] AS $kk => $vv) {
foreach ($v['value'] as $kk => $vv) {
$contactsIdArray = db('crm_contacts')->whereLike('name', '%' . $vv . '%')->column('contacts_id');
foreach ($contactsIdArray AS $kkk => $vvv) {
foreach ($contactsIdArray as $kkk => $vvv) {
$contactsIds[] = $vvv;
}
}
@ -211,16 +212,16 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
}
if ($types == 'receivables' && $k == 'plan_id' && !empty($v['value'])) {
$planIds = [];
foreach ($v['value'] AS $kk => $vv) {
foreach ($v['value'] as $kk => $vv) {
$planIdArray = db('crm_receivables_plan')->whereLike('num', '%' . $vv . '%')->column('plan_id');
foreach ($planIdArray AS $kkk => $vvv) {
foreach ($planIdArray as $kkk => $vvv) {
$planIds[] = $vvv;
}
}
$v['value'] = array_unique($planIds);
}
if ($types == 'invoice' && $v['type'] == 'invoice_status' && !empty($v['value'])) {
foreach ($v['value'] AS $kk => $vv) {
foreach ($v['value'] as $kk => $vv) {
if ($vv == '已开票') $v['value'][$kk] = 1;
if ($vv == '未开票') $v['value'][$kk] = 0;
}
@ -279,7 +280,11 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
if (in_array($k, $check_field_arr)) {
$where[$c . $k] = field($v['value'], 'contains');
} else {
$where[$c . $k] = field($v['value'], $v['condition'], $k);
if ($v['condition'] == 'isNot' || $v['condition'] == 'notContains') {
$where[$c . $k] = [field($v['value'], $v['condition'], $k), ['null'], 'or'];
} else {
$where[$c . $k] = field($v['value'], $v['condition'], $k);
}
}
} elseif (in_array($v['condition'], ['isNull', 'isNotNull', 'in'])) {
$where[$c . $k] = field($v['value'], $v['condition']);
@ -293,13 +298,13 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
}
}
}
# 商机阶段为赢单、输单、无效的值保存在is_end中将status_id改为is_end
if (!empty($where['business.status_id']) && in_array($where['business.status_id'][1], [1,2,3])) {
if (!empty($where['business.status_id']) && in_array($where['business.status_id'][1], [1, 2, 3])) {
$where['business.is_end'] = $where['business.status_id'];
unset($where['business.status_id']);
}
return $where ?: [];
}
@ -322,22 +327,22 @@ function field($search, $condition = '', $k = '')
break;
case "contains" :
$containsWhere = [];
foreach ((array)$search AS $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
foreach ((array)$search as $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
$where = ['like', $containsWhere, 'OR'];
break;
case "notContains" :
$containsWhere = [];
foreach ((array)$search AS $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
foreach ((array)$search as $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
$where = ['notlike', $containsWhere, 'AND'];
break;
case "startWith" :
$startWithWhere = [];
foreach ((array)$search AS $key1 => $value1) $startWithWhere[] = $value1 . '%';
foreach ((array)$search as $key1 => $value1) $startWithWhere[] = $value1 . '%';
$where = ['like', $startWithWhere, 'OR'];
break;
case "endWith" :
$endWithWhere = [];
foreach ((array)$search AS $key1 => $value1) $endWithWhere[] = '%' . $value1;
foreach ((array)$search as $key1 => $value1) $endWithWhere[] = '%' . $value1;
$where = ['like', $endWithWhere, 'OR'];
break;
case "isNull" :
@ -348,42 +353,42 @@ function field($search, $condition = '', $k = '')
break;
case "eq" :
$where = function ($query) use ($search, $k) {
foreach ((array)$search AS $key1 => $value1) {
foreach ((array)$search as $key1 => $value1) {
$query->whereOr($k, $value1);
}
};
break;
case "neq" :
$where = function ($query) use ($search, $k) {
foreach ((array)$search AS $key1 => $value1) {
foreach ((array)$search as $key1 => $value1) {
$query->whereOr($k, '<>', $value1);
}
};
break;
case "gt" :
$where = function ($query) use ($search, $k) {
foreach ((array)$search AS $key1 => $value1) {
foreach ((array)$search as $key1 => $value1) {
$query->whereOr($k, '>', $value1);
}
};
break;
case "egt" :
$where = function ($query) use ($search, $k) {
foreach ((array)$search AS $key1 => $value1) {
foreach ((array)$search as $key1 => $value1) {
$query->whereOr($k, '>=', $value1);
}
};
break;
case "lt" :
$where = function ($query) use ($search, $k) {
foreach ((array)$search AS $key1 => $value1) {
foreach ((array)$search as $key1 => $value1) {
$query->whereOr($k, '<', $value1);
}
};
break;
case "elt" :
$where = function ($query) use ($search, $k) {
foreach ((array)$search AS $key1 => $value1) {
foreach ((array)$search as $key1 => $value1) {
$query->whereOr($k, '<=', $value1);
}
};
@ -408,12 +413,12 @@ function field($search, $condition = '', $k = '')
function field_arr($value, $condition = '')
{
if (is_array($value)) {
} else {
$condition = $condition ?: 'eq';
$where_arr = ['value' => $value, 'condition' => $condition];
}
return $where_arr;
}
@ -432,18 +437,18 @@ function actionLog($id, $join_user_ids = '', $structure_ids = '', $content = '')
}
$header = Request::instance()->header();
$authKey = $header['authkey'];
$cache = cache('Auth_'.$authKey);
$cache = cache('Auth_' . $authKey);
if (!$cache) {
return false;
}
$userInfo = $cache['userInfo'];
$category = $userInfo['id'] == 1 ? '管理员' : '员工';
$request = request();
$m = strtolower($request->module());
$c = strtolower($request->controller());
$a = strtolower($request->action());
$res_action = true;
foreach ($idArr as $v) {
$data = [];
@ -454,27 +459,27 @@ function actionLog($id, $join_user_ids = '', $structure_ids = '', $content = '')
$data['action_id'] = $v;
$data['create_time'] = time();
$data['client_ip'] = request()->ip();
$data['content'] = $content ? : lang('ACTIONLOG', [$category, $userInfo['realname'], date('Y-m-d H:i:s'), lang($action_name), $v, lang($controller_name)]);
$data['join_user_ids'] = $join_user_ids ? : ''; //抄送人
$data['structure_ids'] = $structure_ids ? : ''; //抄送部门
$data['content'] = $content ?: lang('ACTIONLOG', [$category, $userInfo['realname'], date('Y-m-d H:i:s'), lang($action_name), $v, lang($controller_name)]);
$data['join_user_ids'] = $join_user_ids ?: ''; //抄送人
$data['structure_ids'] = $structure_ids ?: ''; //抄送部门
if ($action_name == 'delete' || $action_name == 'commentdel') {
$data['action_delete'] = 1;
}
if (!db('admin_action_log')->insert($data)) {
$res_action = false;
}
# 数据操作日志
db('admin_operation_log')->insert([
'user_id' => $userInfo['id'],
'client_ip' => request()->ip(),
'module' => $m . '_' . $c,
'action_id' => $v,
'content' => $content,
'user_id' => $userInfo['id'],
'client_ip' => request()->ip(),
'module' => $m . '_' . $c,
'action_id' => $v,
'content' => $content,
'create_time' => time()
]);
}
if ($res_action) {
return true;
} else {
@ -598,14 +603,14 @@ function getSubUserId($self = true, $type = 0, $user_id = '')
$userInfo = $cache['userInfo'];
$user_id = $userInfo['id'];
$adminTypes = adminGroupTypes($user_id);
if (in_array(1, $adminTypes)) {
$type = 1;
}
}
$belowIds = [];
if (empty($type)) {
if ($user_id) {
$belowIds = getSubUser($user_id);
}
@ -629,7 +634,7 @@ function getSubUser($userId, $queried = [], $allUserList = [])
if (empty($allUserList)) {
$allUserList = db('admin_user')->field('id,parent_id')->select();
}
foreach ($allUserList as $k=>$v) {
foreach ($allUserList as $k => $v) {
if ($v['parent_id'] == $userId) {
$sub_user[] = $v['id'];
}
@ -725,7 +730,7 @@ function sendMessage($user_id, $content, $action_id, $sysMessage = 0)
$m = strtolower($request->module());
$c = strtolower($request->controller());
$a = strtolower($request->action());
$userInfo = [];
if ($sysMessage == 0) {
$header = $request->header();
@ -739,7 +744,7 @@ function sendMessage($user_id, $content, $action_id, $sysMessage = 0)
foreach ($user_ids as $v) {
$data = [];
$data['content'] = $content;
$data['from_user_id'] = $userInfo['id'] ? : 0;
$data['from_user_id'] = $userInfo['id'] ?: 0;
$data['to_user_id'] = $v;
$data['read_time'] = 0;
$data['send_time'] = time();
@ -777,6 +782,11 @@ function format_bytes($size, $delimiter = '')
*/
function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData = [], $content = '')
{
# 转格式
if (!empty($oldData['next_time']) && $oldData['next_time'] != strtotime($oldData['next_time'])) {
$oldData['next_time'] = strtotime($oldData['next_time']);
}
if (is_array($oldData) && is_array($newData) && $user_id) {
$differentData = array_diff_assoc($newData, $oldData);
$fieldModel = new FieldModel();
@ -787,19 +797,18 @@ function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData =
foreach ($field_arr as $k => $v) {
$newFieldArr[$v['field']] = $v;
}
$unField = ['update_time','create_time']; //定义过滤字段
$unField = ['update_time', 'create_time']; //定义过滤字段
$message = [];
$un_form_type = ['file', 'form'];
foreach ($differentData as $k => $v) {
if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
$field_name = '';
$field_name = $newFieldArr[$k]['name'];
$new_value = $v;
$new_value = $v ?: '空';
$old_value = $oldData[$k] ?: '空';
if ($newFieldArr[$k]['form_type'] == 'datetime') {
$new_value = $v ? date('Y-m-d', $v) : '';
$old_value = date('Y-m-d', $oldData[$k]);
$new_value = $v ? date('Y-m-d', $v) : '';
$old_value = !empty($oldData[$k]) ? date('Y-m-d', $oldData[$k]) : '空';
if (empty($v) && empty($oldData[$k])) continue;
} elseif ($newFieldArr[$k]['form_type'] == 'user') {
$new_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($v))) : '';
@ -829,13 +838,15 @@ function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData =
} elseif ($newFieldArr[$k]['form_type'] == 'visit') {
$new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
$old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
} elseif ($newFieldArr[$k]['form_type'] == 'single_user'){
} elseif ($newFieldArr[$k]['form_type'] == 'single_user') {
$new_value = $v ? db('admin_user')->where(['id' => $v])->value('realname') : '';
$old_value = $v ? db('admin_user')->where(['id' => $oldData['owner_user_id']])->value('realname') : '';
}elseif($newFieldArr[$k]['form_type'] == 'floatnumber'){
$new_value = $v ? number_format($v,2) : '';
} elseif ($newFieldArr[$k]['form_type'] == 'floatnumber') {
$new_value = $v ? number_format($v, 2) : '';
}
if ($old_value != $new_value) {
$message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
}
$message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
}
}
if ($message) {
@ -846,15 +857,6 @@ function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData =
$data['action_id'] = $action_id;
$data['content'] = implode('.|.', $message);
db('admin_action_record')->insert($data);
# 数据操作日志
db('admin_operation_log')->insert([
'user_id' => $user_id,
'client_ip' => request()->ip(),
'module' => $types,
'action_id' => $action_id,
'content' => implode('.|.', $message),
'create_time' => time()
]);
}
} elseif ($content) {
$data = [];
@ -864,15 +866,6 @@ function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData =
$data['action_id'] = $action_id;
$data['content'] = $content;
db('admin_action_record')->insert($data);
# 数据操作日志
db('admin_operation_log')->insert([
'user_id' => $user_id,
'client_ip' => request()->ip(),
'module' => $types,
'action_id' => $action_id,
'content' => $content,
'create_time' => time()
]);
}
}
@ -923,7 +916,7 @@ function checkVerify($saftCode = '5kcrm@')
$parmList['sessionId'] = $header['sessionId'];
$authkey = $header['authKey'];
$clientSign = $parmList['client_sign'];
if ($clientSign) {
unset($parmList['client_sign']);
if (count($parmList) > 0) {
@ -1348,7 +1341,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) {
@ -1609,12 +1602,12 @@ function nextCheckData($user_id, $flow_id, $types, $types_id, $order_id, $check_
$new_order_id = $order_id;
$max_order_id = db('admin_examine_step')->where(['flow_id' => $flow_id])->max('order_id'); //审批流最大排序ID
$examineStepModel = new \app\admin\model\ExamineStep();
$stepInfo = $examineStepModel->getStepByOrder($flow_id, $new_order_id); //审批步骤
$next_user_ids = [];
$is_end = 0; //审批结束
//固定流程status 1负责人主管2指定用户任意一人3指定用户多人会签4上一级审批人主管
//当前步骤审批人user_id
$step_user_ids = $examineStepModel->getUserByStep($stepInfo['step_id'], $user_id);
if ($step_user_ids) {
@ -1771,7 +1764,7 @@ function getWhereUserByParam(&$where, $field = 'owner_user_id', $m = '', $c = ''
{
$param = request()->param();
$userModel = new UserModel();
$map_user_ids = [];
if ($param['user_id']) {
$map_user_ids = array($param['user_id']);
@ -1782,7 +1775,7 @@ function getWhereUserByParam(&$where, $field = 'owner_user_id', $m = '', $c = ''
$where[$field] = array('in', $map_user_ids);
return;
}
$perUserIds = $userModel->getUserByPer($m, $c, $a); //权限范围内userIds
$userIds = array_intersect($map_user_ids, $perUserIds); //数组交集
$where[$field] = array('in', $userIds);
@ -1877,10 +1870,10 @@ function download($file, $name = '', $del = false)
'error' => '文件路径错误',
]);
}
$fp = fopen($file, 'r');
$size = filesize($file);
//下载文件需要的头
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
@ -1889,12 +1882,12 @@ function download($file, $name = '', $del = false)
$file_name = $name != '' ? $name : pathinfo($file, PATHINFO_BASENAME);
// urlencode 处理中文乱码
header("Content-Disposition:attachment; filename=" . urlencode($file_name));
// 导出数据时 csv office Excel 需要添加bom头
if (pathinfo($file, PATHINFO_EXTENSION) == 'csv') {
echo "\xEF\xBB\xBF"; // UTF-8 BOM
}
$fileCount = 0;
$fileUnit = 1024;
while (!feof($fp) && $size - $fileCount > 0) {
@ -1903,7 +1896,7 @@ function download($file, $name = '', $del = false)
$fileCount += $fileUnit;
}
fclose($fp);
// 删除
if ($del) @unlink($file);
die();
@ -1924,7 +1917,7 @@ function tempFileName($ext = '')
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
$ext = trim($ext, '.');
do {
$temp_file = md5(time() . rand(1000, 9999));
@ -1953,7 +1946,7 @@ function delDir($dir)
}
}
}
closedir($dh);
//删除当前文件夹:
@rmdir($dir);
@ -2065,7 +2058,7 @@ function getTimeArray($start = null, $end = null)
break;
}
}
$between = [$start, $end];
$list = [];
$len = ($end - $start) / 86400;
@ -2094,7 +2087,7 @@ function getTimeArray($start = null, $end = null)
$start = $item['end_time'] + 1;
}
}
return [
'list' => $list, // 时间段列表
'time_format' => $time_format, // 时间格式 mysql 格式化时间戳
@ -2127,8 +2120,8 @@ function DBBackup($file = '', $path = '')
$username = config('database.username');
$password = config('database.password');
$dsn = "{$type}:host={$host};dbname={$dbname};port={$port}";
if ($file == '') {
$save_path = dirname(APP_PATH) . DS . 'data' . DS . date('Ym') . DS;
if (!file_exists($save_path) && !mkdir($save_path, '0777', true)) {
@ -2136,11 +2129,11 @@ function DBBackup($file = '', $path = '')
}
$file = $save_path . date('d_H_i') . '_db_backup' . '.sql';
}
if (file_exists($file)) {
return '数据库备份文件已存在自动备份时间间隔需大于1分钟。';
}
try {
$backup = new \com\Mysqldump($dsn, $username, $password);
$backup->start($file);
@ -2148,7 +2141,7 @@ function DBBackup($file = '', $path = '')
} catch (\Exception $e) {
return '备份失败,请手动备份。错误原因:' . $e->getMessage();
}
}
/**
@ -2171,17 +2164,17 @@ if (!function_exists('isSuperAdministrators')) {
function isSuperAdministrators($userId)
{
$status = false;
$apiCommon = new \app\admin\controller\ApiCommon();
$userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
$data = db('admin_access')->where('user_id', $userId)->column('group_id');
if ($userId == 1 || in_array(1, $data)) {
$status = true;
}
return $status;
}
}
@ -2195,11 +2188,11 @@ if (!function_exists('getFieldGrantData')) {
function getFieldGrantData($userId)
{
$result = [];
$apiCommon = new \app\admin\controller\ApiCommon();
$userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
$grantData = Db::query("
SELECT
`grant`.`module`, `grant`.`column`, `grant`.`content`
@ -2212,12 +2205,14 @@ if (!function_exists('getFieldGrantData')) {
WHERE
`access`.`user_id` =
" . $userId);
# 存在多角色多授权的情况
foreach ($grantData AS $key => $value) {
foreach ($grantData as $key => $value) {
if (empty($value['module']) || empty($value['column'])) continue;
$result[$value['module'] . '_' . $value['column']][] = !empty($value['content']) ? unserialize($value['content']) : [];
}
return $result;
}
}
@ -2234,27 +2229,34 @@ if (!function_exists('getFieldGrantStatus')) {
{
# 默认状态都是不能查看、不能编辑,通过配置来取最大权限。
$result = ['read' => 0, 'write' => 0];
foreach ($grantData AS $key => $value) {
# 对于不在权限控制之内的字段将状态都改为1。
foreach ($grantData as $key => $value) {
$fieldBool = false;
foreach ($value AS $ke => $va) {
if ($va['field'] == $field) {
$result['read'] = $va['read'] > $result['read'] ? $va['read'] : $result['read'];
foreach ($value as $ke => $va) {
# 多个字段授权,只取最高的读权限
if ($va['field'] == $field && $result['read'] == 0) {
$result['read'] = $va['read'] > $result['read'] ? $va['read'] : $result['read'];
}
# 多个字段授权,只取最高的写权限
if ($va['field'] == $field && $result['write'] == 0) {
$result['write'] = $va['write'] > $result['write'] ? $va['write'] : $result['write'];
$fieldBool = true;
}
if ($va['field'] == $field) $fieldBool = true;
}
# 对于不在权限控制之内的字段将状态都改为1。
if (!$fieldBool) {
$result['read'] = 1;
$result['read'] = 1;
$result['write'] = 1;
}
}
return $result;
}
/**
* 仪表盘日志使用
* 根据类型获取开始结束时间戳数组
@ -2299,7 +2301,7 @@ if (!function_exists('getFieldGrantStatus')) {
$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) {
@ -2317,7 +2319,7 @@ if (!function_exists('getFieldGrantStatus')) {
$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);
break;
case 'lastQuarter' :
@ -2377,4 +2379,152 @@ if (!function_exists('getFieldGrantStatus')) {
}
return $timeArr;
}
/**
* 系统操作日志
* @param int $user_id 用户
* @param string $types 方法所属模块
* @param int $action_id 操作
* @param string $module_name 模块
* @param string $action_name 修改添加删除新建
* @param array $oldData 旧数据
* @param array $newData 新数据
* @param string $target_name 被操作对象
* @param string $content 添加时创建使用
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/3/26 0026 15:10
*/
function SystemActionLog($user_id, $types, $module_name, $action_id, $action_name, $target_name, $oldData = [], $newData = [], $content = '')
{
//action_name 修改添加删除新建 action_id 操作id client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module_name 模块 系统管理 固定 user_id 用户
$data = [];
$data['user_id'] = $user_id;
$data['create_time'] = time();
$data['client_ip'] = request()->ip();
$data['action_id'] = $action_id;
$data['action_name'] = $action_name;
$data['target_name'] = $target_name;
$data['module_name'] = $module_name;
$data['controller_name'] = $types;
$data['content'] = $content;
db('admin_system_log')->insert($data);
}
/**
* 系统操作日志
* @param int $user_id 用户
* @param string $types 方法所属模块
* @param string $action_name 修改添加删除新建
* @param string $target_name 被操作对象
* @param array $oldData 旧数据
* @param array $newData 新数据
* @param string $content 添加时创建使用
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/2 0026 15:10
*/
function RecordActionLog($user_id, $types, $action_name, $target_name, $oldData = [], $newData = [], $content = '')
{
//action_name 修改 添加 删除 client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module 模块 user_id 用户
if (is_array($oldData) && is_array($newData) && $user_id) {
$differentData = array_diff_assoc($newData, $oldData);
$fieldModel = new FieldModel();
$userModel = new UserModel();
$structureModel = new \app\admin\model\Structure();
$field_arr = $fieldModel->getField(['types' => $types, 'unFormType' => ['file', 'form']]); //获取字段属性
$newFieldArr = array();
foreach ($field_arr as $k => $v) {
$newFieldArr[$v['field']] = $v;
}
$unField = ['update_time', 'create_time']; //定义过滤字段
$message = [];
$un_form_type = ['file', 'form'];
foreach ($differentData as $k => $v) {
if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
$field_name = '';
$field_name = $newFieldArr[$k]['name'];
$new_value = $v ?: '空';
$old_value = $oldData[$k] ?: '空';
switch ($newFieldArr[$k]['form_type']) {
case 'datetime' :
$new_value = $v ? date('Y-m-d', $v) : '';
$old_value = date('Y-m-d', $oldData[$k]);
if (!empty($v) && !empty($oldData[$k]))
break;
case 'user' :
$new_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($v))) : '';
$old_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($oldData[$k]))) : '';
break;
case 'structure' :
$new_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($v))) : '';
$old_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($oldData[$k]))) : '';
break;
case 'business_status' :
$new_value = $v ? db('crm_business_status')->where(['status_id' => $v])->value('name') : '';
$old_value = $v ? db('crm_business_status')->where(['status_id' => $oldData[$k]])->value('name') : '';
break;
case 'business_type' :
$new_value = $v ? db('crm_business_type')->where(['type_id' => $v])->value('name') : '';
$old_value = $v ? db('crm_business_type')->where(['type_id' => $oldData[$k]])->value('name') : '';
break;
case 'customer' :
$new_value = $v ? db('crm_customer')->where(['customer_id' => $v])->value('name') : '';
$old_value = $v ? db('crm_customer')->where(['customer_id' => $oldData[$k]])->value('name') : '';
break;
case 'category' :
$new_value = $v ? db('crm_product_category')->where(['category_id' => $v])->value('name') : '';
$old_value = $v ? db('crm_product_category')->where(['category_id' => $oldData[$k]])->value('name') : '';
break;
case 'business' :
$new_value = $v ? db('crm_business')->where(['business_id' => $v])->value('name') : '';
$old_value = $v ? db('crm_business')->where(['business_id' => $oldData[$k]])->value('name') : '';
break;
case 'visit' :
$new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
$old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
break;
case 'single_user' :
$new_value = $v ? db('admin_user')->where(['id' => $v])->value('realname') : '';
$old_value = $v ? db('admin_user')->where(['id' => $oldData['owner_user_id']])->value('realname') : '';
break;
case 'floatnumber' :
$new_value = $v ? number_format($v, 2) : '';
break;
}
if ($newFieldArr[$k]['field'] == 'check_status') {
$statusArr = ['0' => '待审核', '1' => '审核中', '2' => '审核通过', '3' => '已拒绝', '4' => '已撤回', '5' => '未提交'];
$new_value = $statusArr[$v];
$old_value = $statusArr[$oldData[$k]];
}
if ($old_value != $new_value) {
$message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
}
}
}
if ($message) {
$data = [];
$data['user_id'] = $user_id;
$data['create_time'] = time();
$data['client_ip'] = request()->ip();
$data['action_name'] = $action_name;
$data['action_id'] = 1;
$data['target_name'] = $target_name;
$data['module'] = $types; //子模块 客户线索
$data['content'] = implode(',', $message);
db('admin_operation_log')->insert($data);
}
} elseif ($content) {
$data = [];
$data['user_id'] = $user_id;
$data['create_time'] = time();
$data['client_ip'] = request()->ip();
$data['action_name'] = $action_name;
$data['target_name'] = $target_name;
$data['action_id'] = 1;
$data['module'] = $types; //子模块 客户线索
$data['content'] = $content;
db('admin_operation_log')->insert($data);
}
}
}

@ -0,0 +1,411 @@
<?php
/**
* 使用定时器将符合条件的用户回收到公海池
*
* @author fanqi
* @since 2021-03-31
*/
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 PoolCommand extends Command
{
protected $timer;
protected $interval = 10;
protected function configure()
{
$this->setName('pool')
->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($this->interval, function () {
# 只在凌晨12点至6点间执行
if ((int)date('H') >= 0 && (int)date('H') < 6) {
# 公海规则
$ruleList = db('crm_customer_pool_rule')->alias('rule')->field('rule.*')
->join('__CRM_CUSTOMER_POOL__ pool', 'pool.pool_id = rule.pool_id', 'LEFT')->where('pool.status', 1)->select();
if (!empty($ruleList)) {
# 符合公海条件的客户IDS
$customerIds = $this->getQueryCondition($ruleList);
# 整理客户公海关联数据
$poolRelationData = $this->getCustomerPoolRelationData($customerIds);
# 整理修改客户数据的条件(进入公海时间,前负责人...
$customerWhere = $this->getCustomerQueryCondition($customerIds);
Db::startTrans();
try {
# 将客户退回公海
if (!empty($poolRelationData)) Db::name('crm_customer_pool_relation')->insertAll($poolRelationData);
# 修改客户数据
if (!empty($customerWhere)) {
Db::name('crm_customer')->whereIn('customer_id', $customerWhere)->exp('before_owner_user_id', 'owner_user_id')->update([
'ro_user_id' => '',
'rw_user_id' => '',
'owner_user_id' => 0,
'into_pool_time' => time()
]);
}
# 删除联系人的负责人
Db::name('crm_contacts')->whereIn('customer_id', $customerWhere)->update(['owner_user_id' => '']);
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);
# 创建定时器任务
$task = new Worker();
$task->name = 'pool';
$task->count = 1;
$task->onWorkerStart = [$this, 'start'];
$task->runAll();
}
/**
* 整理修改客户数据的条件
*
* @param array $customerIds 客户ID
* @author fanqi
* @since 2021-04-01
* @return array
*/
private function getCustomerQueryCondition($customerIds)
{
$result = [];
foreach ($customerIds AS $k1 => $v1) {
foreach ($v1 AS $k2 => $v2) {
$result[] = $v2;
}
}
return array_unique($result);
}
/**
* 客户公海关联数据
*
* @param array $customerIds 客户ID
* @author fanqi
* @since 2021-04-01
* @return array
*/
private function getCustomerPoolRelationData($customerIds)
{
$result = [];
# 用于排重
$repeat = [];
foreach ($customerIds AS $k1 => $v1) {
$customerArray = array_unique($v1);
foreach ($customerArray AS $k2 => $v2) {
if (!empty($repeat[$k1][$v2])) continue;
$result[] = [
'pool_id' => $k1,
'customer_id' => $v2
];
$repeat[$k1][$v2] = $v2;
}
}
return $result;
}
/**
* 获取符合公海条件的客户
*
* @param array $rules 公海规则数据
* @author fanqi
* @since 2021-04-01
* @return array
*/
private function getQueryCondition($rules)
{
$result = [];
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']));
}
return $result;
}
/**
* N天内无新建跟进记录的客户
*
* @param int $type 类型1 所有用户不分级别2 根据用户级别区分
* @param Json $levels 级别数据
* @param int $dealStatus 是否排除成交用户1 排除0 不排除
* @param int $businessStatus 是否排除有商机用户1 排除0 不排除
* @author fanqi
* @since 2021-04-01
* @return array
*/
private function getFollowUpQueryResult($type, $levels, $dealStatus, $businessStatus)
{
# 转换格式
$levels = json_decode($levels, true);
# 默认条件
$where = "`customer`.`owner_user_id` > 0";
# 所有用户,不区分级别
if ($type == 1) {
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`)))";
}
}
}
# 根据用户级别设置条件
if ($type == 2) {
foreach ($levels AS $k1 => $v1) {
if (!empty($v1['level']) && !empty($v1['limit_day'])) {
$time = (time() - 24 * 60 * 60 * $v1['limit_day']);
if ($k1 == 0) {
$where .= " AND ( ((`customer`.`level` = '".$v1['level']."' AND `customer`.`last_time` < ".$time." AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` < ".$time." AND ISNULL(`customer`.`last_time`)))";
} else {
$where .= " OR ((`customer`.`level` = '".$v1['level']."' AND `customer`.`last_time` < " . $time . " AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` < " . $time . " AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` < " . $time . " AND ISNULL(`customer`.`last_time`)))";
}
}
}
# 获取最小天数,对于没有设置级别的客户数据使用
$minLimit = $this->getMinDay($levels);
$minTime = (time() - 24 * 60 * 60 * $minLimit);
$where .= " OR ((!`customer`.`level` AND `customer`.`last_time` < ".$minTime." AND `customer`.`last_time` > `customer`.`obtain_time`) OR (!`customer`.`level` AND `customer`.`obtain_time` < ".$minTime." AND `customer`.`obtain_time` > `customer`.`last_time`) OR (!`customer`.`level` AND `customer`.`obtain_time` < ".$minTime." AND ISNULL(`customer`.`last_time`))) )";
}
# 选择不进入公海的客户(已成交客户)
if (!empty($dealStatus)) $where .= " AND (`customer`.`deal_status` <> '已成交' OR ISNULL(`customer`.`deal_status`))";
# 选择不进入公海的客户(有商机客户)
if (!empty($businessStatus)) $where .= " AND ISNULL(`business`.`customer_id`)";
# 锁定的客户不提醒
$where .= " AND `customer`.`is_lock` = 0";
# 查询符合条件的客户
return db('crm_customer')
->alias('customer')->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
->where($where)->column('customer.customer_id');
}
/**
* N天内无新建商机的客户
*
* @param int $type 类型1 所有用户不分级别2 根据用户级别区分
* @param Json $levels 级别数据
* @param int $dealStatus 是否排除成交用户1 排除0 不排除
* @author fanqi
* @since 2021-04-01
* @return array|false|string
*/
private function getBusinessQueryResult($type, $levels, $dealStatus)
{
# 转换格式
$levels = json_decode($levels, true);
# 默认条件
$where = "`customer`.`owner_user_id` > 0";
# 所有用户,不区分级别
if ($type == 1) {
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`) )";
}
}
}
# 根据用户级别设置条件
if ($type == 2) {
foreach ($levels AS $k1 => $v1) {
if (!empty($v1['level']) && !empty($v1['limit_day'])) {
$time = time() - 24 * 60 * 60 * $v1['limit_day'];
if ($k1 == 0) {
$where .= " AND ( ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < ".$time." AND `customer`.`level` = '".$v1['level']."') OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `business`.`create_time` AND `customer`.`level` = '".$v1['level']."') OR (`business`.`create_time` < ".$time." AND `business`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))";
} else {
$where .= " OR ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < ".$time." AND `customer`.`level` = '".$v1['level']."') OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `business`.`create_time` AND `customer`.`level` = '".$v1['level']."') OR (`business`.`create_time` < ".$time." AND `business`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))";
}
}
}
# 获取最小天数,对于没有设置级别的客户数据使用
$minLimit = $this->getMinDay($levels);
$minTime = (time() - 24 * 60 * 60 * $minLimit);
$where .= " OR ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` < ".$minTime." AND !`customer`.`level`) OR (`customer`.`obtain_time` < ".$minTime." AND `customer`.`obtain_time` > `business`.`create_time` AND !`customer`.`level`) OR (`business`.`create_time` < ".$minTime." AND `business`.`create_time` > `customer`.`obtain_time` AND !`customer`.`level`)) )";
}
# 选择不进入公海的客户(已成交客户)
if (!empty($dealStatus)) $where .= " AND (`customer`.`deal_status` <> '已成交' OR ISNULL(`customer`.`deal_status`))";
# 锁定的客户不提醒
$where .= " AND `customer`.`is_lock` = 0";
# 查询匹配条件的客户
return db('crm_customer')->alias('customer')
->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
->where($where)->column('customer.customer_id');
}
/**
* N天内没有成交的客户
*
* @param int $type 类型1 所有用户不分级别2 根据用户级别区分
* @param Json $levels 级别数据
* @param int $businessStatus 是否排除有商机用户1 排除0 不排除
* @author fanqi
* @since 2021-04-01
* @return array|false|string
*/
private function getDealQueryResult($type, $levels, $businessStatus)
{
# 转换格式
$levels = json_decode($levels, true);
# 默认条件
$where = "`customer`.`owner_user_id` > 0";
# 所有用户,不区分级别
if ($type == 1) {
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`) )";
}
}
}
# 根据用户级别设置条件
if ($type == 2) {
foreach ($levels AS $k1 => $v1) {
if (!empty($v1['level']) && !empty($v1['limit_day'])) {
$time = time() - 24 * 60 * 60 * $v1['limit_day'];
if ($k1 == 0) {
$where .= " AND ( ((ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < ".$time." AND `customer`.`level` = '".$v1['level']."') OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `contract`.`create_time` AND `customer`.`level` = '".$v1['level']."') OR (`contract`.`create_time` < ".$time." AND `contract`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))";
} else {
$where .= " OR ((ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < ".$time." AND `customer`.`level` = '".$v1['level']."') OR (`customer`.`obtain_time` < ".$time." AND `customer`.`obtain_time` > `contract`.`create_time` AND `customer`.`level` = '".$v1['level']."') OR (`contract`.`create_time` < ".$time." AND `contract`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))";
}
}
}
# 获取最小天数,对于没有设置级别的客户数据使用
$minLimit = $this->getMinDay($levels);
$minTime = (time() - 24 * 60 * 60 * $minLimit);
$where .= " OR ((ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` < ".$minTime." AND !`customer`.`level`) OR (`customer`.`obtain_time` < ".$minTime." AND `customer`.`obtain_time` > `contract`.`create_time` AND !`customer`.`level`) OR (`contract`.`create_time` < ".$minTime." AND `contract`.`create_time` > `customer`.`obtain_time` AND !`customer`.`level`)) )";
}
# 选择不进入公海的客户(有商机客户)
if (!empty($businessStatus)) $where .= " AND ISNULL(`business`.`customer_id`)";
# 锁定的客户不提醒
$where .= " AND `customer`.`is_lock` = 0";
# 查询符合条件的客户
return db('crm_customer')->alias('customer')
->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
->join('__CRM_CONTRACT__ contract', 'contract.customer_id = customer.customer_id', 'LEFT')
->where($where)->column('customer.customer_id');
}
/**
* 获取公海规则最小数字(最快进入公海天数)
*
* @param $data
* @author fanqi
* @since 2021-04-19
* @return int
*/
private function getMinDay($data)
{
$number = 1;
foreach ($data AS $k1 => $v1) {
if (empty($number) || $v1['limit_day'] < $number) $number = $v1['limit_day'];
}
return $number;
}
}

@ -96,6 +96,8 @@ class Achievement extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
if ($model->createData($param)) {
# 系统操作日志
SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1, 'save','业绩目标设置' , '', '','添加了业绩目标');
return resultArray(['data' => '添加成功']);
} else {
return resultArray(['error' => $model->getError()]);
@ -129,9 +131,11 @@ class Achievement extends ApiCommon
public function update()
{
$model = model('Achievement');
$userInfo = $this->userInfo;
$param = $this->param;
if ($model->updateData($param)) {
# 系统操作日志
SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1, 'update','业绩目标设置' , '', '','设置了业绩目标');
return resultArray(['data' => '编辑成功']);
} else {
return resultArray(['error' => $model->getError()]);
@ -150,9 +154,10 @@ class Achievement extends ApiCommon
if (empty($this->param['achievement_id'])) return resultArray(['error' => '参数错误!']);
$model = new \app\crm\model\Achievement();
$userInfo = $this->userInfo;
if (!$model->delete($this->param['achievement_id'])) return resultArray(['error' => '操作失败!']);
# 系统操作日志
SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1, 'update','业绩目标设置' , '', '','删除了业绩目标');
return resultArray(['data' => '操作成功!']);
}
}

@ -24,7 +24,7 @@ class Activity extends ApiCommon
{
$action = [
'permission'=>[],
'allow'=>['index', 'save', 'read', 'update', 'delete', 'getphrase', 'setphrase', 'getrecordauth']
'allow'=>['index', 'save', 'read', 'update', 'delete', 'getphrase', 'setphrase', 'getrecordauth','excelimport','excelexport','exceldownload']
];
Hook::listen('check_auth',$action);
$request = Request::instance();
@ -77,7 +77,6 @@ class Activity extends ApiCommon
$param['user_id'] = $this->userInfo['id'];
if (!$activityLogic->save($param)) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']);
}
@ -144,7 +143,6 @@ class Activity extends ApiCommon
if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']);
if (!$activityLogic->delete($this->param['activity_id'])) return resultArray(['error' => '操作失败!']);
return resultArray(['data' => '操作成功!']);
}
@ -196,4 +194,239 @@ 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 = ''){
$param = $this->param;
$excelModel = new \app\admin\model\Excel();
$field_list=$this->importData($param);
$types='crm_activity';
$excelModel->importDown($field_list,$types,$save_path);
}
/**
* 导入导出模板标题
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/13 0013 11:15
*/
public function importData($param){
switch ($param['label']){
case 1 :
$field = [
'2' => [
'name' => '所属线索',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'datetime',
'is_null' => 1,
]
];
break;
case 3:
$field = [
'2' => [
'name' => '所属联系人',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'datetime',
'is_null' => 1,
],
];
break;
case 5:
$field = [
'2' => [
'name' => '所属商机',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'text',
'is_null' => 1,
]
];
break;
case 6:
$field = [
'2' => [
'name' => '所属合同',
'field' => 'activity_type_id',
'types' => 'log',
'form_type' => 'text',
'is_null' => 1,
],
];
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,
],
'2' => [
'name' => '所属客户',
'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' => [
'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',
]
];
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' => [
'name' => '跟进方式',
'field' => 'category',
'types' => 'log',
'form_type' => 'text',
],
];
// 导入的字段列表
if(!empty($param['down'])){
$field_list = [
'0' => ['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'],
];
}else{
if(empty($field_list)){
$field_list=array_merge($fields,$field);
}
}
return $field_list;
}
/**
* 导入数据
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/10 0010 16:27
*/
public function excelImport(){
$param = $this->param;
$field_list=$this->importData($param['label']);
$excelModel = new \app\admin\model\Excel();
$file = request()->file('file');
switch ($param['label']){
case 1 :
$param['types']='crm_leads';
$param['activity_type']=1;
break;
case 3:
$param['types']='crm_contacts';
$param['activity_type']=3;
break;
case 5:
$param['types']='crm_business';
$param['activity_type']=5;
break;
case 6:
$param['types']='crm_contract';
$param['activity_type']=6;
break;
case 2:
$param['types']='crm_customer';
$param['activity_type']=2;
break;
}
$res = $excelModel->ActivityImport($file,$field_list, $param,$this);
if (!$res) {
return resultArray(['error' => $excelModel->getError()]);
}
return resultArray(['data' => $excelModel->getError()]);
}
/**
* 导出跟进记录
* action 列表分辨是否导出
* label 导出类型 合同 客户 联系人
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/13 0013 11:32
*/
public function excelExport(){
$activityLogic=new ActivityLogic();
$indexLogic=new \app\crm\logic\IndexLogic();
$param = $this->param;
$param['action']='crm_activity';
$list=$indexLogic->activityList($param);
// $param['down']=1;
$field_list=$this->importData($param);
$data=$activityLogic->excelExport($field_list,$list);
return $data;
}
}

@ -17,47 +17,47 @@ use think\Db;
class Business extends ApiCommon
{
use StarTrait, SearchConditionTrait;
/**
* 用于判断权限
* @permission 无限制
* @allow 登录用户可访问
* @other 其他根据系统设置
**/
**/
public function _initialize()
{
$action = [
'permission'=>[''],
'allow'=>['statuslist','advance','product','system','count','setprimary']
'permission' => [''],
'allow' => ['statuslist', 'advance', 'product', 'system', 'count', 'setprimary']
];
Hook::listen('check_auth',$action);
Hook::listen('check_auth', $action);
$request = Request::instance();
$a = strtolower($request->action());
$a = strtolower($request->action());
if (!in_array($a, $action['permission'])) {
parent::_initialize();
}
}
}
/**
* 商机列表
* @author Michael_xu
* @return
* @author Michael_xu
*/
public function index()
{
$businessModel = model('Business');
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$data = $businessModel->getDataList($param);
$param['user_id'] = $userInfo['id'];
$data = $businessModel->getDataList($param);
return resultArray(['data' => $data]);
}
/**
* 添加商机
* @param
* @return
* @author Michael_xu
* @param
* @return
*/
public function save()
{
@ -66,19 +66,19 @@ class Business extends ApiCommon
$userInfo = $this->userInfo;
$param['create_user_id'] = $userInfo['id'];
$param['owner_user_id'] = $userInfo['id'];
if ($businessModel->createData($param)) {
return resultArray(['data' => '添加成功']);
} else {
return resultArray(['error' => $businessModel->getError()]);
}
}
/**
* 商机详情
* @author Michael_xu
* @param
* @param
* @return
* @author Michael_xu
*/
public function read()
{
@ -92,11 +92,11 @@ class Business extends ApiCommon
$auth_user_ids = $userModel->getUserByPer('crm', 'business', 'read');
//读权限
$roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
$rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
if (!in_array($data['owner_user_id'],$auth_user_ids) && !$rwPre && !$roPre) {
$rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
if (!in_array($data['owner_user_id'], $auth_user_ids) && !$rwPre && !$roPre) {
$authData['dataAuth'] = (int)0;
return resultArray(['data' => $authData]);
}
}
//商机状态组
$data['status_list'] = $businessStatusModel->getDataById($data['type_id']);
$data['lose_reason'] = Db::name('CrmBusinessLog')
@ -108,15 +108,15 @@ class Business extends ApiCommon
}
return resultArray(['data' => $data]);
}
/**
* 编辑商机
* @author Michael_xu
* @param
* @param
* @return
* @author Michael_xu
*/
public function update()
{
{
$businessModel = model('Business');
$userModel = new \app\admin\model\User();
$param = $this->param;
@ -126,31 +126,32 @@ class Business extends ApiCommon
$data = $businessModel->getDataById($param['id']);
$auth_user_ids = $userModel->getUserByPer('crm', 'business', 'update');
//读写权限
$rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
if (!in_array($data['owner_user_id'],$auth_user_ids) && !$rwPre) {
$rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
if (!in_array($data['owner_user_id'], $auth_user_ids) && !$rwPre) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
}
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
if ($businessModel->updateDataById($param, $param['id'])) {
return resultArray(['data' => '编辑成功']);
} else {
return resultArray(['error' => $businessModel->getError()]);
}
}
}
/**
* 删除商机(逻辑删)
* @author Michael_xu
* @param
* @param
* @return
* @author Michael_xu
*/
public function delete()
{
$param = $this->param;
$param = $this->param;
$userInfo = $this->userInfo;
$businessModel = model('Business');
$recordModel = new \app\admin\model\Record();
$fileModel = new \app\admin\model\File();
$actionRecordModel = new \app\admin\model\ActionRecord();
$actionRecordModel = new \app\admin\model\ActionRecord();
if (!is_array($param['id'])) {
$business_id[] = $param['id'];
} else {
@ -158,57 +159,60 @@ class Business extends ApiCommon
}
$delIds = [];
$errorMessage = [];
//数据权限判断
$userModel = new \app\admin\model\User();
$auth_user_ids = $userModel->getUserByPer('crm', 'business', 'delete');
foreach ($business_id as $k=>$v) {
foreach ($business_id as $k => $v) {
$isDel = true;
//数据详情
$data = $businessModel->getDataById($v);
if (!$data) {
$isDel = false;
$errorMessage[] = 'id为'.$v.'的商机删除失败,错误原因:'.$businessModel->getError();
$errorMessage[] = 'id为' . $v . '的商机删除失败,错误原因:' . $businessModel->getError();
}
if (!in_array($data['owner_user_id'],$auth_user_ids)) {
if (!in_array($data['owner_user_id'], $auth_user_ids)) {
$isDel = false;
$errorMessage[] = '名称为'.$data['name'].'的商机删除失败,错误原因:无权操作';
$errorMessage[] = '名称为' . $data['name'] . '的商机删除失败,错误原因:无权操作';
}
if ($isDel) {
if (db('crm_contract')->where(['business_id'=> $v, 'check_status' => ['in', '0,1,2']])->value('contract_id')) {
if (db('crm_contract')->where(['business_id' => $v, 'check_status' => ['in', '0,1,2']])->value('contract_id')) {
$isDel = false;
$errorMessage[] = '名称为'.$data['name'].'的商机删除失败,错误原因:商机下关联的有合同,无法删除!';
}
$errorMessage[] = '名称为' . $data['name'] . '的商机删除失败,错误原因:商机下关联的有合同,无法删除!';
}
}
if ($isDel) {
$delIds[] = $v;
}
}
}
$dataInfo = $businessModel->where('visit_id',['in',$delIds])->select();
if ($delIds) {
$data = $businessModel->delDatas($delIds);
if (!$data) {
return resultArray(['error' => $businessModel->getError()]);
}
//删除跟进记录
$recordModel->delDataByTypes(5,$delIds);
$recordModel->delDataByTypes(5, $delIds);
//删除关联附件
$fileModel->delRFileByModule('crm_business',$delIds);
$fileModel->delRFileByModule('crm_business', $delIds);
//删除关联操作记录
$actionRecordModel->delDataById(['types'=>'crm_business','action_id'=>$delIds]);
actionLog($delIds,'','','');
$actionRecordModel->delDataById(['types' => 'crm_business', 'action_id' => $delIds]);
foreach ($dataInfo as $k => $v) {
RecordActionLog($userInfo['id'], 'crm_business', 'delete', $v['name'], '', '', '删除了商机:' . $v['name']);
}
}
if ($errorMessage) {
return resultArray(['error' => $errorMessage]);
} else {
return resultArray(['data' => '删除成功']);
}
}
}
/**
* 符合条件的商机状态组
* @author Michael_xu
* @param
* @param
* @return
* @author Michael_xu
*/
public function statusList()
{
@ -218,28 +222,28 @@ class Business extends ApiCommon
if (!$list) {
$userInfo = $this->userInfo;
$list = db('crm_business_type')
->field(['name', 'status', 'structure_id', 'type_id'])
->where(['structure_id' => ['like','%,'.$userInfo['structure_id'].',%'],'status' => 1])
->where('is_display', 1)
->whereOr('structure_id','')
->select();
foreach ($list as $k=>$v) {
->field(['name', 'status', 'structure_id', 'type_id'])
->where(['structure_id' => ['like', '%,' . $userInfo['structure_id'] . ',%'], 'status' => 1])
->where('is_display', 1)
->whereOr('structure_id', '')
->select();
foreach ($list as $k => $v) {
$list[$k]['statusList'] = $businessStatusModel->getDataList($v['type_id']);
}
cache($key, $list, config('business_status_cache_time'));
}
return resultArray(['data' => $list]);
}
}
/**
* 商机转移
* @author Michael_xu
* @param owner_user_id 变更负责人
* @param is_remove 1移出2转为团队成员
* @param type 权限 1只读2读写
* @return
*/
* @author Michael_xu
*/
public function transfer()
{
$param = $this->param;
@ -248,12 +252,12 @@ 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' => '变更负责人不能为空']);
}
if (!$param['business_id'] || !is_array($param['business_id'])) {
return resultArray(['error' => '请选择需要转移的商机']);
return resultArray(['error' => '请选择需要转移的商机']);
}
$is_remove = $param['is_remove'] == 2 ? 2 : 1;
@ -262,22 +266,22 @@ class Business extends ApiCommon
$data = [];
$data['owner_user_id'] = $param['owner_user_id'];
$data['update_time'] = time();
$ownerUserName = $userModel->getUserNameById($param['owner_user_id']);
$errorMessage = [];
foreach ($param['business_id'] as $business_id) {
$businessInfo = $businessModel->getDataById($business_id);
if (!$businessInfo) {
$errorMessage[] = '名称:为《'.$businessInfo['name'].'》的商机转移失败,错误原因:数据不存在;';
$errorMessage[] = '名称:为《' . $businessInfo['name'] . '》的商机转移失败,错误原因:数据不存在;';
continue;
}
//权限判断
if (!in_array($businessInfo['owner_user_id'],$authIds)) {
$errorMessage[] = $businessInfo['name'].'"转移失败,错误原因:无权限;';
if (!in_array($businessInfo['owner_user_id'], $authIds)) {
$errorMessage[] = $businessInfo['name'] . '"转移失败,错误原因:无权限;';
continue;
}
//团队成员
teamUserId(
'crm_business',
@ -287,10 +291,10 @@ class Business extends ApiCommon
$is_remove,
0
);
$resBusiness = db('crm_business')->where(['business_id' => $business_id])->update($data);
if (!$resBusiness) {
$errorMessage[] = $businessInfo['name'].'"转移失败,错误原因:数据出错;';
$errorMessage[] = $businessInfo['name'] . '"转移失败,错误原因:数据出错;';
continue;
} else {
$businessArray = [];
@ -305,23 +309,25 @@ class Business extends ApiCommon
}
db('crm_business')->where('business_id', $business_id)->update($businessArray);
}
//修改记录
updateActionLog($userInfo['id'], 'crm_business', $business_id, '', '', '将商机转移给:'.$ownerUserName);
updateActionLog($userInfo['id'], 'crm_business', $business_id, '', '', '将商机转移给:' . $ownerUserName);
RecordActionLog($userInfo['id'], 'crm_business', 'transfer', $businessInfo['name'], '', '', '将商机:' . $businessInfo['name'] . '转移给:' . $ownerUserName);
}
if (!$errorMessage) {
return resultArray(['data' => '转移成功']);
} else {
return resultArray(['error' => $errorMessage]);
}
}
}
/**
* 相关产品
* @author Michael_xu
* @param
* @param
* @return
*/
* @author Michael_xu
*/
public function product()
{
$productModel = model('Product');
@ -331,44 +337,44 @@ class Business extends ApiCommon
if (!$param['business_id']) {
return resultArray(['error' => '参数错误']);
}
$businessInfo = db('crm_business')->where(['business_id' => $param['business_id']])->find();
$businessInfo = db('crm_business')->where(['business_id' => $param['business_id']])->find();
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'business', 'read');
//读写权限
$roPre = $userModel->rwPre($userInfo['id'], $businessInfo['ro_user_id'], $businessInfo['rw_user_id'], 'read');
$rwPre = $userModel->rwPre($userInfo['id'], $businessInfo['ro_user_id'], $businessInfo['rw_user_id'], 'update');
if (!in_array($businessInfo['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
if (!in_array($businessInfo['owner_user_id'], $auth_user_ids) && !$roPre && !$rwPre) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$dataList = db('crm_business_product')->where(['business_id' => $param['business_id']])->select();
foreach ($dataList as $k=>$v) {
foreach ($dataList as $k => $v) {
$where = [];
$where['product_id'] = $v['product_id'];
$productInfo = db('crm_product')->where($where)->field('name,category_id')->find();
$category_name = db('crm_product_category')->where(['category_id' => $productInfo['category_id']])->value('name');
$dataList[$k]['name'] = $productInfo['name'] ? : '';
$dataList[$k]['category_id_info'] = $category_name ? : '';
$dataList[$k]['name'] = $productInfo['name'] ?: '';
$dataList[$k]['category_id_info'] = $category_name ?: '';
}
$list['list'] = $dataList ? : [];
$list['total_price'] = $businessInfo['total_price'] ? : '0.00';
$list['discount_rate'] = $businessInfo['discount_rate'] ? : '0.00';
$list['list'] = $dataList ?: [];
$list['total_price'] = $businessInfo['total_price'] ?: '0.00';
$list['discount_rate'] = $businessInfo['discount_rate'] ?: '0.00';
return resultArray(['data' => $list]);
}
}
/**
* 商机状态推进
* @author Michael_xu
* @param business_id 商机ID
* @param status_id 推进商机状态ID
* @return
*/
* @author Michael_xu
*/
public function advance()
{
$param = $this->param;
$userInfo = $this->userInfo;
$userModel = new \app\admin\model\User();
$is_end = $param['is_end'] ? : 0; //1赢单2输单3无效
$is_end = $param['is_end'] ?: 0; //1赢单2输单3无效
if (!$param['business_id']) {
return resultArray(['error' => '参数错误']);
}
@ -380,13 +386,13 @@ class Business extends ApiCommon
$auth_user_ids = $userModel->getUserByPer('crm', 'business', 'update');
//读写权限
$rwPre = $userModel->rwPre($userInfo['id'], $businessInfo['ro_user_id'], $businessInfo['rw_user_id'], 'update');
if (!in_array($businessInfo['owner_user_id'],$auth_user_ids) && !$rwPre) {
if (!in_array($businessInfo['owner_user_id'], $auth_user_ids) && !$rwPre) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$status_id = $param['status_id'] ? : $businessInfo['status_id'];
$statusInfo = db('crm_business_status')->where(['type_id' => $businessInfo['type_id'],'status_id' => $status_id])->find();
$status_id = $param['status_id'] ?: $businessInfo['status_id'];
$statusInfo = db('crm_business_status')->where(['type_id' => $businessInfo['type_id'], 'status_id' => $status_id])->find();
if (!$statusInfo && !$is_end) {
return resultArray(['error' => '参数错误']);
}
@ -409,69 +415,72 @@ class Business extends ApiCommon
if (empty($businessStatusName) && $is_end == 3) $businessStatusName = '无效';
# 添加活动记录
Db::name('crm_activity')->insert([
'type' => 3,
'activity_type' => 5,
'type' => 3,
'activity_type' => 5,
'activity_type_id' => $businessInfo['business_id'],
'content' => '阶段变更为 ' . $businessStatusName,
'create_user_id' => $businessInfo['owner_user_id'],
'update_time' => time(),
'create_time' => time(),
'customer_ids' => ',' . $businessInfo['customer_id'] . ','
'content' => '阶段变更为 ' . $businessStatusName,
'create_user_id' => $businessInfo['owner_user_id'],
'update_time' => time(),
'create_time' => time(),
'customer_ids' => ',' . $businessInfo['customer_id'] . ','
]);
//推进记录添加
$temp['status_id'] = $status_id ? : 0;
$temp['is_end'] = $is_end ? : 0;
$temp['business_id'] = $param['business_id'];
$temp['create_time'] = time();
//推进记录添加
$temp['status_id'] = $status_id ?: 0;
$temp['is_end'] = $is_end ?: 0;
$temp['business_id'] = $param['business_id'];
$temp['create_time'] = time();
$temp['owner_user_id'] = $userInfo['id'];
$temp['remark'] = $param['remark'] ? : '';
Db::name('CrmBusinessLog')->insert($temp);
# 返回商机阶段数据
$typeId = db('crm_business')->where('business_id', $param['business_id'])->value('type_id');
$businessStatus = db('crm_business_status')->where('type_id', $typeId)->select();
$result = [
'business_id' => $param['business_id'],
'type_id' => $typeId,
'status_id' => $param['status_id'],
$temp['remark'] = $param['statusRemark'] ?: '';
Db::name('CrmBusinessLog')->insert($temp);
# 返回商机阶段数据
$typeId = db('crm_business')->where('business_id', $param['business_id'])->value('type_id');
$businessStatus = db('crm_business_status')->where('type_id', $typeId)->select();
$result = [
'business_id' => $param['business_id'],
'type_id' => $typeId,
'status_id' => $param['status_id'],
'status_list' => $businessStatus
];
return resultArray(['data' => $result]);
}
}
/**
* 商机导出
* @author Michael_xu
* @param
* @param
* @return
* @author Michael_xu
*/
public function excelExport()
{
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$action_name = '导出全部';
if ($param['business_id']) {
$param['business_id'] = ['condition' => 'in','value' => $param['business_id'],'form_type' => 'text','name' => ''];
$param['is_excel'] = 1;
}
$param['business_id'] = ['condition' => 'in', 'value' => $param['business_id'], 'form_type' => 'text', 'name' => ''];
$param['is_excel'] = 1;
$action_name = '导出选中';
}
$excelModel = new \app\admin\model\Excel();
// 导出的字段列表
$fieldModel = new \app\admin\model\Field();
$field_list = $fieldModel->getIndexFieldConfig('crm_business', $userInfo['id']);
// 文件名
$file_name = '5kcrm_business_'.date('Ymd');
$file_name = '5kcrm_business_' . date('Ymd');
$model = model('Business');
$temp_file = $param['temp_file'];
unset($param['temp_file']);
$page = $param['page'] ?: 1;
unset($param['page']);
unset($param['export_queue_index']);
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
RecordActionLog($userInfo['id'], 'crm_customer', 'excelexport', $action_name, '', '', '导出商机');
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
$param['page'] = $page;
$param['limit'] = $limit;
$data = $model->getDataList($param);
@ -479,7 +488,7 @@ class Business extends ApiCommon
return $data;
});
}
/**
* 设置关注
*
@ -489,19 +498,19 @@ class Business extends ApiCommon
*/
public function star()
{
$userId = $this->userInfo['id'];
$userId = $this->userInfo['id'];
$targetId = $this->param['target_id'];
$type = $this->param['type'];
$type = $this->param['type'];
if (empty($userId) || empty($targetId) || empty($type)) return resultArray(['error' => '缺少必要参数!']);
if (!$this->setStar($type, $userId, $targetId)) {
return resultArray(['error' => '设置关注失败!']);
}
return resultArray(['data' => '设置关注成功!']);
}
/**
* 系统信息
*
@ -513,14 +522,14 @@ class Business extends ApiCommon
public function system()
{
if (empty($this->param['id'])) return resultArray(['error' => '参数错误!']);
$businessModel = new \app\crm\model\Business();
$data = $businessModel->getSystemInfo($this->param['id']);
return resultArray(['data' => $data]);
}
/**
* table栏数量统计
*
@ -532,50 +541,50 @@ class Business extends ApiCommon
public function count()
{
if (empty($this->param['business_id'])) return resultArray(['error' => '参数错误!']);
$businessId = $this->param['business_id'];
$userInfo = $this->userInfo;
# 查询联系人和商机关联数据
$contactsIds = Db::name('crm_contacts_business')->where('business_id', $businessId)->column('contacts_id');
# 联系人
$contactsAuth = $this->getContactsSearchWhere($userInfo['id']);
$contactsCount = Db::name('crm_contacts')->whereIn('contacts_id', $contactsIds)->where($contactsAuth)->count();
# 合同
$contractAuth = $this->getContractSearchWhere($userInfo['id']);
$contractCount = Db::name('crm_contract')->where('business_id', $businessId)->where($contractAuth)->count();
# 查询商机和产品的关联表
$productIds = Db::name('crm_business_product')->where('business_id', $businessId)->column('product_id');
# 产品
$productAuth = $this->getProductSearchWhere();
$productCount = Db::name('crm_product')->whereIn('product_id', $productIds)->whereIn('owner_user_id', $productAuth)->count();
# 附件
$fileCount = Db::name('crm_business_file')->alias('business')->join('__ADMIN_FILE__ file', 'file.file_id = business.file_id', 'LEFT')->where('business_id', $businessId)->count();
# 团队
$business = Db::name('crm_business')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('business_id', $businessId)->find();
$business['ro_user_id'] = explode(',', trim($business['ro_user_id'], ','));
$business['rw_user_id'] = explode(',', trim($business['rw_user_id'], ','));
$business['ro_user_id'] = explode(',', trim($business['ro_user_id'], ','));
$business['rw_user_id'] = explode(',', trim($business['rw_user_id'], ','));
$business['owner_user_id'] = [$business['owner_user_id']];
$teamCount = array_filter(array_unique(array_merge($business['ro_user_id'], $business['rw_user_id'], $business['owner_user_id'])));
$data = [
'contactCount' => $contactsCount,
'contactCount' => $contactsCount,
'contractCount' => $contractCount,
'fileCount' => $fileCount,
'memberCount' => count($teamCount),
'productCount' => $productCount
'fileCount' => $fileCount,
'memberCount' => count($teamCount),
'productCount' => $productCount
];
return resultArray(['data' => $data]);
}
/**
* 设置首要联系人
*
@ -587,13 +596,13 @@ class Business extends ApiCommon
{
$businessId = $this->param['business_id'];
$contactsId = $this->param['contacts_id'];
if (empty($businessId) || empty($contactsId)) return resultArray(['error' => '参数错误!']);
if (!Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $contactsId])) {
return resultArray(['error' => '操作失败!']);
}
return resultArray(['data' => '操作成功!']);
}
}

@ -126,11 +126,20 @@ class BusinessStatus extends ApiCommon
{
$businessStatusModel = model('BusinessStatus');
$param = $this->param;
$userInfo=$this->userInfo;
if ($param['id'] == 1) {
return resultArray(['error' => '系统数据,不能操作']);
}
$status = $param['status'] ? : '0';
if (db('crm_business_type')->where(['type_id' => $param['id']])->setField('status', $status)) {
$data=db('crm_business_type')->where(['type_id' => $param['id']])->find();
if($status==0){
$status='停用了商机组:'.$data['name'];
}else{
$status='启用了商机组:'.$data['name'];
}
# 系统操作日志
SystemActionLog($userInfo['id'], 'crm_business_type','customer', $param['id'], 'update',$data['name'] , '', '',$status);
return resultArray(['data' => '操作成功']);
} else {
return resultArray(['error' => $businessStatusModel->getError()]);

@ -185,8 +185,12 @@ class Contacts extends ApiCommon
//删除关联附件
$fileModel->delRFileByModule('crm_contacts',$delIds);
//删除关联操作记录
$actionRecordModel->delDataById(['types'=>'crm_contacts','action_id'=>$delIds]);
actionLog($delIds,'','','');
$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']);
}
}
if ($errorMessage) {
return resultArray(['error' => $errorMessage]);
@ -247,8 +251,10 @@ class Contacts extends ApiCommon
$errorMessage[] = $contactsInfo['name'].'"转移失败,错误原因:数据出错;';
continue;
}
updateActionLog($userInfo['id'], 'crm_contacts', $contacts_id, '', '', '将联系人转移给:' . $owner_user_info['realname']);
updateActionLog($userInfo['id'], 'crm_contacts', $contacts_id, '', '', '将联系人转移给:' . $owner_user_info['realname']);
RecordActionLog($userInfo['id'], 'crm_contacts', 'transfer',$contactsInfo['name'], '','','将联系人:'.$contactsInfo['name'].'转移给:' . $owner_user_info['realname']);
}
if (!$errorMessage) {
return resultArray(['data' => '转移成功']);
} else {
@ -267,13 +273,41 @@ class Contacts extends ApiCommon
$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';
$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);
}
/**
@ -287,9 +321,11 @@ class Contacts extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$action_name='导出全部';
if ($param['contacts_id']) {
$param['contacts_id'] = ['condition' => 'in','value' => $param['contacts_id'],'form_type' => 'text','name' => ''];
$param['is_excel'] = 1;
$action_name='导出选中';
}
$excelModel = new \app\admin\model\Excel();
@ -305,6 +341,7 @@ class Contacts extends ApiCommon
$page = $param['page'] ?: 1;
unset($param['page']);
unset($param['export_queue_index']);
RecordActionLog($userInfo['id'],'crm_contracts','excelexport',$action_name,'','','导出联系人');
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
$param['page'] = $page;
$param['limit'] = $limit;
@ -334,6 +371,7 @@ class Contacts extends ApiCommon
// if (!$res) {
// return resultArray(['error'=>$excelModel->getError()]);
// }
RecordActionLog($userInfo['id'],'crm_contacts','excel','导入联系人','','','导入联系人');
return resultArray(['data' => $excelModel->getError()]);
}

@ -143,7 +143,7 @@ class Contract extends ApiCommon
$receivablesModel = new \app\crm\model\Receivables();
$param = $this->param;
$userInfo = $this->userInfo;
$data = $contractModel->getDataById($param['id']);
$data = $contractModel->getDataById($param['id'], $userInfo['id']);
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'read');
//读权限
@ -324,6 +324,7 @@ class Contract extends ApiCommon
$delIds[] = $v;
}
}
$dataInfo = $contractModel->where('contract_id',['in',$delIds])->select();
if ($delIds) {
$data = $contractModel->delDatas($delIds);
if (!$data) {
@ -337,7 +338,10 @@ class Contract extends ApiCommon
$actionRecordModel->delDataById(['types'=>'crm_contract','action_id'=>$delIds]);
// 删除回款记录
\app\crm\model\ReceivablesPlan::where(['contract_id' => ['IN', $delIds]])->delete();
actionLog($delIds,'','','');
$userInfo = $this->userInfo;
foreach ($dataInfo as $k => $v) {
RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['name'], '', '', '删除了合同:' . $v['name']);
}
}
if ($errorMessage) {
return resultArray(['error' => $errorMessage]);
@ -425,7 +429,9 @@ class Contract extends ApiCommon
}
//修改记录
updateActionLog($userInfo['id'], 'crm_contract', $contract_id, '', '', '将合同转移给:'.$ownerUserName);
updateActionLog($userInfo['id'], 'crm_contract', $contract_id, '', '', '将合同转移给:'.$ownerUserName);
RecordActionLog($userInfo['id'], 'crm_contract', 'transfer',$contractInfo['name'], '','','将合同:'.$contractInfo['name'].'转移给:' . $ownerUserName);
}
if (!$errorMessage) {
return resultArray(['data' => '转移成功']);
@ -676,9 +682,11 @@ class Contract extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$action_name = '导出全部';
if ($param['contract_id']) {
$param['contract_id'] = ['condition' => 'in','value' => $param['contract_id'],'form_type' => 'text','name' => ''];
$param['is_excel'] = 1;
$action_name='导出选中';
}
$excelModel = new \app\admin\model\Excel();
// 导出的字段列表
@ -693,6 +701,7 @@ class Contract extends ApiCommon
$page = $param['page'] ?: 1;
unset($param['page']);
unset($param['export_queue_index']);
RecordActionLog($userInfo['id'],'crm_contract','excelexport',$action_name,'','','导出合同');
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
$param['page'] = $page;
$param['limit'] = $limit;

@ -29,7 +29,7 @@ class Customer extends ApiCommon
{
$action = [
'permission' => ['exceldownload', 'setfollow', 'delete'],
'allow' => ['read', 'system', 'count', 'poolauthority']
'allow' => ['read', 'system', 'count', 'poolauthority', 'level']
];
Hook::listen('check_auth', $action);
$request = Request::instance();
@ -156,6 +156,8 @@ class Customer extends ApiCommon
public function delete()
{
$param = $this->param;
$user=new ApiCommon();
$userInfo = $user->userInfo;
// 是否客户池
if ($param['isSeas'] == 1) {
$permission = checkPerByAction('crm', 'customer', 'poolDelete');
@ -227,6 +229,7 @@ class Customer extends ApiCommon
$delIds[] = $v;
}
}
$dataInfo = $customerModel->where('customer_id',['in',$delIds])->select();
if ($delIds) {
$delRes = $customerModel->delDatas($delIds);
if (!$delRes) {
@ -238,7 +241,9 @@ class Customer extends ApiCommon
$fileModel->delRFileByModule('crm_customer', $delIds);
//删除关联操作记录
$actionRecordModel->delDataById(['types' => 'crm_customer', 'action_id' => $delIds]);
actionLog($delIds, '', '', '');
foreach ($dataInfo as $k => $v) {
RecordActionLog($userInfo['id'], 'crm_customer', 'delete', $v['name'], '', '', '删除了客户:' . $v['name']);
}
}
if ($errorMessage) {
return resultArray(['error' => $errorMessage]);
@ -374,6 +379,7 @@ class Customer extends ApiCommon
}
//修改记录
updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户转移给:' . $ownerUserName);
RecordActionLog($userInfo['id'], 'crm_customer', 'transfer',$customerInfo['name'], '','','将客户:'.$customerInfo['name'].'转移给:' . $ownerUserName);
}
if (!$errorMessage) {
return resultArray(['data' => '转移成功']);
@ -390,48 +396,160 @@ class Customer extends ApiCommon
*/
public function putInPool()
{
$param = $this->param;
if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要放入公海的客户!']);
if (!is_array($this->param['customer_id'])) return resultArray(['error' => '客户ID格式不正确']);
if (empty($this->param['pool_id'])) return resultArray(['error' => '请选择公海!']);
$userInfo = $this->userInfo;
$customerModel = model('Customer');
$settingModel = new \app\crm\model\Setting();
if (!$param['customer_id'] || !is_array($param['customer_id'])) {
return resultArray(['error' => '请选择需要放入公海的客户']);
$userId = $userInfo['id'];
$customerIds = $this->param['customer_id'];
$poolId = $this->param['pool_id'];
# 消息数据
$message = [];
# 获取客户数据
$customerData = [];
$customerList = db('crm_customer')->field(['customer_id', 'owner_user_id', 'name'])->whereIn('customer_id', $customerIds)->select();
foreach ($customerList AS $key => $value) {
$customerData[$value['customer_id']] = $value;
}
$data = [];
$data['owner_user_id'] = 0;
$data['is_lock'] = 0;
$data['update_time'] = time();
$errorMessage = [];
foreach ($param['customer_id'] as $customer_id) {
$customerInfo = [];
$customerInfo = db('crm_customer')->where(['customer_id' => $customer_id])->find();
if (!$customerInfo) {
$errorMessage[] = '名称:为《' . $customerInfo['name'] . '》的客户放入公海失败,错误原因:数据不存在;';
continue;
}
//权限判断
if (!$customerModel->checkData($customer_id)) {
$errorMessage[] = '"' . $customerInfo['name'] . '"放入公海失败,错误原因:无权限';
# 整理数据
$ip = request()->ip();
$poolRelationData = [];
$poolRecordData = [];
$fieldRecordData = [];
$operationLogData = [];
foreach ($customerIds AS $key => $value)
{
if (empty($customerData[$value])) {
$message[] = '将客户放入公海失败,错误原因:数据不存在!';
unset($customerIds[(int)$key]);
continue;
}
//将团队成员全部清除
$data['ro_user_id'] = '';
$data['rw_user_id'] = '';
$resCustomer = db('crm_customer')->where(['customer_id' => $customer_id])->update($data);
if (!$resCustomer) {
$errorMessage[] = '"' . $customerInfo['name'] . '"放入公海失败,错误原因:数据出错;';
if (isset($customerData[$value]['owner_user_id']) && empty($customerData[$value]['owner_user_id'])) {
$message[] = '将客户《' . $customerData[$value]['name'] . '》放入公海失败,错误原因:已经处于公海!';
unset($customerIds[(int)$key]);
continue;
}
//联系人负责人清除
db('crm_contacts')->where(['customer_id' => $customer_id])->update(['owner_user_id' => 0]);
//修改记录
updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户放入公海');
# 公海关联数据
$poolRelationData[] = [
'pool_id' => $poolId,
'customer_id' => $value
];
# 公海操作记录数据
$poolRecordData[] = [
'customer_id' => $value,
'user_id' => $userId,
'pool_id' => $poolId,
'type' => 2,
'create_time' => time()
];
# 字段操作记录数据
$fieldRecordData[] = [
'user_id' => $userId,
'types' => 'crm_customer',
'action_id' => $value,
'content' => '将客户放入公海',
'create_time' => time()
];
# 数据操作日志数据
$operationLogData[] = [
'user_id' => $userId,
'client_ip' => $ip,
'module' => 'crm_customer',
'action_id' => $value,
'content' => '将客户放入公海',
'create_time' => time(),
'action_name' => 'update',
'target_name' => !empty($customerData[$value]['name']) ? $customerData[$value]['name'] : ''
];
}
if (!$errorMessage) {
return resultArray(['data' => '操作成功']);
} else {
return resultArray(['error' => $errorMessage]);
if (empty($customerIds)) return resultArray(['error' => $message]);
Db::startTrans();
try {
# 修改客户数据
Db::name('crm_customer')->whereIn('customer_id', $customerIds)->exp('before_owner_user_id', 'owner_user_id')->update([
'ro_user_id' => '',
'rw_user_id' => '',
'owner_user_id' => 0,
'into_pool_time' => time()
]);
# 删除联系人的负责人
Db::name('crm_contacts')->whereIn('customer_id', $customerIds)->update(['owner_user_id' => 0]);
# 将客户放入公海
Db::name('crm_customer_pool_relation')->insertAll($poolRelationData);
# 公海操作记录
Db::name('crm_customer_pool_record')->insertAll($poolRecordData);
# 字段操作记录
Db::name('admin_action_record')->insertAll($fieldRecordData);
# 数据操作日志
Db::name('admin_operation_log')->insertAll($operationLogData);
Db::commit();
} catch (\Exception $e) {
Db::rollback();
$message = ['操作失败!'];
}
return resultArray(!empty($message) ? ['error' => $message] : ['data' => '操作成功!']);
// $param = $this->param;
// $userInfo = $this->userInfo;
// $customerModel = model('Customer');
// $settingModel = new \app\crm\model\Setting();
// if (!$param['customer_id'] || !is_array($param['customer_id'])) {
// return resultArray(['error' => '请选择需要放入公海的客户']);
// }
// $data = [];
// $data['owner_user_id'] = 0;
// $data['is_lock'] = 0;
// $data['update_time'] = time();
// $errorMessage = [];
// foreach ($param['customer_id'] as $customer_id) {
// $customerInfo = [];
// $customerInfo = db('crm_customer')->where(['customer_id' => $customer_id])->find();
// if (!$customerInfo) {
// $errorMessage[] = '名称:为《' . $customerInfo['name'] . '》的客户放入公海失败,错误原因:数据不存在;';
// continue;
// }
// //权限判断
// if (!$customerModel->checkData($customer_id)) {
// $errorMessage[] = '"' . $customerInfo['name'] . '"放入公海失败,错误原因:无权限';
// continue;
// }
// //将团队成员全部清除
// $data['ro_user_id'] = '';
// $data['rw_user_id'] = '';
// $resCustomer = db('crm_customer')->where(['customer_id' => $customer_id])->update($data);
// if (!$resCustomer) {
// $errorMessage[] = '"' . $customerInfo['name'] . '"放入公海失败,错误原因:数据出错;';
// continue;
// }
// //联系人负责人清除
// db('crm_contacts')->where(['customer_id' => $customer_id])->update(['owner_user_id' => 0]);
// //修改记录
// updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户放入公海');
// RecordActionLog($userInfo['id'],'crm_pool','pool',$customerInfo['name'],'','','将客户'.$customerInfo['name'].'放入公海');
// }
// if (!$errorMessage) {
// return resultArray(['data' => '操作成功']);
// } else {
// return resultArray(['error' => $errorMessage]);
// }
}
/**
@ -483,6 +601,11 @@ class Customer extends ApiCommon
}
//修改记录
updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户' . $lock_name);
if($is_lock == 2){
RecordActionLog($userInfo['id'], 'crm_customer', 'islock',$customerInfo['name'], '','','将客户'.$customerInfo['name'].$lock_name );
}else{
RecordActionLog($userInfo['id'], 'crm_customer', 'lock',$customerInfo['name'], '','','将客户'.$customerInfo['name'].$lock_name );
}
}
if (!$errorMessage) {
return resultArray(['data' => '操作成功']);
@ -542,6 +665,7 @@ class Customer extends ApiCommon
db('crm_contacts')->where(['customer_id' => $v])->update(['owner_user_id' => $userInfo['id']]);
//修改记录
updateActionLog($userInfo['id'], 'crm_customer', $v, '', '', '领取了客户');
RecordActionLog($userInfo['id'], 'crm_customer', 'update',$dataName, '','','领取了客户:'.$dataName);
}
if (!$errorMessage) {
return resultArray(['data' => '领取成功']);
@ -599,6 +723,8 @@ class Customer extends ApiCommon
$data['rw_user_id'] = '';
# 处理分配标识,待办事项专用
$data['is_allocation'] = 1;
# 获取客户的时间
$data['obtain_time'] = time();
$resCustomer = db('crm_customer')->where(['customer_id' => $v])->update($data);
if (!$resCustomer) {
$errorMessage[] = '客户《' . $dataName . '》分配失败,错误原因:数据出错;';
@ -606,6 +732,7 @@ class Customer extends ApiCommon
db('crm_contacts')->where(['customer_id' => $v])->update(['owner_user_id' => $owner_user_id]);
//修改记录
updateActionLog($userInfo['id'], 'crm_customer', $v, '', '', '将客户分配给:' . $ownerUserName);
RecordActionLog($userInfo['id'], 'crm_customer', 'distribute',$dataName, '','','将客户'.$dataName.'分配给:' . $ownerUserName);
//站内信
$send_user_id[] = $owner_user_id;
$sendContent = $userInfo['realname'] . '将客户《' . $dataName . '》,分配给您';
@ -631,8 +758,10 @@ class Customer extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$action_name='导出全部';
if ($param['customer_id']) {
$param['customer_id'] = ['condition' => 'in', 'value' => $param['customer_id'], 'form_type' => 'text', 'name' => ''];
$action_name='导出选中';
}
$param['is_excel'] = 1;
$excelModel = new \app\admin\model\Excel();
@ -648,6 +777,7 @@ class Customer extends ApiCommon
$page = $param['page'] ?: 1;
unset($param['page']);
unset($param['export_queue_index']);
RecordActionLog($userInfo['id'],'crm_customer','excelexport',$action_name,'','','导出客户');
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
$param['page'] = $page;
$param['limit'] = $limit;
@ -655,6 +785,7 @@ class Customer extends ApiCommon
$data['list'] = $model->exportHandle($data['list'], $field_list, 'customer');
return $data;
});
}
/**
@ -668,13 +799,40 @@ class Customer extends ApiCommon
$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);
$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);
}
@ -697,6 +855,7 @@ class Customer extends ApiCommon
$file = request()->file('file');
// $res = $excelModel->importExcel($file, $param, $this);
$res = $excelModel->batchImportData($file, $param, $this);
RecordActionLog($userInfo['id'],'crm_customer','excel','导入客户','','','导入客户');
return resultArray(['data' => $excelModel->getError()]);
}
@ -762,6 +921,7 @@ class Customer extends ApiCommon
$param['user_id'] = $userInfo['id'];
if ($param['customer_id']) {
$param['customer_id'] = ['condition' => 'in', 'value' => $param['customer_id'], 'form_type' => 'text', 'name' => ''];
$action_name='导出选中';
}
$param['is_excel'] = 1;
$excelModel = new \app\admin\model\Excel();
@ -781,6 +941,7 @@ class Customer extends ApiCommon
$page = $param['page'] ?: 1;
unset($param['page']);
unset($param['export_queue_index']);
RecordActionLog($userInfo['id'],'crm_customer','excelexport',$action_name,'','','导出客户');
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param) {
$param['page'] = $page;
$param['limit'] = $limit;
@ -847,6 +1008,11 @@ class Customer extends ApiCommon
}
//修改记录
updateActionLog($userInfo['id'], 'crm_customer', $customer_id, ['deal_status' => $dataInfo['deal_status']], ['deal_status' => $data['deal_status']]);
if($param['status']==1){
RecordActionLog($userInfo['id'], 'crm_customer', 'status',$dataInfo['name'], '','','修改客户:'.$dataInfo['name'].'成交状态:'.$statusArr[$param['status']]);
}else{
RecordActionLog($userInfo['id'], 'crm_customer', 'status',$dataInfo['name'], '','','修改客户:'.$dataInfo['name'].'成交状态:'.$statusArr[$param['status']]);
}
}
if (!$errorMessage) {
return resultArray(['data' => '操作成功']);
@ -1031,4 +1197,20 @@ class Customer extends ApiCommon
return resultArray(['data' => $authority]);
}
/**
* 客户级别列表
*
* @author fanqi
* @since 2021-03-29
* @return \think\response\Json
*/
public function level()
{
$data = db('admin_field')->where(['types' => 'crm_customer', 'field' => 'level'])->value('setting');
$data = explode(chr(10), $data);
return resultArray(['data' => $data]);
}
}

@ -0,0 +1,364 @@
<?php
/**
* 客户公海
*
* @author fanqi
* @since 2021-04-13
*/
namespace app\crm\controller;
use app\admin\controller\ApiCommon;
use app\crm\logic\CustomerPoolLogic;
use think\Hook;
use think\Request;
use think\response\Json;
class CustomerPool extends ApiCommon
{
/**
* 用于判断权限
* @permission 无限制
* @allow 登录用户可访问
* @other 其他根据系统设置
**/
public function _initialize()
{
$action = [
'permission' => [],
'allow' => [
'index',
'read',
'pondlist',
'field',
'advanced',
'authority',
'receive',
'distribute',
'delete',
'fieldconfig',
'setfieldwidth',
'setfieldconfig',
'exceldownload',
'import',
'export'
]
];
Hook::listen('check_auth',$action);
$request = Request::instance();
$a = strtolower($request->action());
if (!in_array($a, $action['permission'])) {
parent::_initialize();
}
}
/**
* 公海列表
*
* @author fanqi
* @since 2021-04-14
* @return Json
*/
public function index()
{
if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
$data = (new CustomerPoolLogic())->getPoolList($this->param);
return resultArray(['data' => $data]);
}
/**
* 详情
*
* @author fanqi
* @since 2021-04-14
* @return Json
*/
public function read()
{
if (empty($this->param['pool_id']) || empty($this->param['customer_id'])) return resultArray(['error' => '参数错误!']);
$userInfo = $this->userInfo;
$param = $this->param;
$param['user_id'] = $userInfo['id'];
$data = (new CustomerPoolLogic())->getPoolData($param);
return resultArray(['data' => $data]);
}
/**
* 删除公海客户
*
* @author fanqi
* @since 2021-04-15
* @return Json
*/
public function delete()
{
if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的客户!']);
$this->param['user_id'] = $this->userInfo['id'];
$result = (new CustomerPoolLogic())->deletePoolCustomer($this->param);
if (!empty($result)) return resultArray(['error' => $result]);
return resultArray(['data' => '删除成功!']);
}
/**
* 公海池列表
*
* @author fanqi
* @since 2021-04-13
* @return Json
*/
public function pondList()
{
$data = (new CustomerPoolLogic())->getPondList(['user_id' => $this->userInfo['id'], 'structure_id' => $this->userInfo['structure_id']]);
return resultArray(['data' => $data]);
}
/**
* 公海字段
*
* @author fanqi
* @since 2021-04-13
* @return Json
*/
public function field()
{
if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
$userInfo = $this->userInfo;
$param = $this->param;
$param['user_id'] = $userInfo['id'];
$data = (new CustomerPoolLogic())->getFieldList($param);
return resultArray(['data' => $data]);
}
/**
* 高级筛选字段列表
*
* @author fanqi
* @since 2021-04-14
* @return Json
*/
public function advanced()
{
if (empty($this->param['types'])) return resultArray(['error' => '缺少模块类型!']);
$data = (new CustomerPoolLogic())->getAdvancedFilterFieldList($this->param);
return resultArray(['data' => $data]);
}
/**
* 领取公海池客户
*
* @author fanqi
* @since 2021-04-15
* @return Json
*/
public function receive()
{
if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要领取的公海客户!']);
$param = $this->param;
$param['user_id'] = $this->userInfo['id'];
$result = (new CustomerPoolLogic())->receiveCustomers($param);
if (!empty($result)) return resultArray(['error' => $result]);
return resultArray(['data' => '领取成功!']);
}
/**
* 分配公海客户
*
* @author fanqi
* @since 2021-04-15
* @return Json
*/
public function distribute()
{
if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要分配的公海客户!']);
if (empty($this->param['user_id'])) return resultArray(['error' => '请选择要分配的员工!']);
$result = (new CustomerPoolLogic())->distributeCustomer($this->param);
if (!empty($result)) return resultArray(['error' => $result]);
return resultArray(['data' => '分配成功!']);
}
// 公海客户导入模板下载
public function excelDownload($save_path='')
{
$excelModel = new \app\admin\model\Excel();
$param=$this->param;
$field_list=$this->fieldsData($param);
$excelModel->excelImportDownload($field_list, 'crm_customer', $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';
$file = request()->file('file');
// $res = $excelModel->importExcel($file, $param, $this);
$res = $excelModel->batchImportData($file, $param, $this);
RecordActionLog($userInfo['id'],'crm_customer','excel','导入公海客户','','','导入公海客户');
return resultArray(['data' => $excelModel->getError()]);
}
// 导出
public function export()
{
$param = $this->param;
$userInfo = $this->userInfo;
$action_name='导出全部';
if ($param['customer_id']) {
$action_name='导出选中';
}
$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');
$temp_file = $param['temp_file'];
unset($param['temp_file']);
$page = $param['page'] ?: 1;
unset($param['page']);
unset($param['export_queue_index']);
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
$param['page'] = $page;
$param['limit'] = $limit;
$data = (new CustomerPoolLogic())->getPoolList($param);
$data['list'] = $model->exportHandle($data['list'], $field_list, 'customer');
return $data;
});
RecordActionLog($userInfo['id'],'crm_customer','excelexport',$action_name,'','','导出客户');
return resultArray(['error' => 'error']);
}
/**
* 公海权限
*
* @author fanqi
* @since 2021-04-14
* @return Json
*/
public function authority()
{
$param = $this->param;
$param['user_id'] = $this->userInfo['id'];
$param['structure_id'] = $this->userInfo['structure_id'];
$data = (new CustomerPoolLogic())->getAuthorityData($param);
return resultArray(['data' => $data]);
}
/**
* 公海字段样式
*
* @author fanqi
* @since 2021-04-22
* @return Json
*/
public function fieldConfig()
{
if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$data = (new CustomerPoolLogic())->getFieldConfigIndex($param);
return resultArray(['data' => $data]);
}
/**
* 设置公海字段宽度
*
* @author fanqi
* @since 2021-04-22
* @return Json
*/
public function setFieldWidth()
{
if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
if (empty($this->param['field'])) return resultArray(['error' => '缺少字段名称!']);
if (empty($this->param['width'])) return resultArray(['error' => '缺少宽度值!']);
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
(new CustomerPoolLogic())->setFieldWidth($param);
return resultArray(['data' => '操作成功!']);
}
/**
* 设置公海字段样式
*
* @author fanqi
* @since 2021-04-22
* @return Json
*/
public function setFieldConfig()
{
if (empty($this->param['pool_id'])) return resultArray(['缺少公海ID']);
if (empty($this->param['value']) && empty($this->param['hide_value'])) return resultArray(['error' => '字段参数错误!']);
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
(new CustomerPoolLogic())->setFieldConfig($param);
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();
$fieldParam['types'] = 'crm_customer';
$fieldParam['action'] = 'excel';
$merge_list = $fieldModel->field($fieldParam);
$field_list=array_intersect($merge_list,$pool_list);
return $field_list;
}
}

@ -595,6 +595,9 @@ class Index extends ApiCommon
if ($c != 'activity') {
$where['owner_user_id']['value'] = $userIds;
if($types=='crm_contract' || $types=='crm_receivables'){
$where['check_status']=2;
}
$data = $model->getDataList($where);
} else {
$typesList = ['1', '2', '3', '5', '6'];

@ -153,6 +153,7 @@ class Invoice extends ApiCommon
# 更新crm_number_sequence表中的last_date、create_time字段
if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
updateActionLog($param['create_user_id'], 'crm_invoice', $invoice_id, '', '', '创建了发票');
RecordActionLog($param['create_user_id'],'crm_invoice','save',$param['invoice_apple_number'],'','','新增了发票'.$param['invoice_apple_number']);
# 创建待办事项的关联数据
$checkUserIds = db('crm_invoice')->where('invoice_id', $invoice_id)->value('check_user_id');
@ -229,8 +230,8 @@ class Invoice extends ApiCommon
if (empty($param['invoice_type'])) return resultArray(['error' => '请选择开票类型!']);
if (empty($param['title_type'])) return resultArray(['error' => '请选择抬头类型!']);
if (empty($param['examineStatus'])) return resultArray(['error' => '缺少审批状态!']);
$userId = $this->userInfo['id'];
$userId = $this->userInfo['id'];
$dataInfo = $this->get($param['invoice_id']);
# 审批是否停用
$examineStatus = $param['examineStatus'];
# 删除无用参数
@ -320,8 +321,8 @@ class Invoice extends ApiCommon
# 更新crm_number_sequence表中的last_date、create_time字段
if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
//修改记录
// updateActionLog($param['user_id'], 'crm_invoice', $param['invoice_id'], $dataInfo, $param);
updateActionLog($param['user_id'], 'crm_invoice', $param['invoice_id'], $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_invoice', 'update',$dataInfo['invoice_apple_number'], $dataInfo, $param);
# 删除待办事项的关联数据
db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'types_id' => ['eq', $param['invoice_id']]])->delete();
# 创建待办事项的关联数据
@ -372,14 +373,17 @@ class Invoice extends ApiCommon
}
if (!$status) return resultArray(['error' => '不能删除审批中或审批结束的发票信息!']);
$dataInfo=db('crm_invoice')->where('invoice_id',['in',$idArray])->select();
if (!$invoiceLogic->delete($idArray)) return resultArray(['error' => '删除失败!']);
# 删除附件
$fileModel->delRFileByModule('crm_invoice', $idArray);
//删除关联操作记录
$actionRecordModel->delDataById(['types'=>'crm_invoice','action_id'=>$idArray]);
$userInfo = $this->userInfo;
foreach ($dataInfo as $k => $v) {
RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['invoice_apple_number'], '', '', '删除了回款:' . $v['invoice_apple_number']);
}
return resultArray(['data' => '删除成功!']);
}
@ -393,13 +397,19 @@ class Invoice extends ApiCommon
{
$ownerUserId = $this->param['owner_user_id'];
$invoiceIds = $this->param['invoice_id'];
$userModel = new \app\admin\model\User();
$userInfo=$this->userInfo;
if (empty($ownerUserId)) return resultArray(['error' => '请选择负责人!']);
if (empty($invoiceIds)) return resultArray(['error' => '请选择发票!']);
if (!is_array($invoiceIds)) return resultArray(['error' => '发票ID类型错误']);
if ($invoiceLogic->transfer($invoiceIds, $ownerUserId) === false) return resultArray(['error' => '操作失败!']);
$owner_user_info = $userModel->getUserById($ownerUserId);
foreach ($invoiceIds as $v){
$invoice_info=db('crm_invoice')->where('invoice_id',$v)->find();
updateActionLog($userInfo['id'], 'crm_invoice', $v, '', '', '将发票转移给:' . $owner_user_info['realname']);
RecordActionLog($userInfo['id'], 'crm_invoice', 'transfer',$invoice_info['invoice_apple_number'], '','','将发票:'.$invoice_info['invoice_apple_number'].'转移给:' . $owner_user_info['realname']);
}
return resultArray(['data' => '操作成功!']);
}
@ -628,14 +638,15 @@ class Invoice extends ApiCommon
public function resetInvoiceStatus(InvoiceLogic $invoiceLogic)
{
if (empty($this->param['invoice_id'])) resultArray(['error' => '参数错误!']);
$userInfo = $this->userInfo;
$this->param['real_invoice_date'] = !empty($this->param['real_invoice_date']) ? $this->param['real_invoice_date'] : date('Y-m-d');
# 开票状态
$this->param['invoice_status'] = 1;
$invoice_info=db('crm_invoice')->where('invoice_id',$this->param['invoice_id'])->find();
if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']);
RecordActionLog($userInfo['id'], 'crm_invoice', 'update',$invoice_info['invoice_apple_number'], '','','将发票:'.$invoice_info['invoice_apple_number'].'重置开票状态');
return resultArray(['data' => '操作成功!']);
}
}

@ -175,6 +175,7 @@ class Leads extends ApiCommon
$delIds[] = $v;
}
}
$dataInfo = $leadsModel->where('leads_id',['in',$delIds])->select();
if ($delIds) {
$data = $leadsModel->delDatas($delIds);
if (!$data) {
@ -186,7 +187,10 @@ class Leads extends ApiCommon
$fileModel->delRFileByModule('crm_leads', $delIds);
//删除关联操作记录
$actionRecordModel->delDataById(['types' => 'crm_leads', 'action_id' => $delIds]);
actionLog($delIds, '', '', '');
$userInfo = $this->userInfo;
foreach ($dataInfo as $k => $v) {
RecordActionLog($userInfo['id'], 'crm_leads', 'delete', $v['name'], '', '', '删除了线索:' . $v['name']);
}
}
if ($errorMessage) {
return resultArray(['error' => $errorMessage]);
@ -250,6 +254,7 @@ class Leads extends ApiCommon
db('crm_leads')->where(['leads_id' => $leads_id])->update($leadsData);
//修改记录
updateActionLog($userInfo['id'], 'crm_customer', $resCustomer['customer_id'], '', '', '将线索"' . $leadsInfo['name'] . '转化为客户');
RecordActionLog($userInfo['id'],'crm_leads','save',$leadsInfo['name'],'','','将线索'.$leadsInfo['name'].'转化为客户');
# 将线索下的跟进记录同步至客户下
$record = db('crm_activity')->field('activity_id', true)->where(['type' => 1, 'activity_type' => 1, 'activity_type_id' => $leads_id])->select();
foreach ($record as $key1 => $value1) {
@ -323,6 +328,8 @@ class Leads extends ApiCommon
}
//修改记录
updateActionLog($userInfo['id'], 'crm_leads', $leads_id, '', '', '将线索转移给:' . $ownerUserName);
RecordActionLog($userInfo['id'], 'crm_leads', 'transfer',$leadsInfo['name'], '','','将线索:'.$leadsInfo['name'].'转移给:' . $ownerUserName);
}
if (!$errorMessage) {
return resultArray(['data' => '转移成功']);
@ -339,7 +346,7 @@ class Leads extends ApiCommon
*/
public function excelDownload($save_path = '')
{
$param = $this->param;
$userInfo = $this->userInfo;
$excelModel = new \app\admin\model\Excel();
@ -350,6 +357,33 @@ class Leads extends ApiCommon
$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]);
}
@ -365,9 +399,11 @@ class Leads extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$action_name='导出全部';
if ($param['leads_id']) {
$param['leads_id'] = ['condition' => 'in', 'value' => $param['leads_id'], 'form_type' => 'text', 'name' => ''];
$param['is_excel'] = 1;
$action_name='导出选中';
}
$excelModel = new \app\admin\model\Excel();
@ -383,6 +419,7 @@ class Leads extends ApiCommon
$page = $param['page'] ?: 1;
unset($param['page']);
unset($param['export_queue_index']);
RecordActionLog($userInfo['id'],'crm_leads','excelexport',$action_name,'','','导出线索');
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $field_list, $param) {
$param['page'] = $page;
$param['limit'] = $limit;
@ -405,13 +442,14 @@ class Leads extends ApiCommon
$excelModel = new \app\admin\model\Excel();
$param['types'] = 'crm_leads';
$param['create_user_id'] = $userInfo['id'];
$param['owner_user_id'] = $param['owner_user_id'] ?: $userInfo['id'];
$file = request()->file('file');
// $res = $excelModel->importExcel($file, $param);
$res = $excelModel->batchImportData($file, $param, $this);
if (!$res) {
return resultArray(['error' => $excelModel->getError()]);
}
RecordActionLog($userInfo['id'],'crm_leads','excel','导入线索','','','导入线索');
return resultArray(['data' => $excelModel->getError()]);
}

@ -0,0 +1,150 @@
<?php
namespace app\crm\controller;
use app\admin\controller\ApiCommon;
use think\Hook;
use think\Request;
use app\crm\logic\MarketLogic;
class Market extends ApiCommon{
/**
* 用于判断权限
* @permission 无限制
* @allow 登录用户可访问
* @other 其他根据系统设置
**/
public function _initialize()
{
$action = [
'permission'=>['exceldownload'],
'allow'=>['index','save','read','update','marketlist']
];
Hook::listen('check_auth',$action);
$request = Request::instance();
$a = strtolower($request->action());
if (!in_array($a, $action['permission'])) {
parent::_initialize();
}
}
/**
* 市场活动列表
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/26 0026 17:15
*/
public function index(){
$marketLogic=new MarketLogic;
$param=$this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$data = $marketLogic->getDataList($param);
return resultArray(['data' => $data]);
}
/**
* 关联对象列表
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/26 0026 17:14
*/
public function marketList(){
$marketLogic=new MarketLogic;
$data = $marketLogic->marketList();
return resultArray(['data' => $data]);
}
public function save(){
$marketLogic=new MarketLogic;
$param = $this->param;
$userInfo = $this->userInfo;
$param['create_user_id'] = $userInfo['id'];
# 检查活动图片
if (!empty($param['cover_images']) && count(explode(',', $param['cover_images'])) > 9) {
return resultArray(['error' => '最多只能上次9张产品图片']);
}
# 检查活动详情图片
if (!empty($param['details_images']) && count(explode(',', $param['details_images'])) > 9) {
return resultArray(['error' => '最多只能上次9张产品详情图片']);
}
if ($marketLogic->createData($param)) {
return resultArray(['data' => '添加成功']);
} else {
return resultArray(['error' => '添加失败']);
}
}
public function update(){
$marketLogic=new MarketLogic;
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
# 检查产品图片
if (!empty($param['cover_images']) && count(explode(',', $param['cover_images'])) > 9) {
return resultArray(['error' => '最多只能上次9张产品图片']);
}
# 检查产品详情图片
if (!empty($param['details_images']) && count(explode(',', $param['details_images'])) > 9) {
return resultArray(['error' => '最多只能上次9张产品详情图片']);
}
if ($marketLogic->updateDataById($param, $param['id'])) {
return resultArray(['data' => '编辑成功']);
} else {
return resultArray(['error' => '编辑失败']);
}
}
public function read()
{
$marketLogic=new MarketLogic;
$userModel = new \app\admin\model\User();
$param = $this->param;
$userInfo = $this->userInfo;
$data = $marketLogic->getDataById($param['id'], $userInfo['id']);
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'Market', 'read');
if (!in_array($data['owner_user_id'], $auth_user_ids)) {
//无权限
$authData['dataAuth'] = (int)0;
return resultArray(['data' => $authData]);
}
if (!$data) {
return resultArray(['error' => $marketLogic->getError()]);
}
return resultArray(['data' => $data]);
}
public function delete(){
$marketLogic=new MarketLogic;
$userInfo = $this->userInfo;
$id_list = (array) $this->param['id'];
$id_list['user_id']=$userInfo['id'];
$id_list = array_map('intval', $id_list);
$data=$marketLogic->delete($id_list);
if($data){
return resultArray(['data' => '删除成功']);
}else{
return resultArray(['error' => '删除失败']);
}
}
public function enables(){
$marketModel = model('Market');
$param = $this->param;
$userInfo=$this->userInfo;
$id = [$param['flow_id']];
$data = $marketModel->enableDatas($id, $param['status']);
# 系统操作日志
if (!$data) {
return resultArray(['error' => $marketModel->getError()]);
}
if($param['status']==0){
$content='禁用了:';
}else{
$content='启用了:';
}
$dataInfo=db('admin_examine_flow')->where('flow_id',$param['flow_id'])->find();
SystemActionLog($userInfo['id'], 'admin_examine','approval', $param['flow_id'], 'update', $dataInfo['name'], '', '',$content.$dataInfo['name']);
return resultArray(['data' => '操作成功']);
}
}

@ -207,14 +207,15 @@ class Message extends ApiCommon
}
}
# 待进入公海提醒
if ($configData['remind_config'] == 1) {
$pool = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
if (!empty($pool)) {
$remindCustomerTime = cache('remindCustomerTime'.$userInfo['id']);
$remindCustomerCount = cache('remindCustomerCount'.$userInfo['id']);
if (time() <= $remindCustomerTime) {
$data['putInPoolRemind'] = (int)$remindCustomerCount;
} else {
$remindCustomer = $this->remindCustomer(true);
$data['putInPoolRemind'] = $remindCustomer['dataCount'] ? : 0;
$data['putInPoolRemind'] = !empty($remindCustomer['dataCount']) ? $remindCustomer['dataCount'] : 0;
cache('remindCustomerCount'.$userInfo['id'], $data['putInPoolRemind']);
cache('remindCustomerTime'.$userInfo['id'], time() + 180);
}
@ -661,7 +662,7 @@ class Message extends ApiCommon
}
/**
* 待进入客户池默认5天
* 待进入客户池
* @author Michael_xu
* @return
*/
@ -684,16 +685,19 @@ class Message extends ApiCommon
$param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userInfo['id'])] : $userInfo['id'];
# 是否提醒
$remind = db('crm_config')->where('name', 'remind_config')->value('value');
$whereData = $param ? : [];
$whereData['is_remind'] = !empty($remind) ? 1 : 0;
$whereData['user_id'] = $userInfo['id'];
$whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => 'me'])->value('scene_id');
if ($isSub) {
$whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => 'sub'])->value('scene_id');
$data = [];
$remind = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
if (!empty($remind)) {
$whereData = $param ? : [];
$whereData['is_remind'] = 1;
$whereData['user_id'] = $userInfo['id'];
$whereData['pool_remain'] = 0;
$whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => 'me'])->value('scene_id');
if ($isSub) {
$whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => 'sub'])->value('scene_id');
}
$data = $customerModel->getDataList($whereData);
}
$data = $customerModel->getDataList($whereData);
if ($types == 'list') {
return resultArray(['data' => $data]);
}
@ -859,30 +863,24 @@ class Message extends ApiCommon
# 处理待进入公海
if ($type == 'putInPoolRemind') {
if (!empty($typeId)) {
Db::name('crm_customer')->whereIn('customer_id', $typeId)->update([
'follow' => '已跟进',
'last_time' => time(),
'deal_time' => time(),
'update_time' => time(),
]);
Db::name('crm_customer')->whereIn('customer_id', $typeId)->update(['pool_remain' => 1]);
} else {
$whereData['page'] = 1;
$whereData['limit'] = 100;
$whereData['is_remind'] = db('crm_config')->where('name', 'remind_config')->value('value');;
$whereData['user_id'] = $userId;
$whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => empty($isSub) ? 'me' : 'sub'])->value('scene_id');
$whereData['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userId)] : $userId;
$poolCustomers = (new \app\crm\model\Customer())->getDataList($whereData);
$ids = [];
foreach ($poolCustomers['list'] AS $key => $value) {
if (!empty($value['customer_id'])) $ids[] = $value['customer_id'];
$poolConfig = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
if (!empty($poolConfig)) {
$whereData['page'] = 1;
$whereData['limit'] = 100;
$whereData['is_remind'] = 1;
$whereData['user_id'] = $userId;
$whereData['pool_remain'] = 0;
$whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => empty($isSub) ? 'me' : 'sub'])->value('scene_id');
$whereData['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userId)] : $userId;
$poolCustomers = (new \app\crm\model\Customer())->getDataList($whereData);
$ids = [];
foreach ($poolCustomers['list'] AS $key => $value) {
if (!empty($value['customer_id'])) $ids[] = $value['customer_id'];
}
if (!empty($ids)) Db::name('crm_customer')->whereIn('customer_id', $ids)->update(['pool_remain' => 1]);
}
if (!empty($ids)) Db::name('crm_customer')->whereIn('customer_id', $ids)->update([
'follow' => '已跟进',
'last_time' => time(),
'deal_time' => time(),
'update_time' => time(),
]);
}
}

@ -0,0 +1,67 @@
<?php
namespace app\crm\controller;
use think\Controller;
use think\Request;
class Preview extends Controller
{
public function previewPdf(Request $request)
{
# 处理跨域
// header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
// header('Access-Control-Allow-Credentials: true');
// header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
// header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId");
# 相应类型
header('Content-Type: application/pdf');
header('Transfer-Encoding: chunked');
$key = $request->param('key');
$data = db('admin_printing_data')->field(['type', 'content'])->where('key', $key)->find();
$contentArray = json_decode($data['content'], true);
$content = $contentArray['data'];
require_once(EXTEND_PATH.'tcpdf'.DS.'config'.DS.'tcpdf_config.php');
require_once(EXTEND_PATH.'tcpdf'.DS.'tcpdf.php');
$tcpdf = new \TCPDF();
// 设置PDF页面边距LEFTTOPRIGHT
$tcpdf->SetMargins(10, 10, 10);
// 设置字体,防止中文乱码
$tcpdf->SetFont('simsun', '', 10);
// 设置文件信息
// $tcpdf->SetCreator(TITLE_NAME);
// $tcpdf->SetAuthor(TITLE_NAME);
$tcpdf->SetTitle("打印内容预览");
// 删除预定义的打印 页眉/页尾
$tcpdf->setPrintHeader(false);
// 设置文档对齐,间距,字体,图片
$tcpdf->SetCreator(PDF_CREATOR);
$tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
// 自动分页
$tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$tcpdf->setFontSubsetting(true);
$tcpdf->setPageMark();
$tcpdf->AddPage();
$html = $content;
$tcpdf->writeHTML($html, true, false, true, true, '');
$tcpdf->lastPage();
$tcpdf->Output(ROOT_PATH.DS.'public'.DS.'temp'.DS.'pdf'.DS.'print.pdf','I');
exit($this->fetch('preview', ['key' => $key]));
}
}

@ -10,6 +10,10 @@ namespace app\crm\controller;
use app\admin\controller\ApiCommon;
use app\crm\logic\PrintingLogic;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\Html;
use think\Controller;
use think\Hook;
use think\Request;
@ -18,8 +22,8 @@ class Printing extends ApiCommon
public function _initialize()
{
$action = [
'permission'=>[''],
'allow'=>['printingdata', 'template', 'setrecord', 'getrecord']
'permission'=>['previewData'],
'allow'=>['printingdata', 'template', 'setrecord', 'getrecord', 'preview', 'down']
];
Hook::listen('check_auth',$action);
$request = Request::instance();
@ -43,12 +47,9 @@ class Printing extends ApiCommon
$actionId = $this->param['action_id'];
$templateId = $this->param['template_id'];
$type = $this->param['type'];
$recordId = $this->param['record_id'];
if (empty($actionId)) return resultArray(['error' => '请选择打印的数据!']);
if (empty($templateId)) return resultArray(['error' => '请选择打印的模板!']);
if (empty($type)) return resultArray(['error' => '请选择打印的类型!']);
$data = $printingLogic->getPrintingData($type, $actionId, $templateId);
$data = $printingLogic->getPrintingData($type, $actionId, $templateId, $recordId);
return resultArray(['data' => $data]);
}
@ -79,9 +80,10 @@ class Printing extends ApiCommon
*/
public function setRecord(PrintingLogic $printingLogic)
{
if (empty($this->param['type'])) return resultArray(['error' => '请选择模块!']);
if (empty($this->param['action_id'])) return resultArray(['error' => '缺少数据ID']);
if (empty($this->param['template_id'])) return resultArray(['error' => '缺少模板ID']);
if (empty($this->param['type'])) return resultArray(['error' => '请选择模块!']);
if (empty($this->param['action_id'])) return resultArray(['error' => '缺少数据ID']);
if (empty($this->param['template_id'])) return resultArray(['error' => '缺少模板ID']);
if (empty($this->param['recordContent'])) return resultArray(['error' => '缺少打印内容!']);
$userId = $this->userInfo['id'];
@ -101,10 +103,108 @@ class Printing extends ApiCommon
*/
public function getRecord(PrintingLogic $printingLogic)
{
if (empty($this->param['type'])) return resultArray(['error' => '请选择模块!']);
if (empty($this->param['crmType'])) return resultArray(['error' => '请选择模块!']);
if (empty($this->param['typeId'])) return resultArray(['error' => '缺少数据ID']);
$data = $printingLogic->getRecord($this->param, $this->userInfo['id']);
return resultArray(['data' => $data]);
}
/**
* 保存打印内容
*
* @param user_id 用户id
* @param type 类型workpdf
* @param content 打印内容
* @author fanqi
* @date 2021-03-25
* @return \think\response\Json
*/
public function preview(PrintingLogic $printingLogic)
{
if (empty($this->param['type'])) return resultArray(['error' => '缺少类型参数!']);
if (empty($this->param['content'])) return resultArray(['error' => '缺少打印内容!']);
$userInfo = $this->userInfo;
$this->param['user_id'] = $userInfo['id'];
$key = $printingLogic->preview($this->param);
return resultArray(['data' => $key]);
}
/**
* 打下打印文件
* @param string key 打印数据的唯一key
* @author fanqi
* @date 2021-03-26
* @return \think\response\Json
*/
public function down()
{
if (empty($this->param['key'])) return resultArray(['error' => '参数错误!']);
$data = db('admin_printing_data')->field(['type', 'content'])->where('key', $this->param['key'])->find();
$type = $data['type'];
$contentArray = json_decode($data['content'], true);
$content = $contentArray['data'];
if ($type == 'pdf') {
require_once(EXTEND_PATH.'tcpdf'.DS.'config'.DS.'tcpdf_config.php');
require_once(EXTEND_PATH.'tcpdf'.DS.'tcpdf.php');
$tcpdf = new \TCPDF();
// 设置PDF页面边距LEFTTOPRIGHT
$tcpdf->SetMargins(10, 10, 10);
// 设置字体,防止中文乱码
$tcpdf->SetFont('simsun', '', 10);
// 设置文件信息
$tcpdf->SetCreator(TITLE_NAME);
$tcpdf->SetAuthor(TITLE_NAME);
$tcpdf->SetTitle("打印文件");
// 删除预定义的打印 页眉/页尾
$tcpdf->setPrintHeader(false);
// 设置文档对齐,间距,字体,图片
$tcpdf->SetCreator(PDF_CREATOR);
$tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
// 自动分页
$tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$tcpdf->setFontSubsetting(true);
$tcpdf->setPageMark();
$tcpdf->AddPage();
$html = $content;
$tcpdf->writeHTML($html, true, false, true, true, '');
$tcpdf->lastPage();
$tcpdf->Output('print.PDF','I');
}
if ($type == 'word') {
$fileName = 'print.docx';
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$fileName");
header('Transfer-Encoding: chunked');
$html = '<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">';
$html .= '<head><meta charset="UTF-8" /></head>';
echo $html . '<body>'.$content .'</body></html>';
}
}
}

@ -94,7 +94,8 @@ class Product extends ApiCommon
$productModel = model('Product');
$userModel = new \app\admin\model\User();
$param = $this->param;
$data = $productModel->getDataById($param['id']);
$userInfo = $this->userInfo;
$data = $productModel->getDataById($param['id'], $userInfo['id']);
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'product', 'read');
if (!in_array($data['owner_user_id'], $auth_user_ids)) {
@ -151,6 +152,8 @@ class Product extends ApiCommon
$data = [];
$data['status'] = ($param['status'] == '上架') ? '上架' : '下架';
$data['update_time'] = time();
$userModel = new \app\admin\model\User();
$owner_user_info = $userModel->getUserById($this->param['owner_user_id']);
if (!is_array($param['id'])) {
$productIds[] = $param['id'];
} else {
@ -163,6 +166,16 @@ class Product extends ApiCommon
if (!$res) {
return resultArray(['error' => '操作失败']);
}
foreach ($productIds as $v){
$product_info=db('crm_product')->where('product_id',$v)->find();
if($param['status'] == '上架'){
updateActionLog($userInfo['id'], 'crm_product', $v, '', '', '将产品上架');
RecordActionLog($userInfo['id'], 'crm_product', 'up',$product_info['name'], '','','将产品上架');
}else{
updateActionLog($userInfo['id'], 'crm_product', $v, '', '', '将产品下架');
RecordActionLog($userInfo['id'], 'crm_product', 'down',$product_info['name'], '','','将产品下架');
}}
return resultArray(['data' => $data['status'].'成功']);
}
@ -177,13 +190,40 @@ class Product extends ApiCommon
$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';
$fieldParam['types'] = 'crm_product';
$fieldParam['action'] = 'excel';
$field_list = $fieldModel->field($fieldParam);
$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);
}
/**
@ -197,8 +237,10 @@ class Product extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$action_name='导出全部';
if ($param['product_id']) {
$param['product_id'] = ['condition' => 'in','value' => $param['product_id'],'form_type' => 'text','name' => ''];
$action_name='导出选中';
}
$excelModel = new \app\admin\model\Excel();
@ -214,6 +256,7 @@ class Product extends ApiCommon
$page = $param['page'] ?: 1;
unset($param['page']);
unset($param['export_queue_index']);
RecordActionLog($userInfo['id'],'crm_product','excelexport',$action_name,'','','导出产品');
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
$param['page'] = $page;
$param['limit'] = $limit;
@ -239,6 +282,7 @@ class Product extends ApiCommon
$param['owner_user_id'] = $param['owner_user_id'] ? : $userInfo['id'];
$file = request()->file('file');
$res = $excelModel->batchImportData($file, $param, $this);
RecordActionLog($userInfo['id'],'crm_product','excel','导入产品','','','导入产品');
return resultArray(['data' => $excelModel->getError()]);
}
@ -283,8 +327,8 @@ class Product extends ApiCommon
if ($isDel) {
$delIds[] = $v;
}
}
}
$dataInfo = $productModel->where('product_id',['in',$delIds])->select();
if ($delIds) {
// 开启事务
ProductModel::startTrans();
@ -298,7 +342,10 @@ class Product extends ApiCommon
// 操作记录
(new ActionRecordModel)->delDataById('crm_product', $delIds);
// 添加删除记录
actionLog($delIds, '', '', '');
$userInfo = $this->userInfo;
foreach ($dataInfo as $k => $v) {
RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['name'], '', '', '删除了产品:' . $v['name']);
}
return resultArray(['data' => '删除成功']);
} else {
// 事务回滚
@ -359,11 +406,16 @@ class Product extends ApiCommon
{
if (empty($this->param['product_id']) || !is_array($this->param['product_id'])) return resultArray(['error' => '产品参数错误!']);
if (empty($this->param['owner_user_id'])) return resultArray(['error' => '请选择要变更的负责人']);
$userModel = new \app\admin\model\User();
$userInfo=$this->userInfo;
$productModel = new \app\crm\model\Product();
if (!$productModel->transfer($this->param)) return resultArray(['error' => '操作失败!']);
$owner_user_info = $userModel->getUserById($this->param['owner_user_id']);
foreach ($this->param['product_id'] as $v){
$product_info=db('crm_product')->where('product_id',$v)->find();
updateActionLog($userInfo['id'], 'crm_product', $v, '', '', '将产品转移给:' . $owner_user_info['realname']);
RecordActionLog($userInfo['id'], 'crm_product', 'transfer',$product_info['name'], '','','将产品:'.$product_info['name'].'转移给:' . $owner_user_info['realname']);
}
return resultArray(['data' => '操作成功!']);
}
}

@ -91,7 +91,7 @@ class ProductCategory extends ApiCommon
if ($res) {
return resultArray(['data' => '编辑成功']);
} else {
return resultArray(['error' => $productDataModel->getError()]);
return resultArray(['error' => $categoryModel->getError()]);
}
}

@ -66,8 +66,10 @@ class Receivables extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$param['user_id'] = $userInfo['id'];
$action_name = '导出全部';
if ($param['receivables_id']) {
$param['receivables_id'] = ['condition' => 'in', 'value' => $param['receivables_id'], 'form_type' => 'text', 'name' => ''];
$action_name='导出选中';
}
$excelModel = new \app\admin\model\Excel();
// 导出的字段列表
@ -81,6 +83,7 @@ class Receivables extends ApiCommon
$page = $param['page'] ?: 1;
unset($param['page']);
unset($param['export_queue_index']);
RecordActionLog($userInfo['id'],'crm_receivables','excelexport',$action_name,'','','导出回款');
return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
$param['page'] = $page;
$param['limit'] = $limit;
@ -174,7 +177,8 @@ class Receivables extends ApiCommon
$receivablesModel = model('Receivables');
$userModel = new \app\admin\model\User();
$param = $this->param;
$data = $receivablesModel->getDataById($param['id']);
$userInfo = $this->userInfo;
$data = $receivablesModel->getDataById($param['id'], $userInfo['id']);
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'read');
@ -338,6 +342,7 @@ class Receivables extends ApiCommon
$delIds[] = $v;
}
}
$dataInfo = $receivablesModel->where('receivables_id',['in',$delIds])->select();
if ($delIds) {
$data = $receivablesModel->delDatas($delIds);
if (!$data) {
@ -349,7 +354,10 @@ class Receivables extends ApiCommon
$fileModel->delRFileByModule('crm_receivables', $delIds);
//删除关联操作记录
$actionRecordModel->delDataById(['types' => 'crm_receivables', 'action_id' => $delIds]);
actionLog($delIds, '', '', '');
$userInfo = $this->userInfo;
foreach ($dataInfo as $k => $v) {
RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['number'], '', '', '删除了回款:' . $v['number']);
}
}
if ($errorMessage) {
@ -594,6 +602,8 @@ class Receivables extends ApiCommon
continue;
}
updateActionLog($userInfo['id'], 'crm_receivables', $receivables_id, '', '', '将回款转移给:' . $owner_user_info['realname']);
RecordActionLog($userInfo['id'], 'crm_receivables', 'transfer',$receivables_info['number'], '','','将回款:'.$receivables_info['number'].'转移给:' . $owner_user_info['realname']);
}
if (!$errorMessage) {
return resultArray(['data' => '转移成功']);

@ -26,24 +26,9 @@ class Setting extends ApiCommon
$action = [
'permission' => [''],
'allow' => [
'config',
'configdata',
'team',
'teamsave',
'contractday',
'recordlist',
'recordedit',
'customerconfiglist',
'customerconfigsave',
'customerconfigupdate',
'customerconfigdelete',
'numberSequenceAdd',
'quitteam',
'setvisitday',
'getvisitday',
'setnumber',
'customerconfigdel',
'numbersequencelist'
'config', 'configdata', 'team', 'teamsave', 'contractday', 'recordlist', 'recordedit', 'customerconfiglist',
'customerconfigsave', 'customerconfigupdate', 'customerconfigdelete', 'numberSequenceAdd', 'quitteam',
'setvisitday', 'getvisitday', 'setnumber', 'customerconfigdel', 'numbersequencelist',
]
];
Hook::listen('check_auth', $action);
@ -307,7 +292,7 @@ class Setting extends ApiCommon
$param['type'] = $param['type'] ?: 1;
$param['is_del'] = $param['is_del'] ?: 3;
$param['owner_user_id'] = $userInfo['id'];
if (!$param['is_del']) {
if (empty($param['is_del'])) {
$res = $settingModel->createTeamData($param);
if (!$res) {
$errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
@ -320,12 +305,25 @@ 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));
}
} else {
$res = $settingModel->createTeamData($param);
if (!$res) {
$errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
}else{
(new Message())->send(
Message::TEAM_END,
[
'title' => $dataInfo['name'],
'action_id' => $v
],
$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));
}
}
@ -352,11 +350,14 @@ class Setting extends ApiCommon
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$param = $this->param;
$userInfo=$this->userInfo;
$data = [];
$contract_day = $param['contract_day'] ? intval($param['contract_day']) : 0;
$contract_config = $param['contract_config'] ? intval($param['contract_config']) : 0;
$res = db('crm_config')->where(['name' => 'contract_config'])->update(['value' => $contract_config]);
if ($contract_day && $contract_config == 1) $res = db('crm_config')->where(['name' => 'contract_day'])->update(['value' => $contract_day]);
# 系统操作日志
SystemActionLog($userInfo['id'], 'crm_config','customer', 1, 'update','' , '', '','编辑了合同到期提醒设置');
return resultArray(['data' => '设置成功']);
}
@ -373,6 +374,7 @@ class Setting extends ApiCommon
public function recordEdit()
{
$param = $this->param;
$userInfo=$this->userInfo;
//权限判断
if (!checkPerByAction('admin', 'crm', 'setting')) {
header('Content-Type:application/json; charset=utf-8');
@ -383,14 +385,18 @@ class Setting extends ApiCommon
$record_type = db('crm_config')->where(['name' => 'record_type'])->find();
if ($record_type) {
$res = db('crm_config')->where(['name' => 'record_type'])->update(['value' => $array]);
$id=$record_type['id'];
} else {
$data = array();
$data['name'] = 'record_type';
$data['value'] = $array;
$data['description'] = '跟进记录类型';
$res = db('crm_config')->insert($data);
$res = db('crm_config')->insertGetId($data);
$id=$res;
$record_type['description']='跟进记录类型';
}
if ($res) {
SystemActionLog($userInfo['id'], 'crm_config','customer', $id, 'update',$record_type['description'] , '', '','编辑了跟进记录类型:'.$record_type['description']);
return resultArray(['data' => '设置成功']);
} else {
return resultArray(['error' => '设置失败,请重试!']);
@ -522,29 +528,6 @@ class Setting extends ApiCommon
return resultArray(['data' => $data]);
}
/**
* 编号添加
*
* @return \think\response\Json
*/
public function numberSequenceAdd()
{
//权限判断
if (!checkPerByAction('admin', 'crm', 'setting')) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code' => 102, 'error' => '无权操作']));
}
$userInfo = $this->userInfo;
$param = $this->param;
$param['user_id'] = $userInfo['id'];
$numberSequenceModel = new \app\crm\model\NumberSequence();
$res = $numberSequenceModel->createData($param);
if (!$res) {
return resultArray(['error' => $numberSequenceModel->getError()]);
}
return resultArray(['data' => '创建成功']);
}
/**
* 编号修改
*
@ -605,7 +588,7 @@ class Setting extends ApiCommon
return resultArray(['data' => '操作成功!']);
}
/**
* 获取回访提醒
*
@ -614,12 +597,11 @@ class Setting extends ApiCommon
public function getVisitDay()
{
$settingModel = new \app\crm\model\Setting();
$data = $settingModel->getVisitDay();
return resultArray(['data' => $data]);
}
/**
* 设置自动编号
*

@ -87,12 +87,11 @@ class Visit extends ApiCommon
*/
public function read()
{
$visit = new VisitLogic;
$userModel = new \app\admin\model\User();
$param = $this->param;
$userInfo = $this->userInfo;
$data = $visit->getDataById($param['id']);
$data = $visit->getDataById($param['id'], $userInfo['id']);
//判断权限
$auth_user_ids = $userModel->getUserByPer('crm', 'visit', 'read');
//读权限

@ -8,6 +8,7 @@
namespace app\crm\logic;
use app\admin\controller\ApiCommon;
use app\admin\model\Group;
use app\crm\model\Activity;
use think\Db;
@ -77,27 +78,110 @@ class ActivityLogic
$recordWhere['type'] = ['neq', 1];
}
# 处理公共查询参数
if (!empty($param['interval_day'])) {
$commonWhere['update_time'] = ['egt', time() - 86400 * $param['interval_day']];
$commonWhere['update_time'] = ['elt', time()];
}
if (!empty($param['start_date']) && !empty($param['end_date'])) {
$commonWhere['update_time'] = ['egt', strtotime($param['start_date'].' 00:00:00')];
$commonWhere['update_time'] = ['elt', strtotime($param['end_date'].' 23:59:59')];
}
if (!empty($param['search'])) {
$commonWhere['content'] = ['like', '%' . $param['search'] . '%'];
}
if (!empty($param['activity_type'])) {
$commonWhere['activity_type'] = $param['activity_type'];
}
# 客户模块的额外查询条件
$contactsData = [];
$businessData = [];
$contractData = [];
$receivablesData = [];
# 联系人ID串
$contacts = Db::name('crm_contacts')->field(['contacts_id'])->where('customer_id', $param['activity_type_id'])->select();
if (!empty($contacts)) {
$contactsData['activity_type'] = 3;
$contactsData['activity_type_id'] = array_reduce($contacts, function ($result, $value) {
return array_merge($result, array_values($value));
}, []);
}
# 商机ID串
$business = Db::name('crm_business')->field(['business_id'])->where('customer_id', $param['activity_type_id'])->select();
if (!empty($business)) {
$businessData['activity_type'] = 5;
$businessData['activity_type_id'] = array_reduce($business, function ($result, $value) {
return array_merge($result, array_values($value));
}, []);
}
# 合同ID串
$contract = Db::name('crm_contract')->field(['contract_id'])->where('customer_id', $param['activity_type_id'])->select();
if (!empty($contract)) {
$contractData['activity_type'] = 6;
$contractData['activity_type_id'] = array_reduce($contract, function ($result, $value) {
return array_merge($result, array_values($value));
}, []);
}
# 回款ID串
$receivables = Db::name('crm_receivables')->field(['receivables_id'])->where('customer_id', $param['activity_type_id'])->select();
if (!empty($receivables)) {
$receivablesData['activity_type'] = 7;
$receivablesData['activity_type_id'] = array_reduce($receivables, function ($result, $value) {
return array_merge($result, array_values($value));
}, []);
}
# 设置时间分组查询条件,第一页就是当天的数据,第二页就是下一天的数据
$datetime = Db::name('crm_activity')
->field('update_time')
->where($recordWhere)
->where('status', 1)
->where(function ($query) use ($param) {
->where(function ($query) use ($param, $contactsData, $businessData, $contractData, $receivablesData) {
$query->whereOr(function ($query) use ($param) {
$query->where('activity_type_id', $param['activity_type_id']);
$query->where('activity_type', $this->moduleToNumber[$param['module']]);
});
$query->whereOr('customer_ids', 'like', ',%'.$param['activity_type_id'].'%,');
$query->whereOr('contacts_ids', 'like', ',%'.$param['activity_type_id'].'%,');
$query->whereOr('contract_ids', 'like', ',%'.$param['activity_type_id'].'%,');
$query->whereOr('business_ids', 'like', ',%'.$param['activity_type_id'].'%,');
$query->whereOr('leads_ids', 'like', ',%'.$param['activity_type_id'].'%,');
$query->whereOr('customer_ids', 'like', '%,'.$param['activity_type_id'].',%');
$query->whereOr('contacts_ids', 'like', '%,'.$param['activity_type_id'].',%');
$query->whereOr('contract_ids', 'like', '%,'.$param['activity_type_id'].',%');
$query->whereOr('business_ids', 'like', '%,'.$param['activity_type_id'].',%');
$query->whereOr('leads_ids', 'like', '%,'.$param['activity_type_id'].',%');
if (!empty($contactsData)) {
$query->whereOr(function ($query) use ($contactsData) {
$query->where('activity_type', $contactsData['activity_type']);
$query->whereIn('activity_type_id', $contactsData['activity_type_id']);
});
}
if (!empty($businessData)) {
$query->whereOr(function ($query) use ($businessData) {
$query->where('activity_type', $businessData['activity_type']);
$query->whereIn('activity_type_id', $businessData['activity_type_id']);
});
}
if (!empty($contractData)) {
$query->whereOr(function ($query) use ($contractData) {
$query->where('activity_type', $contractData['activity_type']);
$query->whereIn('activity_type_id', $contractData['activity_type_id']);
});
}
if (!empty($receivablesData)) {
$query->whereOr(function ($query) use ($receivablesData) {
$query->where('activity_type', $receivablesData['activity_type']);
$query->whereIn('activity_type_id', $receivablesData['activity_type_id']);
});
}
})
->where($commonWhere)
->order('update_time', 'desc')
->group('update_time')
->select();
$dateGroup = [0 => '']; // 加一个占位page是从1开始
$dateWhere = [0 => []]; // 加一个占位page是从1开始
$dateGroup = [0 => '']; // 加一个占位page从1开始
$dateWhere = [0 => []]; // 加一个占位page从1开始
foreach ($datetime AS $key => $value) {
$date = date('Y-m-d', $value['update_time']);
if (!in_array($date, $dateGroup)) {
@ -118,22 +202,6 @@ class ActivityLogic
return ['lastPage' => true, 'list' => [], 'time' => ''];
}
# 处理公共查询参数
if (!empty($param['interval_day'])) {
$commonWhere['update_time'] = ['egt', time() - 86400 * $param['interval_day']];
$commonWhere['update_time'] = ['elt', time()];
}
if (!empty($param['start_date']) && !empty($param['end_date'])) {
$commonWhere['update_time'] = ['egt', strtotime($param['start_date'])];
$commonWhere['update_time'] = ['elt', strtotime($param['end_date'])];
}
if (!empty($param['search'])) {
$commonWhere['content'] = ['like', '%' . $param['search'] . '%'];
}
if (!empty($param['activity_type'])) {
$commonWhere['activity_type'] = $param['activity_type'];
}
# 组织线索、客户、联系人、商机、合同下的查询条件
switch ($param['module']) {
case 'leads' :
@ -143,47 +211,6 @@ class ActivityLogic
};
break;
case 'customer' :
$contactsData = [];
$businessData = [];
$contractData = [];
$receivablesData = [];
# 联系人ID串
$contacts = Db::name('crm_contacts')->field(['contacts_id'])->where('customer_id', $param['activity_type_id'])->select();
if (!empty($contacts)) {
$contactsData['activity_type'] = 3;
$contactsData['activity_type_id'] = array_reduce($contacts, function ($result, $value) {
return array_merge($result, array_values($value));
}, []);
}
# 商机ID串
$business = Db::name('crm_business')->field(['business_id'])->where('customer_id', $param['activity_type_id'])->select();
if (!empty($business)) {
$businessData['activity_type'] = 5;
$businessData['activity_type_id'] = array_reduce($business, function ($result, $value) {
return array_merge($result, array_values($value));
}, []);
}
# 合同ID串
$contract = Db::name('crm_contract')->field(['contract_id'])->where('customer_id', $param['activity_type_id'])->select();
if (!empty($contract)) {
$contractData['activity_type'] = 6;
$contractData['activity_type_id'] = array_reduce($contract, function ($result, $value) {
return array_merge($result, array_values($value));
}, []);
}
# 回款ID串
$receivables = Db::name('crm_receivables')->field(['receivables_id'])->where('customer_id', $param['activity_type_id'])->select();
if (!empty($receivables)) {
$receivablesData['activity_type'] = 7;
$receivablesData['activity_type_id'] = array_reduce($receivables, function ($result, $value) {
return array_merge($result, array_values($value));
}, []);
}
# 客户模块查询条件
$customerWhere = function ($query) use ($param, $contactsData, $businessData, $contractData, $receivablesData) {
$query->whereOr(function ($query) use ($param) {
@ -292,7 +319,7 @@ class ActivityLogic
$fileModel = new \app\admin\model\File();
foreach ($dataArray AS $key => $value) {
# 用户信息 todo 有模型文件,时间问题,暂时将查询写在循环中
# 用户信息
$realname = Db::name('admin_user')->where('id', $dataArray[$key]['create_user_id'])->find();
$dataArray[$key]['create_user_name'] = $realname['realname'];
$dataArray[$key]['thumb_img'] = $realname['thumb_img'] ? getFullPath($realname['thumb_img']) : '';;
@ -418,7 +445,6 @@ class ActivityLogic
$param['create_time'] = time();
$param['update_time'] = time();
if (!empty($param['contacts_ids'])) $param['contacts_ids'] = ',' . $param['contacts_ids'] . ',';
$activityJson = Activity::create($param);
if (empty($activityJson)) return false;
@ -454,7 +480,8 @@ class ActivityLogic
$eventModel->createData($data);
}
$activity=[1 =>'线索', 2=> '客户', 3 =>'联系人' ,4 =>'产品', 5 =>'商机', 6 =>'合同' ,7=>'回款' ,8=>'日志' ,9=>'审批' ,10=>'日程' ,11=>'任务' ,12 =>'发邮件'];
RecordActionLog($param['create_user_id'],'crm_activity','save',$activity[$param['activity_type']],'','','新增了跟进记录'.$param['content']);
return true;
}
@ -472,12 +499,11 @@ class ActivityLogic
$fileIds = !empty($param['file_id']) ? $param['file_id'] : [];
unset($param['is_event']);
unset($param['file_id']);
$param['type'] = 1;
$param['next_time'] = strtotime($param['next_time']);
$param['business_ids'] = !empty($param['business_ids']) ? arrayToString($param['business_ids']) : '';
$param['update_time'] = time();
$dataInfo=db('crm_activity')->where('activity_id',$param['activity_id'])->find();
if (!Activity::update($param)) return false;
# 设置最后跟进记录
@ -514,7 +540,6 @@ class ActivityLogic
$eventModel->createData($data);
}
return true;
}
@ -538,6 +563,9 @@ 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);
return true;
} else {
return false;
@ -795,4 +823,20 @@ class ActivityLogic
$model->where($primaryKey, $typeId)->update(['last_time' => time(), 'last_record' => $content]);
}
/**
* 跟进记录导出
* @param $field_list
* @param $data
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/21 0021 09:35
*/
public function excelExport($field_list,$data){
$excelModel = new \app\admin\model\Excel();
$file_name='activity_record';
$title='跟进记录';
$excelModel->taskExportCsv($file_name, $field_list, $title, $data);
}
}

@ -226,6 +226,8 @@ class CommonLogic
//修改记录
$user_id = $apiCommon->userInfo;
updateActionLog($user_id['id'], $types, $actionId, $info, $data);
RecordActionLog($user_id['id'], $types, 'update',$info['name'], $info, $data);
}
return $res;
}

File diff suppressed because it is too large Load Diff

@ -22,7 +22,7 @@ class IndexLogic extends Common
'11' => 'november',
'12' => 'december',
];
/**
* @param $param
* @return array
@ -46,7 +46,7 @@ class IndexLogic extends Common
$userIds = $whereArr['userIds'];
$between_time = $whereArr['between_time'];
$last_between_time = $lastArr['between_time'];
$customerNum = 0; //新增客户
$customerLastNum = 0; //上期对比
@ -64,13 +64,13 @@ class IndexLogic extends Common
$contractLastMoneyNum = 0; //上期对比
$receivablesMoneyNum = 0; //新增回款金额
$receivablesLastMoneyNum = 0; //上期对比
$where = [];
$where['owner_user_id']['value'] = $userIds;
$where['create_time']['start'] = $between_time[0];
$where['create_time']['end'] = $between_time[1];
$where['getCount'] = 1;
$customer_auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'index');
$contacts_auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'index');
$business_auth_user_ids = $userModel->getUserByPer('crm', 'business', 'index');
@ -89,7 +89,7 @@ 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],
@ -102,7 +102,7 @@ class IndexLogic extends Common
'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? : [-1],
])
);
$customerNum = (int)$resCount[0]['count1'] ?: 0;
$contactsNum = (int)$resCount[1]['count1'] ?: 0;
$businessNum = (int)$resCount[2]['count1'] ?: 0;
@ -111,7 +111,7 @@ class IndexLogic extends Common
$contractMoneyNum = $resCount[3]['count2'] ?: 0;
$receivablesMoneyNum = $resCount[4]['count1'] ?: 0;
$recordNum = (int)$resCount[5]['count1'] ?: 0;
$customerLastNum = (int)$resLastCount[0]['count1'] ?: 0;
$contactsLastNum = (int)$resLastCount[1]['count1'] ?: 0;
$businessLastNum = (int)$resLastCount[2]['count1'] ?: 0;
@ -120,34 +120,34 @@ 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);
$data['data']['contactsNum'] = $contactsNum;
$data['prev']['contactsNum'] = $this->getProportion($contactsNum, $contactsLastNum);
$data['data']['businessNum'] = $businessNum;
$data['prev']['businessNum'] = $this->getProportion($businessNum, $businessLastNum);
$data['data']['contractNum'] = $contractNum;
$data['prev']['contractNum'] = $this->getProportion($contractNum, $contractLastNum);
$data['data']['recordNum'] = $recordNum;
$data['prev']['recordNum'] = $this->getProportion($recordNum, $recordLastNum);
$data['data']['businessMoneyNum'] = $businessMoneyNum;
$data['prev']['businessMoneyNum'] = $this->getProportion($businessMoneyNum, $businessLastMoneyNum);
$data['data']['contractMoneyNum'] = $contractMoneyNum;
$data['prev']['contractMoneyNum'] = $this->getProportion($contractMoneyNum, $contractLastMoneyNum);
$data['data']['receivablesMoneyNum'] = $receivablesMoneyNum;
$data['prev']['receivablesMoneyNum'] = $this->getProportion($receivablesMoneyNum, $receivablesLastMoneyNum);
return $data;
}
public function getCountSql($param)
{
$configModel = new \app\crm\model\ConfigData();
@ -162,9 +162,8 @@ class IndexLogic extends Common
count(1) count1,
0 count2
FROM 5kcrm_crm_customer
WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
WHERE (create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . " OR obtain_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . ")
and owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")
and (( ( deal_time > ".$data['deal_time']." ) or (update_time > ".$data['follow_time']." and deal_time > ".$data['deal_time']."))or deal_status = '已成交' or is_lock = 1 )
UNION ALL
SELECT
count(1) AS count1,
@ -173,7 +172,6 @@ class IndexLogic extends Common
LEFT JOIN 5kcrm_crm_customer customer ON contacts.customer_id=customer.customer_id
WHERE contacts.create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
and contacts.owner_user_id IN (" . implode(',', $param['contacts_auth_user_ids']) . ")
and (( ( customer.deal_time > ".$data['deal_time']." ) or (customer.update_time > ".$data['follow_time']." and customer.deal_time > ".$data['deal_time']."))or customer.deal_status = '已成交' or customer. is_lock = 1 )
UNION ALL
SELECT
count(1) AS count1,
@ -183,7 +181,7 @@ class IndexLogic extends Common
and owner_user_id IN (" . implode(',', $param['business_auth_user_ids']) . ")
UNION ALL
SELECT
count(1) AS count1,
count( CASE WHEN check_status = 2 THEN 1 ELSE null END) AS count1,
SUM( CASE WHEN check_status = 2 THEN money ELSE 0 END) AS count2
FROM 5kcrm_crm_contract
WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
@ -208,7 +206,7 @@ class IndexLogic extends Common
and create_user_id IN (" . implode(',', $param['record_auth_user_ids']) . ")";
return $countSql;
}
///计算涨幅
public function getProportion($now, $last)
{
@ -224,8 +222,8 @@ class IndexLogic extends Common
}
return $res;
}
/**
* 遗忘数据统计
* @return mixed
@ -246,14 +244,14 @@ class IndexLogic extends Common
$auth_customer_user_ids = $userModel->getUserByPer('crm', 'customer', 'index');
$auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集
$owner_user_ids = array('in', $auth_customer_user_ids);
$customerParam = [];
$customerParam['limit'] = $param['limit'];
$customerParam['page'] = $param['page'];
$customerParam['search'] = $param['search'];
$customerParam['getCount'] = 1;
$customerParam['owner_user_id'] = $owner_user_ids;
$sevenDaysParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-1 week') . ") ";
$fifteenDaysParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-15 day') . ") ";
$oneMonthParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-30 day') . ") ";
@ -266,10 +264,10 @@ class IndexLogic extends Common
$data['threeMonth'] = $customerModel->getDataList(array_merge($customerParam, $threeMonthParam))['dataCount'] ?: 0;
$data['sixMonth'] = $customerModel->getDataList(array_merge($customerParam, $sixMonthParam))['dataCount'] ?: 0;
$data['unContactCustomerCount'] = $customerModel->getDataList(array_merge($customerParam, $unContactParam))['dataCount'] ?: 0;
return $data;
}
/**
* 遗忘数据列表
* @return mixed
@ -292,13 +290,13 @@ class IndexLogic extends Common
$auth_customer_user_ids = $userModel->getUserByPer('crm', 'customer', 'index');
$auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集
$owner_user_ids = array('in', $auth_customer_user_ids);
$sql_unContactCustomerList = db('crm_customer')
->where(['owner_user_id' => $owner_user_ids])
->where('last_time < next_time AND next_time < now()')
->fetchSql()
->select();
$label = $param['label'];
$day = $param['day'] ?: '';
$customerParam = [];
@ -306,7 +304,7 @@ class IndexLogic extends Common
$customerParam['page'] = $param['page'];
$customerParam['search'] = $param['search'];
$customerParam['owner_user_id'] = $owner_user_ids;
switch ($label) {
case 1 :
// ((( next_time < " . strtotime(date('Y-m-d 00:00:00')).") AND (last_time IS NOT NULL)) AND (IFNULL(last_time,next_time) >0))
@ -330,7 +328,7 @@ class IndexLogic extends Common
}
return $customerModel->getDataList($customerParam);
}
/**
* 排行榜
* @param $param
@ -351,7 +349,7 @@ class IndexLogic extends Common
$whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
$userIds = $whereArr['userIds'];
$between_time = $whereArr['between_time'];
$auth_user_ids = $userModel->getUserByPer('bi', 'ranking', 'read');
$auth_user_ids = $auth_user_ids ? array_intersect($userIds, $auth_user_ids) : []; //取交集
switch ($param['label']) {
@ -424,7 +422,6 @@ class IndexLogic extends Common
->where([
'contract.owner_user_id' => ['in', $auth_user_ids],
'contract.create_time' => ['between', $between_time],
'contract.check_status' => 2
])
->group('contract.owner_user_id')
->order('count desc,owner_user_id asc')
@ -433,6 +430,10 @@ class IndexLogic extends Common
//新增客户数
case '4':
//新增客户
$logMap=function ($query) use ($between_time) {
$query->where('customer.create_time', array('between', $between_time))
->whereOr('customer.obtain_time', array('between', $between_time));
};
$list = db('crm_customer')
->alias('customer')
->join('__ADMIN_USER__ user', 'customer.create_user_id=user.id')
@ -444,10 +445,10 @@ class IndexLogic extends Common
'user.thumb_img',
'structure.name',
'customer.owner_user_id as owner_user_id'])
->where([
'customer.owner_user_id' => ['in', $auth_user_ids],
'customer.create_time' => ['between', $between_time],
])
->where(
'customer.owner_user_id' ,['in', $auth_user_ids]
)
->where($logMap)
->group('customer.owner_user_id')
->order('count desc,owner_user_id asc')
->select();
@ -499,7 +500,7 @@ class IndexLogic extends Common
->select();
break;
}
//业绩目标
$between_time = getTimeByType($param['type']);
$start_time = $between_time[0];
@ -558,12 +559,12 @@ class IndexLogic extends Common
$ranking['ranking'][] = $v;
$ranking['self'] = $list['self'];
}
$data = [];
$data = $ranking ?: [];
return $data;
}
/**
* 数据汇总
* @param $param
@ -580,14 +581,14 @@ class IndexLogic extends Common
$user_id = $param['user_id'] ?: [-1];
$userIds = $whereArr['userIds'];
$between_time = $whereArr['between_time'];
$customer_auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'index');
$contacts_auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'index');
$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');
$record_auth_user_ids = $userModel->getUserByPer('crm', 'activity', 'index');
$resDataArr = [];
for ($i = 1; $i <= 5; $i++) {
$resData = queryCache(
@ -607,7 +608,7 @@ class IndexLogic extends Common
}
return $resDataArr;
}
/**
* [数据汇总sql]
* @return
@ -629,19 +630,17 @@ class IndexLogic extends Common
count(1) allCustomer,
COUNT(CASE WHEN deal_status = '已成交' THEN 1 ELSE NULL END) AS dealCustomer
FROM 5kcrm_crm_customer
WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")
and (( ( deal_time > ".$data['deal_time']." ) or (update_time > ".$data['follow_time']." and deal_time > ".$data['deal_time']."))or deal_status = '已成交' or is_lock = 1 )
";
WHERE (create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . " OR obtain_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . ")
AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")";
break;
case 2 :
$countSql = "SELECT
COUNT(distinct CASE WHEN b.activity_type_id in (SELECT customer_id FROM 5kcrm_crm_customer
WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ") AND next_time is not null
WHERE (create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . " OR obtain_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . ")
AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ") AND next_time is not null
) THEN b.activity_type_id ELSE NULL END) as activityNum
FROM 5kcrm_crm_activity AS b
WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
WHERE b.create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
AND b.type = '1'
AND b.activity_type = '2'
AND b.status = '1'
@ -669,14 +668,15 @@ class IndexLogic extends Common
SUM( CASE WHEN r.check_status = 2 THEN r.money ELSE 0 END) AS receivablesMoney,
SUM(CASE WHEN p.money > 0 THEN p.money ELSE 0 END) AS planMoney
FROM 5kcrm_crm_receivables as r
LEFT JOIN 5kcrm_crm_receivables_plan AS p ON p.receivables_id = r.receivables_id
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']) . ")";
break;
}
return $countSql;
}
/**
* 赢单输单查看
*/
@ -708,7 +708,7 @@ class IndexLogic extends Common
$data['businesslist'] = $businessList;
return $data;
}
/**
* 仪表盘布局列表
*/
@ -716,7 +716,7 @@ class IndexLogic extends Common
{
$data = [];
$list = db('crm_dashboard')->where('user_id', $param['user_id'])->find();
if ($list) {
$data = unserialize($list['dashboard']);
return $data ?: [];
@ -730,7 +730,7 @@ class IndexLogic extends Common
$data['left'][2]['modelId'] = 7;
$data['left'][2]['list'] = 1;
$data['left'][2]['isHidden'] = 0;
$data['right'][0]['modelId'] = 2;
$data['right'][0]['list'] = 2;
$data['right'][0]['isHidden'] = 0;
@ -742,16 +742,16 @@ class IndexLogic extends Common
$data['right'][2]['isHidden'] = 0;
return $data;
}
}
/**
* 修改自定义仪表盘
* @param $param
*/
public function updateDashboard($param)
{
$data = db('crm_dashboard')->where('user_id', $param['user_id'])->find();
if ($data) {
$list = db('crm_dashboard')->where('user_id', $param['user_id'])->update(['dashboard' => serialize($param['dashboard'])]);
@ -760,9 +760,9 @@ class IndexLogic extends Common
$list = db('crm_dashboard')->insert(['user_id' => $param['user_id'], 'dashboard' => serialize($param['dashboard'])]);
return $list;
}
}
/**
* 跟进记录列表
* @param $param
@ -815,7 +815,7 @@ class IndexLogic extends Common
$end_time = $param['end_time'] ? strtotime($param['end_time'] . ' 23:59:59') : strtotime(date('Y-m-01', time()) . ' +1 month -1 day');
$type['t.create_time'] = ['between', [$start_time, $end_time]];
}
if ($param['queryType'] == 0) {
$type['t.type'] = ['in', [1, 4]];
} else {
@ -865,7 +865,7 @@ class IndexLogic extends Common
$list[$k]['business_list'] = $activity_business ?: [];
$list[$k]['contacts_list'] = $activity_contacts ?: [];
}
if ($v['activity_type'] == 3) {
$activity_name = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->find();
$list[$k]['activity_type_name'] = $activity_name['name'];
@ -910,7 +910,12 @@ class IndexLogic extends Common
$dataInfo['contractList'] = $relation_list['contract_list'] ?: [];
$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')
@ -937,7 +942,7 @@ class IndexLogic extends Common
$list[$k]['business_list'] = $activity_business ?: [];
$list[$k]['contacts_list'] = $activity_contacts ?: [];
}
if ($param['activity_type'] == 3) {
$activity_name = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->find();
$list[$k]['activity_type_name'] = $activity_name['name'];
@ -982,10 +987,12 @@ class IndexLogic extends Common
$dataInfo['contractList'] = $relation_list['contract_list'] ?: [];
$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'));
}
}
$data = [];
$data['list'] = $list;
$data['dataCount'] = $dataCount ?: 0;
@ -999,7 +1006,7 @@ class IndexLogic extends Common
$data['firstPage'] = true;
$data['lastPage'] = false;
}
if(!empty($param['action'])) return $list;
return $data ?: [];
}
}

@ -169,7 +169,7 @@ class InvoiceLogic
$result['invoice_number'] = $dataArray['invoice_number']; # 发票号码
$result['real_invoice_date'] = $dataArray['real_invoice_date']; # 开票日期
$result['flow_id'] = $dataArray['flow_id']; # 审核ID
$check=['0'=>'待审核','1'=>'审核中','2'=>'审核通过','3'=>'审核未通过','4'=>'撤销','5'=>'草稿(未提交)','6'=>'作废'];
# 基本信息
$result['essential'] = [
'invoice_apple_number' => $dataArray['invoice_apple_number'],
@ -187,7 +187,7 @@ class InvoiceLogic
'invoice_number' => $dataArray['invoice_number'],
'real_invoice_date' => $dataArray['real_invoice_date'],
'customer_id' => $dataArray['customer_id'],
'contract_id' => $dataArray['contract_id']
'check_status' => $check[$dataArray['check_status']]
];
# 发票信息

@ -0,0 +1,243 @@
<?php
namespace app\crm\logic;
use think\Db;
use think\Validate;
use app\crm\model\Market;
class MarketLogic{
/**
*
* @param $param
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/27 0027 09:46
*/
public function getDataList($param){
$userModel = new \app\admin\model\User();
if($param['search']) {
$where['market_field_id'] = $param['search'];
}
//权限
$a = 'index';
$auth_user_ids = $userModel->getUserByPer('crm', 'market', $a);
$authMap['market.create_user_id'] = ['in', $auth_user_ids];
$list=db('crm_market')
->alias('market')
->join('__CRM_MARKET_CATEGORY__ market_category','market_category.r_id=market.market_field_id')
->where($where)
->where($authMap)
->page($param['page'],$param['limit'])
->order()
->select();
return $list;
}
/**
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/27 0027 09:46
*/
public function marketList(){
$list=db('admin_market')->where('status',1)->field('types,name')->select();
$data=[
0=>[
'name'=>'客户',
'types'=>'crm_customer'
],
1=>[
'name'=>'线索',
'types'=>'crm_leads'
]
];
$data=array_merge($data,$list);
return $data;
}
public function createData($param){
$fieldModel = new \app\admin\model\Field();
$dataInfo = db('crm_market')->where(['name' => $param['name']])->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();
return false;
}
}
if (db('crm_market')->data($param)->allowField(true)->isUpdate(false)->save()) {
updateActionLog($param['create_user_id'], 'crm_market', $this->product_id, '', '', '创建了市场活动');
RecordActionLog($param['create_user_id'], 'crm_market', 'save', $param['name'], '', '', '新增了市场活动' . $param['name']);
$data = [];
$data['product_id'] = $this->product_id;
return $data;
} else {
$this->error = '添加失败';
return false;
}
}
/**
* 修改
* @param $param
* @param string $market_id
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/27 0027 15:57
*/
public function updateDataById($param,$market_id = ''){
$fieldModel = new \app\admin\model\Field();
$dataInfo = db('crm_market')->where(['market_id' => $market_id])->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();
return false;
}
}
$param['market_id'] = $market_id;
if (db('crm_market')->update($param, ['market_id' => $market_id], true)) {
updateActionLog($param['create_user_id'], 'crm_market', $this->market_id, '', '', '编辑了市场活动');
RecordActionLog($param['create_user_id'], 'crm_market', 'update', $param['name'], '', '', '编辑了市场活动' . $param['name']);
$data = [];
$data['market_id'] = $this->market_id;
return $data;
} else {
$this->error = '添加失败';
return false;
}
}
/**
* 删除
* @param $id_list
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/28 0028 10:48
*/
public function delete($id_list){
$marketModel = model('Market');
// 错误信息
$delIds = [];
$error_message = [];
// 过滤后的ID
$id_list_filter = db('crm_market')->where(['market_id' => ['IN', $id_list]])->column('market_id');
$diff = array_diff($id_list, $id_list_filter);
if (!empty($diff)) {
foreach ($diff as $key => $val) {
$error_message[] = sprintf('ID为 %d 的活动删除失败,错误原因:数据不存在或已删除。', $val);
}
array_unshift($error_message, '数据已更新,刷新页面后重试!');
return resultArray(['error' => $error_message]);
}
//数据权限判断
$userModel = new \app\admin\model\User();
$auth_user_ids = $userModel->getUserByPer('crm', 'market', 'delete');
foreach ($id_list as $k => $v) {
$isDel = true;
//数据详情
$data = $this->getDataById($v);
if (!in_array($data['create_user_id'], $auth_user_ids)) {
$isDel = false;
$errorMessage[] = '名称为' . $data['name'] . '的活动删除失败,错误原因:无权操作';
}
if ($isDel) {
$delIds[] = $v;
}
}
$dataInfo = db('crm_market')->where('market_id',['in',$delIds])->select();
if ($delIds) {
// 软删除数据
$res = $marketModel::destroy(['market_id' => ['IN', $delIds]]);
if ($res == count($delIds)) {
// 添加删除记录
$userInfo = $this->userInfo;
foreach ($dataInfo as $k => $v) {
RecordActionLog($id_list['user_id'], 'crm_market', 'delete', $v['name'], '', '', '删除了活动:' . $v['name']);
}
return resultArray(['data' => '删除成功']);
} else {
return resultArray(['error' => '删除失败']);
}
}
if ($errorMessage) {
return resultArray(['error' => $errorMessage]);
} else {
return resultArray(['data' => '删除成功']);
}
}
/**
* 基本信息
* @param string $id
* @param int $userId
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/27 0027 18:03
*/
public function getDataById($id = '', $userId = 0)
{
$map['market_id'] = $id;
$dataInfo = db('crm_market')->where($map)->find();
if (!$dataInfo) {
$this->error = '暂无此数据';
return false;
}
# 获取封面图片
$dataInfo['cover_images'] = $this->getMarketImages($dataInfo['cover_images']);
# 获取详情图片
$dataInfo['details_images'] = $this->getMarketImages($dataInfo['details_images']);
$userModel = new \app\admin\model\User();
$dataInfo['create_user_id_info'] = $userModel->getUserById($dataInfo['create_user_id']);
$dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
$dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
// 字段授权
if (!empty($userId)) {
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
foreach ($dataInfo as $key => $value) {
if (!$userLevel && !empty($grantData['crm_market'])) {
$status = getFieldGrantStatus($key, $grantData['crm_market']);
# 查看权限
if ($status['read'] == 0) unset($dataInfo[$key]);
}
}
}
return $dataInfo;
}
/**
* 获取活动图片
* @param $fileIds
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/28 0028 10:36
*/
private function getMarketImages($fileIds)
{
$files = Db::name('admin_file')->whereIn('file_id', $fileIds)->select();
foreach ($files as $key => $value) {
$files[$key]['file_path'] = getFullPath($value['file_path']);
$files[$key]['file_path_thumb'] = getFullPath($value['file_path_thumb']);
$files[$key]['size'] = format_bytes($value['size']);
}
return $files;
}
}

@ -15,30 +15,35 @@ class PrintingLogic
/**
* 获取打印数据
*
* @param $type
* @param $actionId
* @param $templateId
* @param int $type 打印模板类型
* @param int $actionId 操作ID商机数据ID、合同数据ID、回款数据ID
* @param int $templateId 模板ID
* @param int $recordId 记录ID
* @author fanqi
* @since 2021-03-29
* @return array|string|string[]
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function getPrintingData($type, $actionId, $templateId)
public function getPrintingData($type, $actionId, $templateId, $recordId)
{
$result = [];
$content = htmlspecialchars_decode(Db::name('admin_printing')->where('id', $templateId)->value('content'));
$content = Db::name('admin_printing')->where('id', $templateId)->value('content');
$content = json_decode($content, true);
$content = $content['data'];
$content = str_replace('\n', '', $content);
$content = str_replace('\\', '', $content);
# 商机模板
if ($type == 1) $result = $this->getBusinessData($actionId, $content);
if ($type == 5) $result = $this->getBusinessData($actionId, $content);
# 合同模板
if ($type == 2) $result = $this->getContractData($actionId, $content);
if ($type == 6) $result = $this->getContractData($actionId, $content);
# 回款模板
if ($type == 3) $result = $this->getReceivablesData($actionId, $content);
if ($type == 7) $result = $this->getReceivablesData($actionId, $content);
# 打印记录
if ($type == 20) $result = $this->getHistoryData($recordId);
return $result;
}
@ -71,6 +76,7 @@ class PrintingLogic
'type' => $param['type'],
'action_id' => $param['action_id'],
'template_id' => $param['template_id'],
'content' => json_encode(['data' => $param['recordContent']]),
'create_time' => time(),
'update_time' => time()
];
@ -95,8 +101,8 @@ class PrintingLogic
$limit = !empty($param['limit']) ? $param['limit'] : 15;
$page = !empty($param['page']) ? $param['page'] : 1;
$where['type'] = $param['type'];
$where['user_id'] = $userId;
$where['action_id'] = $param['typeId'];
$where['type'] = $param['crmType'];
$count = Db::name('crm_printing_record')->where($where)->count();
$data = Db::name('crm_printing_record')->where($where)->limit(($page - 1) * $limit, $limit)->select();
@ -105,6 +111,7 @@ class PrintingLogic
$templateName = Db::name('admin_printing')->where('id', $value['template_id'])->value('name');
$result[] = [
'record_id' => $value['printing_id'],
'type' => $value['type'],
'action_id' => $value['action_id'],
'template_id' => $value['template_id'],
@ -128,6 +135,9 @@ class PrintingLogic
*/
private function getBusinessData($id, $content)
{
# 清除无用数据
$content = preg_replace("/[\t\n\r]+/", "", $content);
# 查询商机数据
$businessData = Db::name('crm_business')->where('business_id', $id)->find();
# 查询商机状态组
@ -137,80 +147,158 @@ class PrintingLogic
# 查询客户数据
$customerData = Db::name('crm_customer')->where('customer_id', $businessData['customer_id'])->find();
# 查询产品数据
$businessProduct = Db::name('crm_business_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal'])->where('business_id', $businessData['business_id'])->select();
$businessProduct = Db::name('crm_business_product')->where('business_id', $businessData['business_id'])->select();
$productIdArray = [];
$productInfo = [];
foreach ($businessProduct AS $key => $value) {
$productIdArray[] = $value['product_id'];
$productInfo[$value['product_id']] = $value;
}
$productList = Db::name('crm_product')->whereIn('product_id', $productIdArray)->select();
$productInfo = [];
foreach ($productList AS $key => $value) {
$productInfo[$value['product_id']] = $value;
}
# 产品类别数据
$productCategoryList = db('crm_product_category')->select();
$productCategoryData = [];
foreach ($productCategoryList AS $key => $value) {
$productCategoryData[$value['category_id']] = $value['name'];
}
# 创建人
$createUserName = Db::name('admin_user')->where('id', $businessData['create_user_id'])->value('realname');
# 负责人
$ownerUserName = Db::name('admin_user')->where('id', $businessData['owner_user_id'])->value('realname');
# 产品自定义字段
$productFields = db('admin_field')->field(['field', 'name', 'form_type'])->where('types', 'crm_product')->select();
# 产品数据替换
preg_match_all('/<tr data-wk-table-tr-tag="value">(.*)<\/tr>/mU', $content, $productHtml);
if (!empty($productHtml[1])) {
foreach ($productHtml[1] AS $k => $v) {
if (empty($productHtml[0][$k])) continue;
$oldHtml = $productHtml[0][$k]; # 保留旧HTML数据用于str_str_replace函数查找替换
$replaceHtml = ''; # 要替换的HTML数据
foreach ($businessProduct AS $key => $value) {
$replaceHtml .= '<tr data-wk-table-tr-tag="value">';
$detail = str_replace('{产品名称}', $productInfo[$value['product_id']]['name'], $productHtml[1][$k]);
$detail = str_replace('{产品编码}', $productInfo[$value['product_id']]['num'], $detail);
$detail = str_replace('{单位}', $value['unit'], $detail);
$detail = str_replace('{标准价格}', $value['price'], $detail);
$detail = str_replace('{产品描述}', $productInfo[$value['product_id']]['description'], $detail);
$detail = str_replace('{售价}', $value['sales_price'], $detail);
$detail = str_replace('{数量}', (int)$value['num'], $detail);
$detail = str_replace('{折扣}', (int)$value['discount'].'%', $detail);
$detail = str_replace('{合计}', $value['subtotal'], $detail);
foreach ($productFields AS $key1 => $value1) {
switch ($value1['form_type']) {
case 'user' :
$productUsers = db('admin_user')->whereIn('id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('realname');
$detail = str_replace('{'.$value1['name'].'}', implode(',', $productUsers), $detail);
break;
case 'structure' :
$productStructure = db('admin_structure')->whereIn('id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('name');
$detail = str_replace('{'.$value1['name'].'}', implode(',', $productStructure), $detail);
break;
case 'file' :
$productFiles = db('admin_file')->whereIn('file_id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('name');
$detail = str_replace('{'.$value1['name'].'}', implode(',', $productFiles), $detail);
break;
case 'datetime' :
$productDatetime = !empty($productInfo[$value['product_id']][$value1['field']]) ? date('Y-m-d H:i:s', $productInfo[$value['product_id']][$value1['field']]) : '';
$detail = str_replace('{'.$value1['name'].'}', $productDatetime, $detail);
break;
case 'category' :
$categoryId = $productInfo[$value['product_id']]['category_id'];
$detail = str_replace('{'.$value1['name'].'}', !empty($productCategoryData[$categoryId]) ? $productCategoryData[$categoryId] : '', $detail);
break;
default :
$detail = str_replace('{'.$value1['name'].'}', trim($productInfo[$value['product_id']][$value1['field']], ','), $detail);
}
}
# 商机模板数据替换
$content = str_replace('{商机名称}', $businessData['name'], $content);
if (strstr($detail, '{产品类别}')) {
$categoryNam = Db::name('crm_product_category')->where('category_id', $productInfo[$value['product_id']]['category_id'])->value('name');
$detail = str_replace('{产品类别}', $categoryNam, $detail);
}
$replaceHtml .= $detail . '</tr>';
}
$content = str_replace($oldHtml, $replaceHtml, $content);
}
}
# 替换商机数据
$content = str_replace('{商机状态组}', $businessType, $content);
$content = str_replace('{商机阶段}', $businessStatus, $content);
$content = str_replace('{商机金额}', $businessData['money'], $content);
$content = str_replace('{预计成交日期}', $businessData['deal_date'], $content);
$content = str_replace('{备注}', $businessData['remark'], $content);
$content = str_replace('{负责人}', $createUserName, $content);
$content = str_replace('{创建人}', $ownerUserName, $content);
$content = str_replace('{创建日期}', date('Y-m-d H:i:s', $businessData['create_time']), $content);
$content = str_replace('{更新日期}', date('Y-m-d H:i:s', $businessData['update_time']), $content);
# 客户模板数据替换
$content = str_replace('{客户名称}', $customerData['name'], $content);
$content = str_replace('{客户级别}', $customerData['level'], $content);
$content = str_replace('{客户行业}', $customerData['industry'], $content);
$content = str_replace('{客户来源}', $businessStatus, $content);
$content = str_replace('{成交状态}', $customerData['deal_status'], $content);
$content = str_replace('{电话}', $customerData['telephone'], $content);
$content = str_replace('{网址}', $customerData['website'], $content);
$content = str_replace('{手机}', $customerData['mobile'], $content);
# 产品模板数据替换
preg_match_all('/(data-wk-table-tr-tag="value")>(.*)<\/tr>/mU', $content, $productHtml);
if (!empty($productHtml[2])) {
# 循环匹配到的HTML数据
foreach ($productHtml[2] AS $key => $value) {
# 循环产品数据
$oldHtml = $productHtml[0][$key]; # 保留旧HTML数据用于str_str_replace函数查找替换
$replaceHtml = '';
foreach ($productList AS $k => $v) {
if ($k == 0) {
$replaceHtml .= 'data-wk-table-tr-tag="value">';
} else {
$replaceHtml .= '<tr data-wk-table-tr-tag="value">';
}
$value = str_replace('{产品名称}', $v['name'], $value);
$value = str_replace('{产品编码}', $v['num'], $value);
$value = str_replace('{单位}', $v['unit'], $value);
$value = str_replace('{标准价格}', $v['price'], $value);
$value = str_replace('{产品描述}', $v['description'], $value);
$value = str_replace('{售价}', $productInfo[$v['product_id']]['sales_price'], $value);
$value = str_replace('{数量}', $productInfo[$v['product_id']]['num'], $value);
$value = str_replace('{折扣}', $productInfo[$v['product_id']]['discount'], $value);
$value = str_replace('{整单折扣}', $businessData['discount_rate'], $value);
$value = str_replace('{合计}', $productInfo[$v['product_id']]['subtotal'], $value);
if (strstr($value, '{产品类别}')) {
$categoryNam = Db::name('crm_product_category')->where('category_id', $v['category_id'])->value('name');
$value = str_replace('{产品类别}', $categoryNam, $value);
}
$replaceHtml .= $value . '</tr>';
$businessFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_business')->select();
foreach ($businessFields AS $key => $value) {
preg_match_all('/<span class="wk-print-tag-wukong wk-tiny-color--business" contenteditable="([true|false]*)" data-wk-tag="business.'.$value['field'].'">(.*)<\/span>/mU', $content, $businessHtml);
if (!empty($businessHtml[0])) {
$businessSourceData = $businessHtml[0];
switch ($value['form_type']) {
case 'user' :
$businessUsers = db('admin_user')->whereIn('id', trim($businessData[$value['field']], ','))->column('realname');
$businessTargetData = str_replace('{'.$value['name'].'}', implode(',', $businessUsers), $businessHtml[0]);
break;
case 'structure' :
$businessStructure = db('admin_structure')->whereIn('id', trim($businessData[$value['field']], ','))->column('name');
$businessTargetData = str_replace('{'.$value['name'].'}', implode(',', $businessStructure), $businessHtml[0]);
break;
case 'file' :
$businessFiles = db('admin_file')->whereIn('file_id', trim($businessData[$value['field']], ','))->column('name');
$businessTargetData = str_replace('{'.$value['name'].'}', implode(',', $businessFiles), $businessHtml[0]);
break;
case 'datetime' :
$businessDatetime = !empty($businessData[$value['field']]) ? date('Y-m-d H:i:s', $businessData[$value['field']]) : '';
$businessTargetData = str_replace('{'.$value['name'].'}', $businessDatetime, $businessHtml[0]);
break;
default :
$businessTargetData = str_replace('{'.$value['name'].'}', trim($businessData[$value['field']], ','), $businessHtml[0]);
}
$content = str_replace($businessSourceData, $businessTargetData, $content);
}
}
$content = str_replace($oldHtml, $replaceHtml, $content);
# 替换客户数据
$content = str_replace('{详细地址}', $customerData['detail_address'], $content);
$content = str_replace('{区域}', $customerData['address'], $content);
$customerFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_customer')->select();
foreach ($customerFields AS $key => $value) {
preg_match_all('/<span class="wk-print-tag-wukong wk-tiny-color--customer" contenteditable="([true|false]*)" data-wk-tag="customer.'.$value['field'].'">(.*)<\/span>/mU', $content, $customerHtml);
if (!empty($customerHtml[0])) {
$customerSourceData = $customerHtml[0];
switch ($value['form_type']) {
case 'user' :
$customerUsers = db('admin_user')->whereIn('id', trim($customerData[$value['field']], ','))->column('realname');
$customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerUsers), $customerHtml[0]);
break;
case 'structure' :
$customerStructure = db('admin_structure')->whereIn('id', trim($customerData[$value['field']], ','))->column('name');
$customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerStructure), $customerHtml[0]);
break;
case 'file' :
$customerFiles = db('admin_file')->whereIn('file_id', trim($customerData[$value['field']], ','))->column('name');
$customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerFiles), $customerHtml[0]);
break;
case 'datetime' :
$customerDatetime = !empty($customerData[$value['field']]) ? date('Y-m-d H:i:s', $customerData[$value['field']]) : '';
$customerTargetData = str_replace('{'.$value['name'].'}', $customerDatetime, $customerHtml[0]);
break;
default :
$customerTargetData = str_replace('{'.$value['name'].'}', trim($customerData[$value['field']], ','), $customerHtml[0]);
}
$content = str_replace($customerSourceData, $customerTargetData, $content);
}
}
# 替换整单折扣
$content = str_replace('{整单折扣}', $businessData['discount_rate'], $content);
$content = str_replace('{整单折扣}', (int)$businessData['discount_rate'].'%', $content);
$content = str_replace('{产品总金额}', $businessData['money'], $content);
return $content;
}
@ -227,6 +315,9 @@ class PrintingLogic
*/
private function getContractData($id, $content)
{
# 清除无用数据
$content = preg_replace("/[\t\n\r]+/", "", $content);
# 查询合同数据
$contractData = Db::name('crm_contract')->where('contract_id', $id)->find();
# 查询商机数据
@ -236,18 +327,21 @@ 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'])->where('business_id', $contractData['business_id'])->select();
$businessProduct = Db::name('crm_business_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal', 'unit'])->where('business_id', $contractData['business_id'])->select();
$productIdArray = [];
$productInfo = [];
foreach ($businessProduct AS $key => $value) {
$productIdArray[] = $value['product_id'];
$productInfo[$value['product_id']] = $value;
}
$productList = Db::name('crm_product')->whereIn('product_id', $productIdArray)->select();
$productInfo = [];
foreach ($productList AS $key => $value) {
$productInfo[$value['product_id']] = $value;
}
# 回款金额
$receivablesModel = new \app\crm\model\Receivables();
$moneyInfo = $receivablesModel->getMoneyByContractId($contractData['contract_id']);
$doneMoney = $moneyInfo['doneMoney'] ? : 0.00;
$doneMoney = !empty($moneyInfo['doneMoney']) ? $moneyInfo['doneMoney'] : 0.00;
$unMoney = $moneyInfo['contractMoney'] - $doneMoney > 0 ? $moneyInfo['contractMoney'] - $doneMoney : 0.00;
# 合同签约人
$signerString = '';
$signerArray = Db::name('admin_user')->field('realname')->whereIn('id', $contractData['order_user_id'])->select();
@ -256,26 +350,112 @@ class PrintingLogic
$createUserName = Db::name('admin_user')->where('id', $contractData['create_user_id'])->value('realname');
# 负责人
$ownerUserName = Db::name('admin_user')->where('id', $contractData['owner_user_id'])->value('realname');
# 合同附件
$fileList = Db::name('crm_contract_file')->alias('contract')->join('__ADMIN_FILE__ file', 'file.file_id = contract.file_id', 'left')
->where('contract.contract_id', $id)->column('file.file_path');
$fileInfo = [];
foreach ($fileList AS $key => $value) {
$fileInfo[] = getFullPath($value['file_path']);
}
# 产品类别数据
$productCategoryList = db('crm_product_category')->select();
$productCategoryData = [];
foreach ($productCategoryList AS $key => $value) {
$productCategoryData[$value['category_id']] = $value['name'];
}
# 产品自定义字段
$productFields = db('admin_field')->field(['field', 'name', 'form_type'])->where('types', 'crm_product')->select();
# 客户模板数据替换
$content = str_replace('{客户名称}', $customerData['name'], $content);
$content = str_replace('{客户级别}', $customerData['level'], $content);
$content = str_replace('{客户行业}', $customerData['industry'], $content);
$content = str_replace('{客户来源}', $customerData['source'], $content);
$content = str_replace('{成交状态}', $customerData['deal_status'], $content);
$content = str_replace('{网址}', $customerData['website'], $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--customer" contenteditable="([true|false]*?)" data-wk-tag="customer.mobile">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--customer" contenteditable="true" data-wk-tag="customer.mobile">'.$customerData['mobile'].'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--customer" contenteditable="([true|false]*?)" data-wk-tag="customer.telephone">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--customer" contenteditable="true" data-wk-tag="customer.telephone">'.$customerData['telephone'].'</span>', $content);
# 合同模板数据替换
$content = str_replace('{合同编号}', $contractData['num'], $content);
$content = str_replace('{合同名称}', $contractData['name'], $content);
$content = str_replace('{客户名称}', $customerData['name'], $content);
# 产品模板数据替换
preg_match_all('/<tr data-wk-table-tr-tag="value">(.*)<\/tr>/mU', $content, $productHtml);
if (!empty($productHtml[1])) {
foreach ($productHtml[1] AS $k => $v) {
$oldHtml = $productHtml[0][$k]; # 保留旧HTML数据用于str_str_replace函数查找替换
$replaceHtml = ''; # 要替换的HTML数据
foreach ($businessProduct AS $key => $value) {
$replaceHtml .= '<tr data-wk-table-tr-tag="value">';
$detail = str_replace('{产品名称}', $productInfo[$value['product_id']]['name'], $productHtml[1][$k]);
$detail = str_replace('{产品编码}', $productInfo[$value['product_id']]['num'], $detail);
$detail = str_replace('{单位}', $value['unit'], $detail);
$detail = str_replace('{标准价格}', $value['price'], $detail);
$detail = str_replace('{产品描述}', $productInfo[$value['product_id']]['description'], $detail);
$detail = str_replace('{售价}', $value['sales_price'], $detail);
$detail = str_replace('{数量}', (int)$value['num'], $detail);
$detail = str_replace('{折扣}', (int)$value['discount'].'%', $detail);
$detail = str_replace('{合计}', $value['subtotal'], $detail);
foreach ($productFields AS $key1 => $value1) {
switch ($value1['form_type']) {
case 'user' :
$productUsers = db('admin_user')->whereIn('id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('realname');
$detail = str_replace('{'.$value1['name'].'}', implode(',', $productUsers), $detail);
break;
case 'structure' :
$productStructure = db('admin_structure')->whereIn('id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('name');
$detail = str_replace('{'.$value1['name'].'}', implode(',', $productStructure), $detail);
break;
case 'file' :
$productFiles = db('admin_file')->whereIn('file_id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('name');
$detail = str_replace('{'.$value1['name'].'}', implode(',', $productFiles), $detail);
break;
case 'datetime' :
$productDatetime = !empty($productInfo[$value['product_id']][$value1['field']]) ? date('Y-m-d H:i:s', $productInfo[$value['product_id']][$value1['field']]) : '';
$detail = str_replace('{'.$value1['name'].'}', $productDatetime, $detail);
break;
case 'category' :
$categoryId = $productInfo[$value['product_id']]['category_id'];
$detail = str_replace('{'.$value1['name'].'}', !empty($productCategoryData[$categoryId]) ? $productCategoryData[$categoryId] : '', $detail);
break;
default :
$detail = str_replace('{'.$value1['name'].'}', trim($productInfo[$value['product_id']][$value1['field']], ','), $detail);
}
}
if (strstr($detail, '{产品类别}')) {
$categoryNam = Db::name('crm_product_category')->where('category_id', $productInfo[$value['product_id']]['category_id'])->value('name');
$detail = str_replace('{产品类别}', $categoryNam, $detail);
}
$replaceHtml .= $detail . '</tr>';
}
$content = str_replace($oldHtml, $replaceHtml, $content);
}
}
# 替换客户数据
$content = str_replace('{详细地址}', $customerData['detail_address'], $content);
$content = str_replace('{区域}', $customerData['address'], $content);
$customerFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_customer')->select();
foreach ($customerFields AS $key => $value) {
preg_match_all('/<span class="wk-print-tag-wukong wk-tiny-color--customer" contenteditable="([true|false]*)" data-wk-tag="customer.'.$value['field'].'">(.*)<\/span>/mU', $content, $customerHtml);
if (!empty($customerHtml[0])) {
$customerSourceData = $customerHtml[0];
switch ($value['form_type']) {
case 'user' :
$customerUsers = db('admin_user')->whereIn('id', trim($customerData[$value['field']], ','))->column('realname');
$customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerUsers), $customerHtml[0]);
break;
case 'structure' :
$customerStructure = db('admin_structure')->whereIn('id', trim($customerData[$value['field']], ','))->column('name');
$customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerStructure), $customerHtml[0]);
break;
case 'file' :
$customerFiles = db('admin_file')->whereIn('file_id', trim($customerData[$value['field']], ','))->column('name');
$customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerFiles), $customerHtml[0]);
break;
case 'datetime' :
$customerDatetime = !empty($customerData[$value['field']]) ? date('Y-m-d H:i:s', $customerData[$value['field']]) : '';
$customerTargetData = str_replace('{'.$value['name'].'}', $customerDatetime, $customerHtml[0]);
break;
default :
$customerTargetData = str_replace('{'.$value['name'].'}', trim($customerData[$value['field']], ','), $customerHtml[0]);
}
$content = str_replace($customerSourceData, $customerTargetData, $content);
}
}
# 替换合同数据
$content = str_replace('{商机名称}', $businessData['name'], $content);
$content = str_replace('{下单时间}', $contractData['order_date'], $content);
$content = str_replace('{合同金额}', $contractData['money'], $content);
$content = str_replace('{合同开始时间}', $contractData['start_time'], $content);
$content = str_replace('{合同到期时间}', $contractData['end_time'], $content);
$content = str_replace('{合同附件}', implode(' | ', $fileInfo), $content);
$content = str_replace('{客户签约人}', $contactsData['name'], $content);
$content = str_replace('{公司签约人}', trim($signerString, '、'), $content);
$content = str_replace('{负责人}', $createUserName, $content);
@ -283,60 +463,70 @@ class PrintingLogic
$content = str_replace('{创建日期}', date('Y-m-d H:i:s', $contractData['create_time']), $content);
$content = str_replace('{更新日期}', date('Y-m-d H:i:s', $contractData['update_time']), $content);
$content = str_replace('{已收款金额}', $doneMoney, $content);
$content = str_replace('{未收款金额}', $contractData['money'] - $doneMoney, $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="([true|false]*?)" data-wk-tag="contract.remark">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="true" data-wk-tag="contract.remark">'.$contractData['remark'].'</span>', $content);
$content = str_replace('{未收款金额}', $unMoney, $content);
$contractFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_contract')->select();
foreach ($contractFields AS $key => $value) {
preg_match_all('/<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="([true|false]*)" data-wk-tag="contract.'.$value['field'].'">(.*)<\/span>/mU', $content, $contractHtml);
if (!empty($contractHtml[0])) {
$contractSourceData = $contractHtml[0];
switch ($value['form_type']) {
case 'user' :
$contractUsers = db('admin_user')->whereIn('id', trim($contractData[$value['field']], ','))->column('realname');
$contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractUsers), $contractHtml[0]);
break;
case 'structure' :
$contractStructure = db('admin_structure')->whereIn('id', trim($contractData[$value['field']], ','))->column('name');
$contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractStructure), $contractHtml[0]);
break;
case 'file' :
$contractFiles = db('admin_file')->whereIn('file_id', trim($contractData[$value['field']], ','))->column('name');
$contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractFiles), $contractHtml[0]);
break;
case 'datetime' :
$contractDatetime = !empty($contractData[$value['field']]) ? date('Y-m-d H:i:s', $contractData[$value['field']]) : '';
$contractTargetData = str_replace('{'.$value['name'].'}', $contractDatetime, $contractHtml[0]);
break;
default :
$contractTargetData = str_replace('{'.$value['name'].'}', trim($contractData[$value['field']], ','), $contractHtml[0]);
}
$content = str_replace($contractSourceData, $contractTargetData, $content);
}
}
# 联系人模板替换
$content = str_replace('{姓名}', $contactsData['name'], $content);
# 替换联系人数据
$content = str_replace('{客户名称}', $customerData['name'], $content);
$content = str_replace('{电子邮箱}', $contactsData['email'], $content);
$content = str_replace('{是否关键决策人}', $contactsData['decision'], $content);
$content = str_replace('{职务}', $contactsData['post'], $content);
$content = str_replace('{性别}', $contactsData['sex'], $content);
$content = str_replace('{地址}', $contactsData['detail_address'], $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--contacts" contenteditable="([true|false]*?)" data-wk-tag="contacts.mobile">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--contacts" contenteditable="true" data-wk-tag="contacts.mobile">'.$contactsData['mobile'].'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--contacts" contenteditable="([true|false]*?)" data-wk-tag="contacts.telephone">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--contacts" contenteditable="true" data-wk-tag="contacts.telephone">'.$contactsData['telephone'].'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--contacts" contenteditable="([true|false]*?)" data-wk-tag="contacts.remark">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--contacts" contenteditable="true" data-wk-tag="contacts.remark">'.$contactsData['remark'].'</span>', $content);
# 替换产品模板
preg_match_all('/(data-wk-table-tr-tag="value")>(.*)<\/tr>/mU', $content, $productHtml);
if (!empty($productHtml[2])) {
# 循环匹配到的HTML数据
foreach ($productHtml[2] AS $key => $value) {
# 循环产品数据
$oldHtml = $productHtml[0][$key]; # 保留旧HTML数据用于str_str_replace函数查找替换
$replaceHtml = '';
foreach ($productList AS $k => $v) {
if ($k == 0) {
$replaceHtml .= 'data-wk-table-tr-tag="value">';
} else {
$replaceHtml .= '<tr data-wk-table-tr-tag="value">';
}
$value = str_replace('{产品名称}', $v['name'], $value);
$value = str_replace('{产品编码}', $v['num'], $value);
$value = str_replace('{单位}', $v['unit'], $value);
$value = str_replace('{标准价格}', $v['price'], $value);
$value = str_replace('{产品描述}', $v['description'], $value);
$value = str_replace('{售价}', $productInfo[$v['product_id']]['sales_price'], $value);
$value = str_replace('{数量}', $productInfo[$v['product_id']]['num'], $value);
$value = str_replace('{折扣}', $productInfo[$v['product_id']]['discount'], $value);
$value = str_replace('{整单折扣}', $businessData['discount_rate'], $value);
$value = str_replace('{合计}', $productInfo[$v['product_id']]['subtotal'], $value);
if (strstr($value, '{产品类别}')) {
$categoryNam = Db::name('crm_product_category')->where('category_id', $v['category_id'])->value('name');
$value = str_replace('{产品类别}', $categoryNam, $value);
}
$replaceHtml .= $value . '</tr>';
$contactsFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_contacts')->select();
foreach ($contactsFields AS $key => $value) {
preg_match_all('/<span class="wk-print-tag-wukong wk-tiny-color--contacts" contenteditable="([true|false]*)" data-wk-tag="contacts.'.$value['field'].'">(.*)<\/span>/mU', $content, $contactsHtml);
if (!empty($contactsHtml[0])) {
$contactsSourceData = $contactsHtml[0];
switch ($value['form_type']) {
case 'user' :
$contactsUsers = db('admin_user')->whereIn('id', trim($contactsData[$value['field']], ','))->column('realname');
$contactsTargetData = str_replace('{'.$value['name'].'}', implode(',', $contactsUsers), $contactsHtml[0]);
break;
case 'structure' :
$contactsStructure = db('admin_structure')->whereIn('id', trim($contactsData[$value['field']], ','))->column('name');
$contactsTargetData = str_replace('{'.$value['name'].'}', implode(',', $contactsStructure), $contactsHtml[0]);
break;
case 'file' :
$contactsFiles = db('admin_file')->whereIn('file_id', trim($contactsData[$value['field']], ','))->column('name');
$contactsTargetData = str_replace('{'.$value['name'].'}', implode(',', $contactsFiles), $contactsHtml[0]);
break;
case 'datetime' :
$contactsDatetime = !empty($contactsData[$value['field']]) ? date('Y-m-d H:i:s', $contactsData[$value['field']]) : '';
$contactsTargetData = str_replace('{'.$value['name'].'}', $contactsDatetime, $contactsHtml[0]);
break;
default :
$contactsTargetData = str_replace('{'.$value['name'].'}', trim($contactsData[$value['field']], ','), $contactsHtml[0]);
}
$content = str_replace($oldHtml, $replaceHtml, $content);
}
$content = str_replace($contactsSourceData, $contactsTargetData, $content);
}
# 替换整单折扣
$content = str_replace('{整单折扣}', $businessData['discount_rate'], $content);
$content = str_replace('{产品总金额}', $businessData['money'], $content);
return $content;
}
@ -360,7 +550,7 @@ class PrintingLogic
# 查询客户数据
$customerName = Db::name('crm_customer')->where('customer_id', $receivablesData['customer_id'])->value('name');
# 查询商机数据
$businessName = Db::name('crm_business')->where('business_id', $contractData['business_id'])->find();
$businessName = Db::name('crm_business')->where('business_id', $contractData['business_id'])->value('name');
# 查询联系人数据
$contactsName = Db::name('crm_contacts')->where('contacts_id', $contractData['contacts_id'])->value('name');
# 合同签约人
@ -371,46 +561,150 @@ class PrintingLogic
$contractCreate = Db::name('admin_user')->where('id', $contractData['create_user_id'])->value('realname');
$contractOwner = Db::name('admin_user')->where('id', $contractData['owner_user_id'])->value('realname');
# 回款创建人、负责人
$receivablesCreate = Db::name('admin_user')->where('id', $contractData['create_user_id'])->value('realname');
$receivablesOwner = Db::name('admin_user')->where('id', $contractData['owner_user_id'])->value('realname');
$receivablesCreate = Db::name('admin_user')->where('id', $receivablesData['create_user_id'])->value('realname');
$receivablesOwner = Db::name('admin_user')->where('id', $receivablesData['owner_user_id'])->value('realname');
# 回款金额
$receivablesModel = new \app\crm\model\Receivables();
$moneyInfo = $receivablesModel->getMoneyByContractId($contractData['contract_id']);
$doneMoney = $moneyInfo['doneMoney'] ? : 0.00;
# 合同附件
$fileList = Db::name('crm_contract_file')->alias('contract')->join('__ADMIN_FILE__ file', 'file.file_id = contract.file_id', 'left')
->where('contract.contract_id', $id)->column('file.file_path');
$fileInfo = [];
foreach ($fileList AS $key => $value) {
$fileInfo[] = getFullPath($value['file_path']);
}
# 期数
$plan = '';
if (!empty($receivablesData['plan_id'])) {
$plan = db('crm_receivables_plan')->where('plan_id', $receivablesData['plan_id'])->value('num');
}
# 合同模板数据替换
$content = str_replace('{合同编号}', $contractData['num'], $content);
$content = str_replace('{合同名称}', $contractData['name'], $content);
$content = str_replace('{客户名称}', $customerName, $content);
# 替换合同数据
$content = str_replace('{商机名称}', $businessName, $content);
$content = str_replace('{下单时间}', $contractData['order_date'], $content);
$content = str_replace('{合同金额}', $contractData['money'], $content);
$content = str_replace('{合同开始时间}', $contractData['start_time'], $content);
$content = str_replace('{合同到期时间}', $contractData['end_time'], $content);
$content = str_replace('{客户签约人}', $contactsName, $content);
$content = str_replace('{公司签约人}', trim($signerString, '、'), $content);
$content = str_replace('{已收款金额}', $doneMoney, $content);
$content = str_replace('{未收款金额}', $contractData['money'] - $doneMoney, $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="([true|false]*?)" data-wk-tag="contract.create_user_id">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="true" data-wk-tag="contract.create_user_id">'.$contractCreate.'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="([true|false]*?)" data-wk-tag="contract.owner_user_id">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="true" data-wk-tag="contract.owner_user_id">'.$contractOwner.'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="([true|false]*?)" data-wk-tag="contract.create_time">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="true" data-wk-tag="contract.create_time">'.date('Y-m-d H:i:s', $contractData['create_time']).'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="([true|false]*?)" data-wk-tag="contract.update_time">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="true" data-wk-tag="contract.update_time">'.date('Y-m-d H:i:s', $contractData['update_time']).'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="([true|false]*?)" data-wk-tag="contract.remark">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="true" data-wk-tag="contract.remark">'.$contractData['remark'].'</span>', $content);
# 回款模板数据替换
$content = str_replace('{回款编号}', $receivablesData['number'], $content);
$contractFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_contract')->select();
foreach ($contractFields AS $key => $value) {
preg_match_all('/<span class="wk-print-tag-wukong wk-tiny-color--contract" contenteditable="([true|false]*)" data-wk-tag="contract.'.$value['field'].'">(.*)<\/span>/mU', $content, $contractHtml);
if (!empty($contractHtml[0])) {
$contractSourceData = $contractHtml[0];
switch ($value['form_type']) {
case 'user' :
$contractUsers = db('admin_user')->whereIn('id', trim($contractData[$value['field']], ','))->column('realname');
$contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractUsers), $contractHtml[0]);
break;
case 'structure' :
$contractStructure = db('admin_structure')->whereIn('id', trim($contractData[$value['field']], ','))->column('name');
$contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractStructure), $contractHtml[0]);
break;
case 'file' :
$contractFiles = db('admin_file')->whereIn('file_id', trim($contractData[$value['field']], ','))->column('name');
$contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractFiles), $contractHtml[0]);
break;
case 'datetime' :
$contractDatetime = !empty($contractData[$value['field']]) ? date('Y-m-d H:i:s', $contractData[$value['field']]) : '';
$contractTargetData = str_replace('{'.$value['name'].'}', $contractDatetime, $contractHtml[0]);
break;
default :
$contractTargetData = str_replace('{'.$value['name'].'}', trim($contractData[$value['field']], ','), $contractHtml[0]);
}
$content = str_replace($contractSourceData, $contractTargetData, $content);
}
}
# 替换回款数据
$content = str_replace('{客户名称}', $customerName, $content);
$content = str_replace('{合同编号}', $contractData['num'], $content);
$content = str_replace('{回款日期}', $receivablesData['return_time'], $content);
$content = str_replace('{回款方式}', $receivablesData['return_type'], $content);
$content = str_replace('{回款金额}', $receivablesData['money'], $content);
$content = str_replace('{期数}', '0期', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="([true|false]*?)" data-wk-tag="receivables.create_user_id">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="true" data-wk-tag="receivables.create_user_id">'.$receivablesCreate.'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="([true|false]*?)" data-wk-tag="receivables.owner_user_id">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="true" data-wk-tag="receivables.owner_user_id">'.$receivablesOwner.'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="([true|false]*?)" data-wk-tag="receivables.create_time">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="true" data-wk-tag="receivables.create_time">'.date('Y-m-d H:i:s', $receivablesData['create_time']).'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="([true|false]*?)" data-wk-tag="receivables.update_time">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="true" data-wk-tag="receivables.update_time">'.date('Y-m-d H:i:s', $receivablesData['update_time']).'</span>', $content);
$content = preg_replace('/<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="([true|false]*?)" data-wk-tag="receivables.remark">(.*?)<\/span>/si', '<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="true" data-wk-tag="receivables.remark">'.$receivablesData['remark'].'</span>', $content);
$content = str_replace('{创建人}', $receivablesCreate, $content);
$content = str_replace('{负责人}', $receivablesOwner, $content);
$content = str_replace('{创建日期}', date('Y-m-d H:i:s', $receivablesData['create_time']), $content);
$content = str_replace('{更新日期}', date('Y-m-d H:i:s', $receivablesData['update_time']), $content);
$receivablesFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_receivables')->select();
foreach ($receivablesFields AS $key => $value) {
preg_match_all('/<span class="wk-print-tag-wukong wk-tiny-color--receivables" contenteditable="([true|false]*)" data-wk-tag="receivables.'.$value['field'].'">(.*)<\/span>/mU', $content, $receivablesHtml);
if (!empty($receivablesHtml[0])) {
$receivablesSourceData = $receivablesHtml[0];
switch ($value['form_type']) {
case 'user' :
$receivablesUsers = db('admin_user')->whereIn('id', trim($receivablesData[$value['field']], ','))->column('realname');
$receivablesTargetData = str_replace('{'.$value['name'].'}', implode(',', $receivablesUsers), $receivablesHtml[0]);
break;
case 'structure' :
$receivablesStructure = db('admin_structure')->whereIn('id', trim($receivablesData[$value['field']], ','))->column('name');
$receivablesTargetData = str_replace('{'.$value['name'].'}', implode(',', $receivablesStructure), $receivablesHtml[0]);
break;
case 'file' :
$receivablesFiles = db('admin_file')->whereIn('file_id', trim($receivablesData[$value['field']], ','))->column('name');
$receivablesTargetData = str_replace('{'.$value['name'].'}', implode(',', $receivablesFiles), $receivablesHtml[0]);
break;
case 'datetime' :
$receivablesDatetime = !empty($receivablesData[$value['field']]) ? date('Y-m-d H:i:s', $receivablesData[$value['field']]) : '';
$receivablesTargetData = str_replace('{'.$value['name'].'}', $receivablesDatetime, $receivablesHtml[0]);
break;
case 'receivables_plan' :
$receivablesTargetData = str_replace('{'.$value['name'].'}', $plan, $receivablesHtml[0]);
break;
default :
$receivablesTargetData = str_replace('{'.$value['name'].'}', trim($receivablesData[$value['field']], ','), $receivablesHtml[0]);
}
$content = str_replace($receivablesSourceData, $receivablesTargetData, $content);
}
}
return $content;
}
/**
* 保存预览数据
*
* @param $param user_id 用户idtype 类型workpdfcontent 打印内容;
* @author fanqi
* @date 2021-03-25
* @return string
*/
public function preview($param)
{
$userId = $param['user_id'];
$type = $param['type'];
$content = $param['content'];
$key = md5(md5($content).$type);
$dataId = db('admin_printing_data')->where('key', $key)->value('data_id');
if (empty($dataId)) {
db('admin_printing_data')->insert([
'key' => $key,
'content' => json_encode(['data' => $content]),
'user_id' => $userId,
'type' => $type,
'create_time' => time()
]);
}
return $key;
}
/**
* 获取打印记录数据
*
* @param int $printingId 记录ID
* @author fanqi
* @since 2021-03-29
* @return array
*/
private function getHistoryData($printingId)
{
$data = db('crm_printing_record')->field(['type', 'content', 'template_id'])->where('printing_id', $printingId)->find();
$contentArray = !empty($data['content']) ? json_decode($data['content'], true) : ['data' => ''];
$result = [
'type' => (int)$data['type'],
'template_id' => (int)$data['template_id'],
'content' => $contentArray['data']
];
return $result;
}
}

@ -2,6 +2,7 @@
namespace app\crm\logic;
use app\admin\controller\ApiCommon;
use app\admin\model\Common;
use app\crm\model\Visit;
use think\Db;
@ -185,7 +186,7 @@ class VisitLogic extends Common
/**
* 回访详情
*/
public function getDataById($id = '')
public function getDataById($id = '', $userId = 0)
{
$dataInfo = db('crm_visit')->where('visit_id', $id)->find();
if (!$dataInfo) {
@ -210,6 +211,19 @@ class VisitLogic extends Common
}
$dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
$dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
// 字段授权
if (!empty($userId)) {
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) {
if (!$userLevel && !empty($grantData['crm_visit'])) {
$status = getFieldGrantStatus($key, $grantData['crm_visit']);
# 查看权限
if ($status['read'] == 0) unset($dataInfo[$key]);
}
}
}
return $dataInfo;
}
@ -236,16 +250,25 @@ class VisitLogic extends Common
if ($param['contract_id']) {
Db::name('crm_contract')->where('contract_id', $param['contract_id'])->update(['is_visit' => 1]);
}
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_visit');
foreach ($arrFieldAtt as $k => $v) {
if ($v == 'visit_user_id') continue;
$param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_visit', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
$visitModel = new Visit();
if ($visitModel->data($param)->allowField(true)->save()) {
$visit_id = $visitModel->visit_id;
updateActionLog($param['create_user_id'], 'crm_visit', $visitModel->visit_id, '', '', '创建了客户回访');
RecordActionLog($param['create_user_id'],'crm_visit','save',$param['number'],'','','新增了客户回访'.$param['number']);
$data = [];
$data['visit_id'] = $visit_id;
return $data;
@ -276,23 +299,32 @@ class VisitLogic extends Common
$fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
// $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();
return false;
}
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_visit');
foreach ($arrFieldAtt as $k => $v) {
if ($v == 'visit_user_id') continue;
$param[$v] = arrayToString($param[$v]);
if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_visit', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
if ($Visit->update($param, ['visit_id' => $visit_id], true)) {
//修改记录
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;
return $data;
@ -333,6 +365,7 @@ class VisitLogic extends Common
$delIds[] = $v;
}
}
$dataInfo = $Visit->where('visit_id',['in',$delIds])->select();
if ($delIds) {
$data = $Visit->delDatas($delIds);
if (!$data) {
@ -342,7 +375,11 @@ class VisitLogic extends Common
$fileModel->delRFileByModule('crm_visit', $delIds);
//删除关联操作记录
$actionRecordModel->delDataById(['types' => 'crm_visit', 'visit_id' => $delIds]);
actionLog($delIds, '', '', '');
$user=new ApiCommon();
$userInfo = $user->userInfo;
foreach ($dataInfo as $k => $v) {
RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['name'], '', '', '删除了客户回访:' . $v['name']);
}
}
return $errorMessage;
}
@ -363,7 +400,7 @@ class VisitLogic extends Common
# 创建人
$realname = Db::name('admin_user')->where('id', $visit['create_user_id'])->value('realname');
return [
'create_user_name' => $realname,
'create_user_id' => $realname,
'create_time' => date('Y-m-d H:i:s', $visit['create_time']),
'update_time' => date('Y-m-d H:i:s', $visit['update_time'])
];

@ -45,7 +45,7 @@ class Business extends Common
$order_type = $request['order_type'];
$is_excel = $request['is_excel']; //导出
$getCount = $request['getCount'];
$businessTypeId = $request['typeId']; // 针对mobile
$businessTypeId = $request['typesId']; // 针对mobile
$businessStatusId = $request['statusId']; // 针对mobile
unset($request['scene_id']);
unset($request['search']);
@ -55,7 +55,7 @@ class Business extends Common
unset($request['order_type']);
unset($request['is_excel']);
unset($request['getCount']);
unset($request['typeId']);
unset($request['typesId']);
unset($request['statusId']);
$request = $this->fmtRequest($request);
@ -78,11 +78,21 @@ class Business extends Common
}
if (isset($requestMap['type_id'])) {
$requestMap['type_id']['value'] = $requestMap['type_id']['type_id'];
if ($requestMap['type_id']['status_id']) $requestMap['status_id']['value'] = $requestMap['type_id']['status_id'];
if(in_array($requestMap['type_id']['status_id'],[1,2,3])){
$requestMap['is_end']=$requestMap['type_id']['status_id'];
}else{
if ($requestMap['type_id']['status_id']) $requestMap['status_id']['value'] = $requestMap['type_id']['status_id'];
$requestMap['is_end']=0;
}
}
if ($sceneMap['type_id']) {
$requestMap['type_id']['value'] = $sceneMap['type_id']['type_id'];
if ($sceneMap['type_id']['status_id']) $requestMap['status_id']['value'] = $sceneMap['type_id']['status_id'];
if(in_array($sceneMap['type_id']['status_id'],[1,2,3])){
$sceneMap['is_end']=$sceneMap['type_id']['status_id'];
}else{
if ($sceneMap['type_id']['status_id']) $requestMap['status_id']['value'] = $sceneMap['type_id']['status_id'];
$sceneMap['is_end']=0;
}
unset($sceneMap['type_id']);
}
$partMap = [];
@ -157,10 +167,17 @@ class Business extends Common
} else {
$order = 'business.update_time desc';
}
# 商机组和商机状态搜索
if (!empty($businessTypeId)) $map['business.type_id'] = ['eq', $businessTypeId];
if (!empty($businessStatusId)) $map['business.status_id'] = ['eq', $businessStatusId];
if (!empty($businessStatusId)) {
if(preg_match("/^[1-9][0-9]*$/" ,$businessStatusId)){
$map['is_end']=0;
$map['business.status_id'] = ['eq', $businessStatusId];
}else{
$map['is_end']=abs($businessStatusId);
}
}
$readAuthIds = $userModel->getUserByPer('crm', 'business', 'read');
$updateAuthIds = $userModel->getUserByPer('crm', 'business', 'update');
$deleteAuthIds = $userModel->getUserByPer('crm', 'business', 'delete');
@ -279,11 +296,18 @@ class Business extends Common
return false;
}
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_business');
foreach ($arrFieldAtt as $k => $v) {
$param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_business', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
# 设置今日需联系商机
if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
@ -292,6 +316,7 @@ class Business extends Common
$param['discount_rate'] = $param['discount_rate'] ?: '0.00';
if ($this->data($param)->allowField(true)->save()) {
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;
if ($param['product']) {
//产品数据处理
@ -356,7 +381,8 @@ class Business extends Common
$fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
@ -370,10 +396,17 @@ class Business extends Common
$param['money'] .= '.00';
}
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_business');
foreach ($arrFieldAtt as $k => $v) {
$param[$v] = arrayToString($param[$v]);
if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_business', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
# 设置今日需联系商机
@ -393,6 +426,7 @@ class Business extends Common
$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;
return $data;
@ -441,10 +475,26 @@ class Business extends Common
foreach ($datetimeField as $key => $val) {
$dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
}
if($dataInfo['is_end']!=1){
$dataInfo['statusRemark']=db('crm_business_log')->where(['business_id'=>$id,'is_end'=>$dataInfo['is_end']])->value('remark');
}
$dataInfo['next_time'] = !empty($dataInfo['next_time']) ? date('Y-m-d H:i:s', $dataInfo['next_time']) : null;
$dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
$dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
$dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
// 字段授权
if (!empty($userId)) {
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) {
if (!$userLevel && !empty($grantData['crm_business'])) {
$status = getFieldGrantStatus($key, $grantData['crm_business']);
# 查看权限
if ($status['read'] == 0) unset($dataInfo[$key]);
}
}
}
return $dataInfo;
}
@ -666,17 +716,15 @@ class Business extends Common
public function getSystemInfo($id)
{
# 商机
$business = Db::name('crm_business')->field(['create_user_id', 'create_time', 'update_time'])->where('business_id', $id)->find();
$business = Db::name('crm_business')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('business_id', $id)->find();
# 创建人
$realname = Db::name('admin_user')->where('id', $business['create_user_id'])->value('realname');
# 跟进时间
$followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 5, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
return [
'create_user_name' => $realname,
'create_user_id' => $realname,
'create_time' => date('Y-m-d H:i:s', $business['create_time']),
'update_time' => date('Y-m-d H:i:s', $business['update_time']),
'follow_time' => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : ''
'last_time' => !empty($business['last_time']) ? date('Y-m-d H:i:s', $business['last_time']) : ''
];
}

@ -6,6 +6,7 @@
// +----------------------------------------------------------------------
namespace app\crm\model;
use app\admin\controller\ApiCommon;
use think\Db;
use app\admin\model\Common;
use think\Request;
@ -118,7 +119,9 @@ class BusinessStatus extends Common
}
}
db('crm_business_status')->insertAll($statusData);
return true;
# 系统操作日志
SystemActionLog($param['create_user_id'], 'crm_business','customer', $type_id, 'save',$param['name'] , '', '','添加了商机组:'.$param['name']);
return true;
} else {
$this->error = '添加失败';
return false;
@ -194,8 +197,12 @@ class BusinessStatus extends Common
//新增
db('crm_business_status')->insertAll($statusData);
// 提交事务
Db::commit();
return true;
Db::commit();
# 系统操作日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_business','customer', $type_id, 'update',$dataInfo['name'] , '', '','编辑了商机组:'.$dataInfo['name']);
return true;
} catch (\Exception $e) {
$this->error = '编辑失败';
// 回滚事务
@ -247,7 +254,13 @@ class BusinessStatus extends Common
// db('crm_business_status')->where(['type_id' => $id])->delete();
// 提交事务
Db::commit();
return true;
# 系统操作日志
$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']);
return true;
} catch(\Exception $e) {
$this->error = '删除失败';
// 回滚事务

@ -231,13 +231,22 @@ class Contacts extends Common
$param['primary'] = 1;
}
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
foreach ($arrFieldAtt as $k=>$v) {
$param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
RecordActionLog($param['create_user_id'],'crm_contacts','save',$param['name'],'','','新增了联系人'.$param['name']);
$data = [];
$data['contacts_id'] = $this->contacts_id;
@ -311,7 +320,8 @@ class Contacts extends Common
}
$fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
@ -320,11 +330,18 @@ class Contacts extends Common
return false;
}
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
foreach ($arrFieldAtt as $k=>$v) {
$param[$v] = arrayToString($param[$v]);
if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
# 处理首要联系人
$primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
@ -340,6 +357,7 @@ class Contacts extends Common
if ($this->update($param, ['contacts_id' => $contacts_id], true)) {
//修改记录
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;
return $data;
@ -388,6 +406,19 @@ class Contacts extends Common
$dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
$dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
$dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
// 字段授权
if (!empty($userId)) {
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) {
if (!$userLevel && !empty($grantData['crm_contacts'])) {
$status = getFieldGrantStatus($key, $grantData['crm_contacts']);
# 查看权限
if ($status['read'] == 0) unset($dataInfo[$key]);
}
}
}
return $dataInfo;
}
@ -454,17 +485,15 @@ class Contacts extends Common
public function getSystemInfo($id)
{
# 联系人
$contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time'])->where('contacts_id', $id)->find();
$contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('contacts_id', $id)->find();
# 创建人
$realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname');
# 跟进时间
$followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 3, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
return [
'create_user_name' => $realname,
'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),
'update_time' => date('Y-m-d H:i:s', $contacts['update_time']),
'follow_time' => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : ''
'create_user_id' => $realname,
'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),
'update_time' => date('Y-m-d H:i:s', $contacts['update_time']),
'last_time' => !empty($contacts['last_time']) ? date('Y-m-d H:i:s', $contacts['last_time']) : ''
];
}
}

@ -380,11 +380,18 @@ class Contract extends Common
# 处理下次联系时间
if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_contract');
foreach ($arrFieldAtt as $k=>$v) {
$param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_contract', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
# 下单时间
$param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
@ -420,8 +427,8 @@ class Contract extends Common
$this->commit();
//修改记录
updateActionLog($param['create_user_id'], 'crm_contract', $this->contract_id, '', '', '创建了合同');
updateActionLog($param['create_user_id'], 'crm_contract', $this->contract_id, '', '', '创建了合同');
RecordActionLog($param['create_user_id'],'crm_contract','save',$param['name'],'','','新增了合同'.$param['name']);
# 添加活动记录
Db::name('crm_activity')->insert([
'type' => 2,
@ -476,7 +483,8 @@ 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); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
@ -492,17 +500,25 @@ class Contract extends Common
if (empty($param['start_time'])) $param['start_time'] = null;
if (empty($param['end_time'])) $param['end_time'] = null;
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_contract');
foreach ($arrFieldAtt as $k=>$v) {
$param[$v] = arrayToString($param[$v]);
if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_contract', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
if ($this->update($param, ['contract_id' => $contract_id], true)) {
//产品数据处理
$resProduct = $productModel->createObject('crm_contract', $param, $contract_id);
//修改记录
updateActionLog($param['user_id'], 'crm_contract', $contract_id, $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_contract', 'update',$dataInfo['name'], $dataInfo, $param);
//站内信
$send_user_id = stringToArray($param['check_user_id']);
if ($send_user_id && empty($param['check_status'])) {
@ -549,7 +565,7 @@ class Contract extends Common
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function getDataById($id = '')
public function getDataById($id = '', $userId = 0)
{
$receivablesModel = new \app\crm\model\Receivables();
$userModel = new \app\admin\model\User();
@ -583,6 +599,30 @@ class Contract extends Common
$dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
$dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
$dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
// 字段授权
if (!empty($userId)) {
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) {
if (!$userLevel && !empty($grantData['crm_contract'])) {
$status = getFieldGrantStatus($key, $grantData['crm_contract']);
# 查看权限
if ($status['read'] == 0) unset($dataInfo[$key]);
}
}
if (!$userLevel && !empty($grantData['crm_contract'])) {
# 客户名称
$customerStatus = getFieldGrantStatus('customer_id', $grantData['crm_contract']);
if ($customerStatus['read'] == 0) {
$dataInfo['customer_name'] = '';
$dataInfo['customer_id_info'] = [];
}
# 回款金额
$doneMoneyStatus = getFieldGrantStatus('done_money', $grantData['crm_contract']);
if ($doneMoneyStatus['read'] == 0) $dataInfo['receivablesMoney'] = '';
}
}
return $dataInfo;
}
@ -682,19 +722,17 @@ class Contract extends Common
$business = Db::name('crm_contract')->where('contract_id', $id)->find();
# 创建人
$realname = Db::name('admin_user')->where('id', $business['create_user_id'])->value('realname');
# 跟进时间
$followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 6, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
# 回款
$receivablesModel = new Receivables();
$receivables = $receivablesModel->getMoneyByContractId($id);
return [
'create_user_name' => $realname,
'create_time' => date('Y-m-d H:i:s', $business['create_time']),
'update_time' => date('Y-m-d H:i:s', $business['update_time']),
'follow_time' => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : '',
'done_money' => $receivables['doneMoney'],
'un_money' => $receivables['unMoney']
'create_user_id' => $realname,
'create_time' => date('Y-m-d H:i:s', $business['create_time']),
'update_time' => date('Y-m-d H:i:s', $business['update_time']),
'last_time' => !empty($business['last_time']) ? date('Y-m-d H:i:s', $business['last_time']) : '',
'done_money' => $receivables['doneMoney'],
'un_money' => $receivables['unMoney']
];
}

File diff suppressed because it is too large Load Diff

@ -6,6 +6,7 @@
// +----------------------------------------------------------------------
namespace app\crm\model;
use app\admin\controller\ApiCommon;
use think\Db;
use app\admin\model\Common;
use think\Request;
@ -79,13 +80,23 @@ class CustomerConfig extends Common
$this->error = '有员工或部门包含在其他的规则里!';
return false;
}
$param['types'] = !empty($param['types']) ? $param['types'] : 1; # 1拥有客户上限2锁定客户上限
$param['user_ids'] = !empty($param['user_ids']) ? arrayToString($param['user_ids']) : ''; # 处理user_id
$param['structure_ids'] = !empty($param['structure_ids']) ? arrayToString($param['structure_ids']) : ''; # 处理structure_id
if ($this->allowField(true)->isUpdate(empty($id) ? false : true)->save($param, !empty($id) ? ['id' => $id] : [])) {
$data['id'] = $this->id;
return $data;
# 系统操作日志
if(!empty($param['id'])){
$content='编辑员工拥有、锁定客户限制';
$action='update';
}else{
$content='添加员工拥有、锁定客户限制';
$action='update';
}
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_customer','customer', $this->id, $action,$content , '', '',$content);
return $data;
} else {
$this->error = '创建失败';
return false;
@ -139,54 +150,108 @@ class CustomerConfig extends Common
}
/**
* 验证相关信息
* 验证是否可以持有或锁定客户
*
* @param $user_id
* @param $types
* @param string $is_update
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @param int $userId 用户id
* @param int $types 类型类型1 拥有客户数2 锁定客户数
* @param int $isUpdate 是否是更新
* @param int $addCount 多公海分配或领取使用的参数,代表要领取或分配的客户数量
* @return bool|int|mixed
*/
public function checkData($user_id, $types, $is_update = '')
{
$userModel = new \app\admin\model\User();
$customerModel = new \app\crm\model\Customer();
$userInfo = $userModel->getUserById($user_id);
$dataInfo = $this->where(['types' => $types,'user_ids' => ['like','%,'.$user_id.',%']])->order('update_time desc')->find();
if (!$dataInfo) {
$dataInfo = $this->where(['types' => $types,'structure_ids' => ['like','%,'.$userInfo['structure_id'].',%']])->find();
}
switch ($types) {
case '1' : $types_title = '拥有的客户数量'; break;
case '2' : $types_title = '锁定的客户数量'; break;
}
if ($dataInfo) {
$is_deal = $dataInfo['is_deal'] ? : 0;
if (!$dataInfo['value']) {
$this->error = $types_title.'超出限制:'.$dataInfo['value'].'个';
return false;
}
//拥有数、锁定数
$count = $customerModel->getCountByHave($user_id,$is_deal,$types);
$error = false;
if ($count >= $dataInfo['value']) {
$error = true;
}
if ($is_update == 1 && $types == 1 && $dataInfo['is_deal'] == 1) {
//更改成交状态
if ($count = $dataInfo['value']) {
$error = false;
}
}
if ($error == true) {
$this->error = $userInfo['realname'].','.$types_title.'超出限制:'.$dataInfo['value'].'个';
return false;
}
}
return true;
}
public function checkData($userId, $types, $isUpdate = 0, $addCount = 0)
{
# 用户信息
$userinfo = db('admin_user')->field(['realname', 'structure_id'])->where('id', $userId)->find();
$username = $userinfo['realname'];
$structureId = $userinfo['structure_id'];
# 查询客户配置(拥有,锁定),以用户配置优先
$customerConfig = db('crm_customer_config')->field(['value', 'is_deal'])->where(['types' => $types, 'user_ids' => ['like', '%,' . $userId . ',%']])->find();
if (!$customerConfig) $customerConfig = db('crm_customer_config')->field(['value', 'is_deal'])->where(['types' => $types, 'structure_ids' => ['like', '%,' . $structureId . ',%']])->find();
# 提示标题
$title = '';
if ($types == 1) $title = '拥有的客户数量';
if ($types == 2) $title = '锁定的客户数量';
if ($customerConfig) {
if (empty($customerConfig['value'])) {
$this->error = $title . '超出限制,最大:' . $customerConfig['value'] . ' 个';
return false;
}
# 成交用户是否暂用数量
$isDeal = !empty($customerConfig['is_deal']) ? 1 : 0;
# 获取目前拥有或锁定的客户数量
$customerModel = new Customer();
$count = $customerModel->getCountByHave($userId, $isDeal, $types);
$error = false;
if (empty($addCount)) {
# 多公海以外的地方调用
if ($count >= $customerConfig['value']) {
$error = true;
}
if ($isUpdate == 1 && $types == 1 && $customerConfig['is_deal'] == 1) {
//更改成交状态
if ($count = $customerConfig['value']) {
$error = false;
}
}
if ($error == true) {
$this->error = $username.','.$title.'超出限制:'.$customerConfig['value'].'个';
return false;
}
} else {
# 多公海中的领取、分配调用,返回超出的个数
if ($count + $addCount > $customerConfig['value']) {
return ($count + $addCount) - $customerConfig['value'];
}
}
}
return true;
}
// public function checkData($user_id, $types, $is_update = '')
// {
// $userModel = new \app\admin\model\User();
// $customerModel = new \app\crm\model\Customer();
// $userInfo = $userModel->getUserById($user_id);
// $dataInfo = $this->where(['types' => $types,'user_ids' => ['like','%,'.$user_id.',%']])->order('update_time desc')->find();
// if (!$dataInfo) {
// $dataInfo = $this->where(['types' => $types,'structure_ids' => ['like','%,'.$userInfo['structure_id'].',%']])->find();
// }
// switch ($types) {
// case '1' : $types_title = '拥有的客户数量'; break;
// case '2' : $types_title = '锁定的客户数量'; break;
// }
// if ($dataInfo) {
// $is_deal = $dataInfo['is_deal'] ? : 0;
// if (!$dataInfo['value']) {
// $this->error = $types_title.'超出限制:'.$dataInfo['value'].'个';
// return false;
// }
// //拥有数、锁定数
// $count = $customerModel->getCountByHave($user_id,$is_deal,$types);
// $error = false;
// if ($count >= $dataInfo['value']) {
// $error = true;
// }
// if ($is_update == 1 && $types == 1 && $dataInfo['is_deal'] == 1) {
// //更改成交状态
// if ($count = $dataInfo['value']) {
// $error = false;
// }
// }
// if ($error == true) {
// $this->error = $userInfo['realname'].','.$types_title.'超出限制:'.$dataInfo['value'].'个';
// return false;
// }
// }
// return true;
// }
/**
* 验证拥有/锁定客户数中的员工或部门是否重复添加

@ -212,11 +212,18 @@ class Leads extends Common
return false;
}
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_leads');
foreach ($arrFieldAtt as $k => $v) {
$param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_leads', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
# 设置今日需联系线索
if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
@ -224,6 +231,7 @@ class Leads extends Common
if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
//修改记录
updateActionLog($param['create_user_id'], 'crm_leads', $this->leads_id, '', '', '创建了线索');
RecordActionLog($param['create_user_id'],'crm_leads','save',$param['name'],'','','新增了线索'.$param['name']);
# 添加活动记录
Db::name('crm_activity')->insert([
'type' => 2,
@ -276,7 +284,8 @@ class Leads extends Common
$fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
// $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) {
@ -284,10 +293,17 @@ class Leads extends Common
return false;
}
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_leads');
foreach ($arrFieldAtt as $k => $v) {
$param[$v] = arrayToString($param[$v]);
if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_leads', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
# 设置今日需联系线索
@ -296,6 +312,7 @@ class Leads extends Common
if ($this->update($param, ['leads_id' => $leads_id], true)) {
//修改记录
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;
return $data;
@ -339,6 +356,19 @@ class Leads extends Common
$dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
$dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
$dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
// 字段授权
if (!empty($userId)) {
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) {
if (!$userLevel && !empty($grantData['crm_leads'])) {
$status = getFieldGrantStatus($key, $grantData['crm_leads']);
# 查看权限
if ($status['read'] == 0) unset($dataInfo[$key]);
}
}
}
return $dataInfo;
}
@ -355,17 +385,15 @@ class Leads extends Common
function getSystemInfo($id)
{
# 线索
$leads = Db::name('crm_leads')->field(['create_user_id', 'create_time', 'update_time'])->where('leads_id', $id)->find();
$leads = Db::name('crm_leads')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('leads_id', $id)->find();
# 创建人
$realname = Db::name('admin_user')->where('id', $leads['create_user_id'])->value('realname');
# 最后跟进时间
$followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 1, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
return [
'create_user_name' => $realname,
'create_user_id' => $realname,
'create_time' => date('Y-m-d H:i:s', $leads['create_time']),
'update_time' => date('Y-m-d H:i:s', $leads['update_time']),
'follow_time' => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : ''
'last_time' => !empty($leads['last_time']) ? date('Y-m-d H:i:s', $leads['last_time']) : ''
];
}
}

@ -0,0 +1,14 @@
<?php
namespace app\crm\model;
use app\crm\controller\Common;
class Market extends Common {
/**
* 为了数据库的整洁同时又不影响Model和Controller的名称
* 我们约定每个模块的数据表都加上相同的前缀比如CRM模块用crm作为数据表前缀
*/
protected $name = 'crm_market';
protected $createTime = 'create_time';
protected $updateTime = 'update_time';
}

File diff suppressed because it is too large Load Diff

@ -6,6 +6,7 @@
// +----------------------------------------------------------------------
namespace app\crm\model;
use app\admin\controller\ApiCommon;
use think\Db;
use app\admin\model\Common;
use think\Request;
@ -60,7 +61,11 @@ class ProductCategory extends Common
if ($this->data($param)->allowField(true)->save()) {
$data = [];
$data['id'] = $this->category_id;
return $data;
# 系统操作日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_product','customer', $this->category_id, 'save',$param['name'] , '', '','添加了产品分类:'.$param['name']);
return $data;
} else {
$this->error = '添加失败';
return false;
@ -90,7 +95,11 @@ class ProductCategory extends Common
}
if ($this->allowField(true)->save($param, ['category_id' => $category_id])) {
return true;
# 系统操作日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_product','customer', $category_id, 'update',$dataInfo['name'] , '', '','编辑了产品分类:'.$dataInfo['name']);
return true;
} else {
$this->error = '编辑失败';
return false;
@ -126,6 +135,7 @@ class ProductCategory extends Common
$this->error = '请先移除该类型及子类下的相关产品';
return false;
}
$data=db('crm_product_category')->where('category_id' , $id)->find();
//提交事务
$this->startTrans();
try {
@ -137,8 +147,12 @@ class ProductCategory extends Common
$this->where('category_id', 'in', $childIds)->delete();
}
}
$this->commit();
return true;
# 系统操作日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_product','customer', $id, 'update',$data['name'] , '', '','删除了产品分类:'.$data['name']);
$this->commit();
return true;
} catch(\Exception $e) {
$this->error = '删除失败';
$this->rollback();

@ -269,11 +269,19 @@ class Receivables extends Common
return false;
}
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_receivables');
foreach ($arrFieldAtt as $k=>$v) {
$param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
if ($this->data($param)->allowField(true)->save()) {
//站内信
$send_user_id = stringToArray($param['check_user_id']);
@ -291,7 +299,8 @@ class Receivables extends Common
$data['receivables_id'] = $this->receivables_id;
//修改记录
updateActionLog($param['create_user_id'], 'crm_receivables', $this->receivables_id, '', '', '创建了回款');
updateActionLog($param['create_user_id'], 'crm_receivables', $this->receivables_id, '', '', '创建了回款');
RecordActionLog($param['create_user_id'],'crm_receivables','save',$param['number'],'','','新增了回款'.$param['number']);
# 添加活动记录
Db::name('crm_activity')->insert([
@ -375,7 +384,8 @@ class Receivables extends Common
$fieldModel = new \app\admin\model\Field();
// 自动验证
$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
// $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
$validate = new Validate($validateArr['rule'], $validateArr['message']);
$result = $validate->check($param);
@ -384,15 +394,23 @@ class Receivables extends Common
return false;
}
//处理部门、员工、附件、多选类型字段
// 处理部门、员工、附件、多选类型字段
$arrFieldAtt = $fieldModel->getArrayField('crm_receivables');
foreach ($arrFieldAtt as $k=>$v) {
$param[$v] = arrayToString($param[$v]);
if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
}
// 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date');
if (!empty($dateField)) {
foreach ($param AS $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
}
}
if ($this->update($param, ['receivables_id' => $receivables_id], true)) {
//修改记录
updateActionLog($param['user_id'], 'crm_receivables', $receivables_id, $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_receivables', 'update',$dataInfo['number'], $dataInfo, $param);
//站内信
$send_user_id = stringToArray($param['check_user_id']);
if ($send_user_id && empty($param['check_status'])) {
@ -440,7 +458,7 @@ class Receivables extends Common
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function getDataById($id = '')
public function getDataById($id = '', $userId = 0)
{
$map['receivables_id'] = $id;
$dataInfo = db('crm_receivables')->where($map)->find();
@ -464,6 +482,33 @@ class Receivables extends Common
}
$dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
$dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
// 字段授权
if (!empty($userId)) {
$grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) {
if (!$userLevel && !empty($grantData['crm_receivables'])) {
$status = getFieldGrantStatus($key, $grantData['crm_receivables']);
# 查看权限
if ($status['read'] == 0) unset($dataInfo[$key]);
}
}
if (!$userLevel && !empty($grantData['crm_receivables'])) {
# 客户名称
$customerStatus = getFieldGrantStatus('customer_id', $grantData['crm_receivables']);
if ($customerStatus['read'] == 0) {
$dataInfo['customer_name'] = '';
$dataInfo['customer_id_info'] = [];
}
# 合同金额
$contractMoneyStatus = getFieldGrantStatus('contract_money', $grantData['crm_receivables']);
if ($contractMoneyStatus['read'] == 0) $dataInfo['contract_id_info']['money'] = '';
# 合同名称
$contractMoneyStatus = getFieldGrantStatus('contract_money', $grantData['crm_receivables']);
if ($contractMoneyStatus['read'] == 0) $dataInfo['contract_id_info']['money'] = '';
}
}
return $dataInfo;
}
@ -651,7 +696,7 @@ class Receivables extends Common
$contractMoney = db('crm_contract')->where(['contract_id' => $contract_id])->value('money');
$unMoney = $contractMoney-$doneMoney;
$data['doneMoney'] = $doneMoney ? : '0.00';
$data['unMoney'] = $unMoney ? : '0.00';
$data['unMoney'] = (int)$unMoney>0 ? (int)$unMoney : '0.00';
$data['contractMoney'] = $contractMoney ? : '0.00';
return $data;
}
@ -673,9 +718,9 @@ class Receivables extends Common
$realname = Db::name('admin_user')->where('id', $receivables['create_user_id'])->value('realname');
return [
'create_user_name' => $realname,
'create_time' => date('Y-m-d H:i:s', $receivables['create_time']),
'update_time' => date('Y-m-d H:i:s', $receivables['update_time'])
'create_user_id' => $realname,
'create_time' => date('Y-m-d H:i:s', $receivables['create_time']),
'update_time' => date('Y-m-d H:i:s', $receivables['update_time'])
];
}
}

@ -98,7 +98,10 @@ class Setting extends Common
]);
}
}
# 系统操作日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_config','customer', 1, 'update','客户回访提醒' , '', '','设置了客户回访提醒');
return true;
}
@ -172,7 +175,10 @@ class Setting extends Common
}
Db::commit();
# 系统操作日志
$user=new ApiCommon();
$userInfo=$user->userInfo;
SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1, 'update','编号规则设置' , '', '','设置了编号规则');
return true;
} catch (Exception $e) {
Db::rollback();

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<embed name="{$key}" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" src="about:blank" type="application/pdf" internalid="{$key}">
</body>
</html>

@ -275,6 +275,7 @@ class Event extends ApiCommon
{
$eventModel = model('Event');
$param = $this->param;
$userInfo=$this->userInfo;
if (!$param['event_id']) {
return resultArray(['error' => '参数错误']);
}
@ -289,6 +290,9 @@ class Event extends ApiCommon
if (!$ret) {
return resultArray(['error' => $eventModel->getError()]);
}
RecordActionLog($userInfo['id'], 'oa_event', 'delete', $flag['title'], '', '', '删除了日程:' . $flag['title']);
return resultArray(['data' => '删除成功']);
}
}

@ -27,7 +27,7 @@ class Examine extends ApiCommon
{
$action = [
'permission'=>[''],
'allow'=>['index','save','read','update','delete','categorylist','check','revokecheck','category','categorysave','categoryupdate','categorydelete','categoryenables','excelexport','myexamine']
'allow'=>['index','save','read','update','delete','categorylist','check','revokecheck','category','categorysave','categoryupdate','categorydelete','categoryenables','excelexport','myexamine','examinesort']
];
Hook::listen('check_auth',$action);
$request = Request::instance();
@ -37,7 +37,7 @@ class Examine extends ApiCommon
}
//权限判断
// $unAction = ['index','save','read','update','delete','categorylist','check','revokecheck','excelexport',];
$unAction = ['index','save','read','update','delete','categorylist','check','revokecheck','category','categorysave','categoryupdate','categorydelete','categoryenables','excelexport','myexamine'];
$unAction = ['index','save','read','update','delete','categorylist','check','revokecheck','category','categorysave','categoryupdate','categorydelete','categoryenables','excelexport','myexamine','examinesort'];
if (!in_array($a, $unAction) && !checkPerByAction('admin', 'oa', 'examine')) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode(['code'=>102,'error'=>'无权操作']));
@ -287,6 +287,10 @@ class Examine extends ApiCommon
$res = $categoryModel->createData($param);
if ($res) {
#添加系统操作日志
$userInfo=$this->userInfo;
SystemActionLog($userInfo['id'], 'admin_examine','approval', $res['category_id'], 'save', $param['title'], '', '','添加了办公审批流:'.$param['title']);
return resultArray(['data' => $res]);
} else {
return resultArray(['error' => $categoryModel->getError()]);
@ -322,7 +326,7 @@ class Examine extends ApiCommon
$param['structure_ids'] = arrayToString($param['structure_ids']);
$param['update_user_id'] = $userInfo['id'];
$param['create_time'] = time();
$param['update_time'] = time();
// $param['update_time'] = time();
$param['status'] = 1;
$resUpdate = $examineFlowModel->createData($param);
@ -350,6 +354,10 @@ class Examine extends ApiCommon
if (!$res) {
return resultArray(['error' => $categoryModel->getError()]);
}
# 系统操作记录
$userInfo=$this->userInfo;
SystemActionLog($userInfo['id'], 'oa_examine','approval', $category_id, 'save', '办公审批' , '', '编辑了办公审批流:办公审批');
return resultArray(['data' => '编辑成功']);
} else {
return resultArray(['error' => $examineFlowModel->getError()]);
@ -391,6 +399,14 @@ class Examine extends ApiCommon
if (!$data) {
return resultArray(['error' => $categoryModel->getError()]);
}
$info=db('oa_examine_category')->where('category_id',$param['id'])->find();
# 系统操作记录
if($param['status']==0){
$content='停用了:'.$info['title'];
}else{
$content='启用了:'.$info['title'];
}
SystemActionLog($userInfo['id'], 'oa_examine','approval', $param['id'], 'delete',$info['title'] , '', '',$content);
return resultArray(['data' => '操作成功']);
}
@ -404,17 +420,31 @@ class Examine extends ApiCommon
$param = $this->param;
$userInfo = $this->userInfo;
$where = [];
$where['is_deleted'] = ['neq',1];
$where['status'] = ['eq',1];
$where['c.is_deleted'] = ['neq',1];
$where['c.status'] = ['eq',1];
$examineCategory=db('oa_examine_order')->where('user_id',$userInfo['id'])->column('work_id');
$category_id=db('oa_examine_category')->where(['create_user_id'=>$userInfo['id'],'is_deleted'=>['neq',1],'status'=>1])->column('category_id');
if($examineCategory && count($examineCategory)==count($category_id)){
$orderField = 'o.order';
$orderSort = 'asc';
$join=[['__OA_EXAMINE_ORDER__ o','o.work_id=c.category_id','LEFT']];
$where['o.user_id'] = ['eq',$userInfo['id']];
}else{
$orderField = 'c.category_id';
$orderSort = 'asc';
$join='';
}
$list = db('oa_examine_category')
->alias('c')
->join($join)
->where($where)
->where(function ($query) use ($userInfo){
$query->where('`user_ids` = "" AND `structure_ids` = ""')
$query->where('c.`user_ids` = "" AND c.`structure_ids` = ""')
->whereOr(function($query) use ($userInfo){
$query->where('structure_ids','like','%,'.$userInfo['structure_id'].',%')
->whereOr('user_ids','like','%,'.$userInfo['id'].',%');
$query->where('c.structure_ids','like','%,'.$userInfo['structure_id'].',%')
->whereOr('c.user_ids','like','%,'.$userInfo['id'].',%');
});
})->select();
})->order($orderField,$orderSort)->select();
return resultArray(['data' => $list]);
}
@ -615,4 +645,20 @@ class Examine extends ApiCommon
$data = $ExamineLogic->myExamine($param);
return resultArray(['data' => $data]);
}
/**
* 办公审批类型排序
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/16 0016 14:02
*/
public function examineSort(){
$examineIds = $this->param['examineIds'];
$userInfo = $this->userInfo;
$examineCategory=new ExamineLogic();
$examineCategory->setWorkOrder($examineIds, $userInfo['id']);
return resultArray(['data' => '操作成功!']);
}
}

@ -61,7 +61,7 @@ class Log extends ApiCommon
}
}
/**
/**commentSave
* 日志列表
* @return
* @author Michael_xu
@ -293,6 +293,15 @@ class Log extends ApiCommon
$log_id = $param['log_id'];
$param['user_id']=$userInfo['id'];
$logModel = model('Log');
if(!empty($param['is_relation'])){
$indexLogic = new LogLogic();
$save = $indexLogic->oneBulletin($param);
$param['save_customer'] = $save['data']['customerNum'];
$param['save_business'] = $save['data']['businessNum'];
$param['save_contract'] = $save['data']['contractNum'];
$param['save_receivables'] = $save['data']['receivablesMoneyNum'];
$param['save_activity'] = $save['data']['recordNum'];
}
if ($log_id) {
$dataInfo = db('oa_log')->where(['log_id' => $log_id])->find();
//权限判断

@ -132,9 +132,11 @@ class Task extends ApiCommon
}
//状态
$status = $param['status'] ?: '';
if ($status) {
if ($status==1) {
$where['t.status'] = $status;
} else {
} elseif($status==6) {
$where['t.status'] = 5;
}else{
$where['t.status'] = [['=', 1], ['=', 5], 'OR'];
}
if ($param['main_user_id']) {

@ -469,4 +469,31 @@ class ExamineLogic extends Common
return $data;
}
/**
* @param $workIds
* @param $userId
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/4/16 0016 14:00
*/
public function setWorkOrder($examineIds, $userId)
{
$data = [];
foreach ($examineIds AS $key => $value) {
$data[] = [
'work_id' => $value,
'user_id' => $userId,
'order' => $key + 1
];
}
if (!empty($data)) {
if (db('oa_examine_order')->where('user_id', $userId)->delete() === false) return false;
if (db('oa_examine_order')->insertAll($data) === false) return false;
}
return true;
}
}

@ -56,9 +56,6 @@ class LogLogic extends Common
if ($request['category_id']) {
$map['log.category_id'] = $request['category_id'];
}
if ($request['create_user_id']) {
$map['log.create_user_id'] = $request['create_user_id'];
}
if ($request['type']) {
$timeAry = ByDateTime($request['type']);
$between_time = [$timeAry[0], $timeAry[1]];
@ -77,8 +74,8 @@ class LogLogic extends Common
$dataWhere['structure_id'] = $request['structure_id'];
$dataWhere['auth_user_ids'] = $auth_user_ids;
$logMap = '';
if ($request['send_user_id'] != '') {
$map['log.create_user_id'] = ['in', trim(arrayToString($request['send_user_id']), ',')];
if ($request['create_user_id'] != '') {
$map['log.create_user_id'] = ['in', trim(arrayToString($request['create_user_id']), ',')];
}
switch ($by) {
case 'me' :
@ -242,17 +239,22 @@ class LogLogic extends Common
$between_time = [$start_time['start_time'], $start_time['end_time']];
$map['owner_user_id'] = $user_id;
$map['create_time'] = array('between', $between_time);
$map1['update_time'] = array('between', $between_time);
$logMap=function ($query) use ($between_time) {
$query->where('create_time', array('between', $between_time))
->whereOr('obtain_time', array('between', $between_time));
};
$customerNum = Db::name('CrmCustomer')
->where($map1)
->where($logMap)
->count();
$businessNum = Db::name('CrmBusiness')
->where($map)
->count();
$contractNum = Db::name('CrmContract')
->where('check_status',2)
->where($map)
->count();
$receivablesMoneyNum = Db::name('CrmReceivables')
->where('check_status',2)
->where($map)
->sum('money');
unset($map['owner_user_id']);
@ -308,17 +310,22 @@ class LogLogic extends Common
switch ($type) {
case '1':
if ($search) $map['customer.name'] = array('like', '%' . $search . '%');
$map['customer.update_time'] = array('between', $between_time);
$map['customer.create_time'] = array('between', $between_time);
$logMap['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)
->order('customer.customer_id desc')
->field('customer.customer_id,customer.name,customer.deal_status,customer.create_time,user.realname as owner_user_name,customer.last_time')
->field('customer.customer_id,customer.level,customer.name,customer.deal_status,customer.create_time,user.realname as owner_user_name,customer.last_time,customer.next_time')
->page($param['page'],$param['limit'])
->select();
foreach ($activityData as $k => $v){
$activityData[$k]['last_time']=!empty($v['last_time'])?date('Y-m-d H:i:s',$v['last_time']):!empty($v['next_time'])?date('Y-m-d H:i:s',$v['next_time']):null;
}
$dataCount = Db::name('CrmCustomer')
->alias('customer')
->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
@ -338,8 +345,24 @@ class LogLogic extends Common
->where($map2)
->order('business.business_id desc')
->page($param['page'],$param['limit'])
->field('business.business_id,business.name,status.name as status_name,business.create_time,user.realname as owner_user_name,business.last_time')
->field('business.business_id,business.money,business.status_id,business.type_id,business.name,status.name as status_name,business.create_time,user.realname as owner_user_name,business.last_time,business.deal_date')
->select();
$endStatus = ['1' => '赢单', '2' => '输单', '3' => '无效'];
foreach ($activityData as $k=>$v){
$statusInfo = [];
$status_count = 0;
if (!$v['is_end']) {
$statusInfo = db('crm_business_status')->where('status_id', $v['status_id'])->find();
if ($statusInfo['order_id'] < 99) {
$status_count = db('crm_business_status')->where('type_id', ['eq', $v['type_id']])->count();
}
//进度
$activityData[$k]['status_progress'] = [$statusInfo['order_id'], $status_count + 1];
} else {
$statusInfo['name'] = $endStatus[$v['is_end']];
}
$activityData[$k]['status_id_info'] = $statusInfo['name'];//销售阶段
}
$dataCount = Db::name('CrmBusiness')
->alias('business')
->join('__CRM_BUSINESS_STATUS__ status', 'status.status_id=business.status_id')
@ -351,15 +374,32 @@ class LogLogic extends Common
case '3':
$map['contract.name'] = array('like', '%' . $search . '%');
$map['contract.create_time'] = array('between', $between_time);
$map['contract.check_status'] = 2;
$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,contract.name,contract.create_time,contract.check_status,u.realname as order_user_name')
->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'])){
$activityData[$k]['order_date'] = ($v['order_date']!='0000-00-00') ? $v['order_date'] : null;
}else{
$activityData=[];
}
}
$dataCount = Db::name('CrmContract')
->alias('contract')
->join('__ADMIN_USER__ u', 'u.id = contract.owner_user_id', 'LEFT')
@ -370,10 +410,11 @@ class LogLogic extends Common
case '4':
$map['receivables.number'] = array('like', '%' . $search . '%');
$map['receivables.create_time'] = array('between', $between_time);
$map['receivables.check_status'] = 2;
$activityData = Db::name('CrmReceivables')
->alias('receivables')
->join('__ADMIN_USER__ user', 'user.id = receivables.owner_user_id', 'LEFT')
->field('receivables.receivables_id,receivables.number,receivables.return_time,user.realname as owner_user_name')
->field('receivables.receivables_id,receivables.number,receivables.return_time,receivables.money,user.realname as owner_user_name')
->where($map)
->where($map4)
->page($param['page'],$param['limit'])
@ -690,7 +731,7 @@ class LogLogic extends Common
}
/**
*
* 跟进记录列表
* @param $param
* @return array
* @throws \think\Exception
@ -966,6 +1007,10 @@ class LogLogic extends Common
} else {
$item['bulletin'] = 0;
}
# 发送人信息
$sendUserList = !empty($item['send_user_ids']) ? db('admin_user')->field(['id', 'realname'])->whereIn('id', stringToArray($item['send_user_ids']))->select() : [];
$item['sendUserList'] = $sendUserList;
$data = [];
$data['list'] = $item;
return $data;

@ -28,9 +28,11 @@ class TaskLogic
}
//状态
$status = $param['status'] ?: '';
if ($status) {
if ($status==1) {
$where['t.status'] = $status;
} else {
} elseif($status==6) {
$where['t.status'] = 5;
}else{
$where['t.status'] = [['=', 1], ['=', 5], 'OR'];
}
@ -264,7 +266,6 @@ class TaskLogic
public function excelExport($param)
{
$data = $this->getDataList($param);
p($data);
$excelModel = new \app\admin\model\Excel();
if ($param['work_id'] != 0) {
$file_name = 'work_task';

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

Loading…
Cancel
Save