Michael_xu před 5 roky
rodič
revize
5782b6c665
100 změnil soubory, kde provedl 9533 přidání a 2761 odebrání
  1. 5
    5
      README.md
  2. 25
    0
      application/admin/common.php
  3. 1
    3
      application/admin/controller/ApiCommon.php
  4. 45
    1
      application/admin/controller/Base.php
  5. 2
    0
      application/admin/controller/ConfigSet.php
  6. 16
    5
      application/admin/controller/DailyRule.php
  7. 22
    5
      application/admin/controller/ExamineFlow.php
  8. 70
    32
      application/admin/controller/Field.php
  9. 8
    2
      application/admin/controller/Groups.php
  10. 8
    0
      application/admin/controller/Index.php
  11. 5
    1
      application/admin/controller/Initialize.php
  12. 26
    6
      application/admin/controller/Install.php
  13. 78
    1
      application/admin/controller/Log.php
  14. 1
    0
      application/admin/controller/Market.php
  15. 4
    7
      application/admin/controller/Printing.php
  16. 137
    1
      application/admin/controller/Setting.php
  17. 19
    8
      application/admin/controller/Structures.php
  18. 12
    5
      application/admin/controller/System.php
  19. 122
    0
      application/admin/controller/UpdateSql.php
  20. 273
    199
      application/admin/controller/Users.php
  21. 8
    5
      application/admin/controller/Work.php
  22. 8
    8
      application/admin/logic/DailyRuleLogic.php
  23. 269
    165
      application/admin/logic/FieldGrantLogic.php
  24. 44
    10
      application/admin/logic/InitializeLogic.php
  25. 274
    50
      application/admin/logic/LogLogic.php
  26. 1
    0
      application/admin/logic/MarketLogic.php
  27. 1
    1
      application/admin/logic/MessageLogic.php
  28. 481
    0
      application/admin/logic/PoolConfigLogic.php
  29. 63
    42
      application/admin/logic/PrintingLogic.php
  30. 21
    6
      application/admin/logic/WorkLogic.php
  31. 10
    0
      application/admin/model/Config.php
  32. 2
    1
      application/admin/model/ExamineFlow.php
  33. 27
    20
      application/admin/model/ExamineRecord.php
  34. 17
    16
      application/admin/model/ExamineStep.php
  35. 607
    61
      application/admin/model/Excel.php
  36. 264
    220
      application/admin/model/Field.php
  37. 13
    3
      application/admin/model/Group.php
  38. 10
    3
      application/admin/model/LoginRecord.php
  39. 1
    0
      application/admin/model/Market.php
  40. 7
    0
      application/admin/model/Message.php
  41. 7
    3
      application/admin/model/Scene.php
  42. 12
    2
      application/admin/model/Structure.php
  43. 167
    52
      application/admin/model/User.php
  44. 30
    6
      application/admin/model/UserField.php
  45. 101
    88
      application/bi/controller/Customer.php
  46. 2
    2
      application/bi/controller/Examine.php
  47. 18
    45
      application/bi/controller/Product.php
  48. 1
    1
      application/bi/controller/Ranking.php
  49. 3
    6
      application/bi/logic/ExcelLogic.php
  50. 1
    0
      application/command.php
  51. 267
    117
      application/common.php
  52. 411
    0
      application/common/command/PoolCommand.php
  53. 8
    3
      application/crm/controller/Achievement.php
  54. 236
    3
      application/crm/controller/Activity.php
  55. 172
    163
      application/crm/controller/Business.php
  56. 9
    0
      application/crm/controller/BusinessStatus.php
  57. 44
    6
      application/crm/controller/Contacts.php
  58. 12
    3
      application/crm/controller/Contract.php
  59. 219
    37
      application/crm/controller/Customer.php
  60. 364
    0
      application/crm/controller/CustomerPool.php
  61. 3
    0
      application/crm/controller/Index.php
  62. 22
    11
      application/crm/controller/Invoice.php
  63. 41
    3
      application/crm/controller/Leads.php
  64. 150
    0
      application/crm/controller/Market.php
  65. 32
    34
      application/crm/controller/Message.php
  66. 67
    0
      application/crm/controller/Preview.php
  67. 111
    11
      application/crm/controller/Printing.php
  68. 62
    10
      application/crm/controller/Product.php
  69. 1
    1
      application/crm/controller/ProductCategory.php
  70. 12
    2
      application/crm/controller/Receivables.php
  71. 29
    47
      application/crm/controller/Setting.php
  72. 1
    2
      application/crm/controller/Visit.php
  73. 115
    71
      application/crm/logic/ActivityLogic.php
  74. 2
    0
      application/crm/logic/CommonLogic.php
  75. 1084
    0
      application/crm/logic/CustomerPoolLogic.php
  76. 74
    67
      application/crm/logic/IndexLogic.php
  77. 2
    2
      application/crm/logic/InvoiceLogic.php
  78. 243
    0
      application/crm/logic/MarketLogic.php
  79. 457
    163
      application/crm/logic/PrintingLogic.php
  80. 44
    7
      application/crm/logic/VisitLogic.php
  81. 63
    15
      application/crm/model/Business.php
  82. 17
    4
      application/crm/model/BusinessStatus.php
  83. 41
    12
      application/crm/model/Contacts.php
  84. 53
    15
      application/crm/model/Contract.php
  85. 736
    386
      application/crm/model/Customer.php
  86. 113
    48
      application/crm/model/CustomerConfig.php
  87. 37
    9
      application/crm/model/Leads.php
  88. 14
    0
      application/crm/model/Market.php
  89. 567
    371
      application/crm/model/Product.php
  90. 18
    4
      application/crm/model/ProductCategory.php
  91. 55
    10
      application/crm/model/Receivables.php
  92. 8
    2
      application/crm/model/Setting.php
  93. 10
    0
      application/crm/view/preview/preview.html
  94. 4
    0
      application/oa/controller/Event.php
  95. 55
    9
      application/oa/controller/Examine.php
  96. 10
    1
      application/oa/controller/Log.php
  97. 4
    2
      application/oa/controller/Task.php
  98. 27
    0
      application/oa/logic/ExamineLogic.php
  99. 58
    13
      application/oa/logic/LogLogic.php
  100. 0
    0
      application/oa/logic/TaskLogic.php

+ 5
- 5
README.md Zobrazit soubor

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

+ 25
- 0
application/admin/common.php Zobrazit soubor

@@ -203,4 +203,29 @@ function formatPubKey($pubKey) {
203 203
     }
204 204
     $fKey .= "-----END PUBLIC KEY-----";
205 205
     return $fKey;
206
+}
207
+
208
+/**
209
+ * foreach循环内查询数据
210
+ * @param string $types
211
+ * @param $data
212
+ *
213
+ * @author      alvin guogaobo
214
+ * @version     1.0 版本号
215
+ * @since       2021/4/15 0015 14:39
216
+ */
217
+function foreachData($types='',$data)
218
+{
219
+    switch ($types) {
220
+        case 'admin_structure' :
221
+            $res=Db::name('AdminUser')->where('id',$data)->value('realname');
222
+            break;
223
+        case '' :
224
+            $res=Db::name('AdminUser')->where('id',$data['id'])->update(['structure_id'=>$data['structure_id']]);
225
+            break;
226
+        case 'market':
227
+            $res=Db::name('MarketData')->whereIn('id',$data)->select();
228
+            break;
229
+    }
230
+    return $res;
206 231
 }

+ 1
- 3
application/admin/controller/ApiCommon.php Zobrazit soubor

@@ -29,7 +29,7 @@ class ApiCommon extends Common
29 29
         $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
30 30
         $cache = Cache::get('Auth_'.$authKey.$platform);
31 31
 //        $cache = cache('Auth_'.$authKey.$platform);
32
-
32
+//        dump($request->action());die;
33 33
         // 校验sessionid和authKey
34 34
         if (empty($sessionId) || empty($authKey) || empty($cache)) {
35 35
             header('Content-Type:application/json; charset=utf-8');
@@ -52,7 +52,5 @@ class ApiCommon extends Common
52 52
         session('user_id', $userInfo['id']);
53 53
         // 更新缓存
54 54
         Cache::set('Auth_'.$authKey, $cache, $loginExpire);
55
-//        cache('Auth_'.$authKey, $cache, $loginExpire, 'UserToken');
56
-        // $GLOBALS['userInfo'] = $userInfo;
57 55
     }
58 56
 }

+ 45
- 1
application/admin/controller/Base.php Zobrazit soubor

@@ -31,8 +31,52 @@ class Base extends Common
31 31
         if (!$data) {
32 32
             return resultArray(['error' => $userModel->getError()]);
33 33
         }
34
+
35
+        # 数据库更新 todo 在线升级正常使用后删除
36
+        $updateStatus = $this->executeUpdateSql();
37
+        if (empty($updateStatus['status'])) return resultArray(['error' => $updateStatus['message']]);
38
+
34 39
         return resultArray(['data' => $data]);
35
-    }     
40
+    }
41
+
42
+    /**
43
+     * 更新SQL
44
+     *
45
+     * @author fanqi
46
+     * @since 2021-05-08
47
+     */
48
+    public function executeUpdateSql()
49
+    {
50
+        # 表前缀
51
+        $prefix = config('database.prefix');
52
+
53
+        # 检查更新记录表是否存在
54
+        if (!db()->query("SHOW TABLES LIKE '".$prefix."admin_upgrade_record'")) {
55
+            db()->query("
56
+                CREATE TABLE `".$prefix."admin_upgrade_record` (
57
+                  `version` int(10) unsigned DEFAULT NULL COMMENT '版本号',
58
+                  UNIQUE KEY `version` (`version`) USING BTREE
59
+                ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT = 'SQL更新记录,用于防止重复执行更新。'
60
+            ");
61
+        }
62
+
63
+        # 检查是否执行过11.0.3版本的更新
64
+        if (!db('admin_upgrade_record')->where('version', 1103)->value('version')) {
65
+            # 添加跟进记录导入导出权限数据
66
+            UpdateSql::addFollowRuleData();
67
+
68
+            # 添加公海默认数据
69
+            $poolStatus = UpdateSql::addPoolDefaultData();
70
+            if (!$poolStatus) return ['status' => false, 'message' => '添加公海默认配置失败,请在后台手动添加!'];
71
+
72
+            # 添加此次升级标记
73
+            db('admin_upgrade_record')->insert(['version' => 1103]);
74
+
75
+            return ['status' => true, 'message' => '更新完成!'];
76
+        }
77
+
78
+        return ['status' => true, 'message' => '没有可用更新!'];
79
+    }
36 80
 
37 81
     //退出登录
38 82
     public function logout()

+ 2
- 0
application/admin/controller/ConfigSet.php Zobrazit soubor

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

+ 16
- 5
application/admin/controller/DailyRule.php Zobrazit soubor

@@ -24,7 +24,7 @@ class DailyRule extends ApiCommon
24 24
     {
25 25
         $action = [
26 26
             'permission'=>[''],
27
-            'allow'=>['welcome', 'setwelcome', 'worklogrule', 'setworklogrule','scheduleList','addschedule','setschedule','delschedule']
27
+            'allow'=>['welcome', 'setwelcome', 'worklogrule', 'setworklogrule','schedulelist','addschedule','setschedule','delschedule']
28 28
         ];
29 29
         Hook::listen('check_auth',$action);
30 30
         $request = Request::instance();
@@ -58,11 +58,12 @@ class DailyRule extends ApiCommon
58 58
     public function setWelcome(DailyRuleLogic $dailyRuleLogic)
59 59
     {
60 60
         $mark = $this->param['welcome'];
61
-
61
+        $userInfo=$this->userInfo;
62 62
         if (empty($mark)) return resultArray(['error' => '缺少日志欢迎语!']);
63 63
 
64 64
         if (!$dailyRuleLogic->setWelcome($mark)) return resultArray(['error' => '添加失败!']);
65
-
65
+        # 系统操作日志
66
+        SystemActionLog($userInfo['id'], 'admin_oalog_rule','work_task','1','update','日志欢迎语' , '', '','设置了日志欢迎语');
66 67
         return resultArray(['data' => '添加成功!']);
67 68
     }
68 69
 
@@ -93,9 +94,10 @@ class DailyRule extends ApiCommon
93 94
     public function setWorkLogRule(DailyRuleLogic $dailyRuleLogic)
94 95
     {
95 96
         if (empty($this->param['rule'])) return resultArray(['error' => '缺少规则参数!']);
96
-
97
+        $userInfo=$this->userInfo;
97 98
         $dailyRuleLogic->setWorkLogRule($this->param['rule']);
98
-
99
+        # 系统操作日志
100
+        SystemActionLog($userInfo['id'], 'admin_oalog_rule','work_task', 1, 'update','日志规则' , '', '','设置了日志规则');
99 101
         return resultArray(['data' => '设置成功!']);
100 102
     }
101 103
 
@@ -120,8 +122,11 @@ class DailyRule extends ApiCommon
120 122
      * @throws \think\exception\PDOException
121 123
      */
122 124
     public function  setSchedule(DailyRuleLogic $dailyRuleLogic){
125
+        $userInfo=$this->userInfo;
123 126
         if(empty($this->param['id'])) return resultArray(['error'=>'缺少参数']);
124 127
           $dailyRuleLogic->setSchedule($this->param);
128
+        # 系统操作日志
129
+        SystemActionLog($userInfo['id'], 'admin_oalog_rule','work_task', 1, 'update','日程类型' , '', '','设置了日程类型');
125 130
         return resultArray(['data' => '设置成功!']);
126 131
 
127 132
     }
@@ -132,8 +137,11 @@ class DailyRule extends ApiCommon
132 137
      * @return \think\response\Json
133 138
      */
134 139
     public function addSchedule(DailyRuleLogic $dailyRuleLogic){
140
+        $userInfo=$this->userInfo;
135 141
         if(empty($this->param['name'])) return resultArray(['error'=>'缺少参数']);
136 142
         $dailyRuleLogic->addSchedule($this->param);
143
+        # 系统操作日志
144
+        SystemActionLog($userInfo['id'], 'admin_oalog_rule','work_task', 1, 'save','日程类型' , '', '','新增了日程类型');
137 145
         return resultArray(['data' => '添加成功!']);
138 146
 
139 147
     }
@@ -144,8 +152,11 @@ class DailyRule extends ApiCommon
144 152
      * @return \think\response\Json
145 153
      */
146 154
     public function delSchedule(DailyRuleLogic $dailyRuleLogic){
155
+        $userInfo=$this->userInfo;
147 156
         if(empty($this->param['id'])) return resultArray(['error'=>'缺少参数']);
148 157
         $dailyRuleLogic->delSchedule($this->param['id']);
158
+        # 系统操作日志
159
+        SystemActionLog($userInfo['id'], 'admin_oalog_rule','work_task', 1, 'update','日程类型' , '', '','删除了日程类型');
149 160
         return resultArray(['data' => '删除成功!']);
150 161
     }
151 162
 

+ 22
- 5
application/admin/controller/ExamineFlow.php Zobrazit soubor

@@ -82,6 +82,7 @@ class ExamineFlow extends ApiCommon
82 82
         $param['structure_ids'] = arrayToString($param['structure_ids']);
83 83
         $res = $examineFlowModel->createData($param);
84 84
         $param['config'] = $param['config'] ? 1 : 0;
85
+        SystemActionLog($userInfo['id'], 'admin_examine','approval', $res['flow_id'], 'save', $param['name'], '', '','添加了审批流:'.$param['name']);
85 86
         if ($res) {
86 87
             $config = $param['config'];
87 88
             if ((int)$config == 1) {
@@ -94,6 +95,7 @@ class ExamineFlow extends ApiCommon
94 95
                     return resultArray(['error' => $examineStepModel->getError()]);
95 96
                 }               
96 97
             }
98
+           
97 99
             return resultArray(['data' => '添加成功']);
98 100
         } else {
99 101
         	return resultArray(['error' => $examineFlowModel->getError()]);
@@ -144,7 +146,8 @@ class ExamineFlow extends ApiCommon
144 146
             $upData['delete_user_id'] = $userInfo['id'];
145 147
             $upData['status'] = 0;
146 148
             db('admin_examine_flow')->where(['flow_id' => $flowId])->update($upData);
147
-
149
+            # 添加系统操作日志
150
+            SystemActionLog($userInfo['id'], 'admin_examine','approval', $flowId,  'update', $param['name'], '', '','编辑了审批流:'.$param['name']);
148 151
             $config = $param['config'];
149 152
             if ((int)$config == 1) {
150 153
                 //固定审批流
@@ -220,11 +223,15 @@ class ExamineFlow extends ApiCommon
220 223
     public function delete()
221 224
     {
222 225
         $examineFlowModel = model('ExamineFlow');
223
-        $param = $this->param;       
226
+        $param = $this->param;
227
+        $userInfo = $this->userInfo;
224 228
         $data = $examineFlowModel->signDelById($param['flow_id']);
225 229
         if (!$data) {
226 230
             return resultArray(['error' => $examineFlowModel->getError()]);
227 231
         }
232
+        # 系统操作日志
233
+        $newData = db('admin_examine_flow')->where(['flow_id' => $param['flow_id']])->find();
234
+        SystemActionLog($userInfo['id'], 'admin_examine','approval', $param['flow_id'], 'update', $newData['name'], '', '','删除了审批流:'.$newData['name']);
228 235
         return resultArray(['data' => '删除成功']);
229 236
     }
230 237
 
@@ -238,12 +245,22 @@ class ExamineFlow extends ApiCommon
238 245
     public function enables()
239 246
     {
240 247
         $examineFlowModel = model('ExamineFlow');
241
-        $param = $this->param;        
248
+        $param = $this->param;
249
+        $userInfo=$this->userInfo;
242 250
         $id = [$param['flow_id']];
243
-        $data = $examineFlowModel->enableDatas($id, $param['status']);  
251
+        $data = $examineFlowModel->enableDatas($id, $param['status']);
252
+        # 系统操作日志
244 253
         if (!$data) {
245 254
             return resultArray(['error' => $examineFlowModel->getError()]);
246
-        } 
255
+        }
256
+        if($param['status']==0){
257
+            $content='禁用了:';
258
+        }else{
259
+            $content='启用了:';
260
+        }
261
+        $dataInfo=db('admin_examine_flow')->where('flow_id',$param['flow_id'])->find();
262
+//        p(3333);
263
+        SystemActionLog($userInfo['id'], 'admin_examine','approval', $param['flow_id'], 'update', $dataInfo['name'], '', '',$content.$dataInfo['name']);
247 264
         return resultArray(['data' => '操作成功']);         
248 265
     }
249 266
 

+ 70
- 32
application/admin/controller/Field.php Zobrazit soubor

@@ -108,7 +108,7 @@ class Field extends ApiCommon
108 108
         if ($this->param['types'] == 'oa_examine' && $this->param['types_id'] < 7) {
109 109
             return resultArray(['error' => '系统审批类型暂不支持编辑']);
110 110
         }
111
-
111
+        $userInfo=$this->userInfo;
112 112
         $fieldModel = model('Field');
113 113
 
114 114
         $param      = $this->param;
@@ -160,25 +160,37 @@ class Field extends ApiCommon
160 160
         foreach ($deleteIds AS $key => $value) {
161 161
             if (!in_array($value, $delParam)) $delParam[] = $value;
162 162
         }
163
-
163
+        $recordModules = [
164
+            'crm_leads'       => '线索',
165
+            'crm_customer'    => '客户',
166
+            'crm_pool'        => '客户公海',
167
+            'crm_contacts'    => '联系人',
168
+            'crm_product'     => '产品',
169
+            'crm_business'    => '商机',
170
+            'crm_contract'    => '合同',
171
+            'crm_receivables' => '回款',
172
+            'crm_visit'       => '回访',
173
+            'crm_invoice'     => '回款',
174
+            'oa_log'          => '办公日志',
175
+            'oa_examine'      => '办公审批',
176
+        ];
164 177
         # 新增
165 178
         if (!empty($saveParam)) {
166 179
             if (!$data = $fieldModel->createData($types, $saveParam)) {
167 180
                 $errorMessage[] = $fieldModel->getError();
168 181
             }            
169 182
         }
170
-
171 183
         # 编辑
172 184
         if (!empty($updateParam)) {
173
-            if (!$data = $fieldModel->updateDataById($updateParam)) {
185
+            if (!$data = $fieldModel->updateDataById($updateParam, $types)) {
174 186
                 $errorMessage[] = $fieldModel->getError();
175 187
             }
176 188
         }
177 189
 
178 190
         # 删除
179 191
         if (!empty($delParam)) {
180
-            if (!$data = $fieldModel->delDataById($delParam)) {
181
-                if (!empty($fieldModel->getError())) $errorMessage[] = $fieldModel->getError();
192
+            if (!$data = $fieldModel->delDataById($delParam, $types)) {
193
+                $errorMessage[] = $fieldModel->getError();
182 194
             }
183 195
         }
184 196
 
@@ -188,6 +200,27 @@ class Field extends ApiCommon
188 200
         if ($errorMessage) {
189 201
             return resultArray(['error' => $errorMessage]);
190 202
         } else {
203
+            # 系统操作记录
204
+            $recordModules = [
205
+                'crm_leads'       => '线索',
206
+                'crm_customer'    => '客户',
207
+                'crm_pool'        => '客户公海',
208
+                'crm_contacts'    => '联系人',
209
+                'crm_product'     => '产品',
210
+                'crm_business'    => '商机',
211
+                'crm_contract'    => '合同',
212
+                'crm_receivables' => '回款',
213
+                'crm_visit'       => '回访',
214
+                'crm_invoice'     => '回款',
215
+                'oa_log'          => '办公日志',
216
+                'oa_examine'      => '办公审批',
217
+            ];
218
+            if($types !== 'oa_examine'){
219
+                $systemModules='customer';
220
+            }else{
221
+                $systemModules='approval';
222
+            }
223
+            SystemActionLog($userInfo['id'], $types,$systemModules, 1,  'update', $recordModules[$types], '','','编辑了自定义字段:'.$recordModules[$types]);
191 224
             return resultArray(['data' => '修改成功']);
192 225
         }
193 226
     }
@@ -227,6 +260,11 @@ class Field extends ApiCommon
227 260
                     case 'crm_customer' : 
228 261
                         $customerModel = new \app\crm\model\Customer();
229 262
                         $dataInfo = $customerModel->getDataById(intval($param['action_id']));
263
+                        // 公海
264
+                        if (!empty($param['pool_id'])) {
265
+                            $data = $fieldModel->getPoolFieldData($param['pool_id'], $dataInfo);
266
+                            return resultArray(['data' => $data]);
267
+                        }
230 268
                         //判断权限
231 269
                         $auth_user_ids = $userModel->getUserByPer('crm', 'customer', $param['action']);
232 270
                         //读写权限
@@ -342,6 +380,15 @@ class Field extends ApiCommon
342 380
         $action_id = $param['action_id'] ? : '';
343 381
         $data = $fieldModel->field($param, $dataInfo) ? : [];
344 382
 
383
+        # 回访模块下,负责人名称变更为回访人
384
+        if ($param['types'] == 'crm_visit') {
385
+            foreach ($data AS $key => $value) {
386
+                if ($value['field'] == 'owner_user_id') {
387
+                    $data[$key]['name'] = '回访人';
388
+                    break;
389
+                }
390
+            }
391
+        }
345 392
         # 去掉客户模块下的成交信息
346 393
         if ($param['types'] == 'crm_customer' && $param['action'] == 'read') {
347 394
             foreach ($data AS $key => $value) {
@@ -351,28 +398,18 @@ class Field extends ApiCommon
351 398
                 }
352 399
             }
353 400
         }
354
-
355
-        if ($param['types'] == 'crm_customer' && $param['action'] == 'index') {
401
+        # 合同回款 基本信息审核状态
402
+        if(in_array($param['types'], ['crm_receivables', 'crm_contract']) && $param['action'] == 'read'){
403
+            $check=['0'=>'待审核','1'=>'审核中','2'=>'审核通过','3'=>'审核未通过','4'=>'撤销','5'=>'草稿(未提交)','6'=>'作废'];
356 404
             $data[] = [
357
-                'field'       => 'pool_day',
358
-                'name'        => '距进入公海天数',
405
+                'field'       => 'check_status',
406
+                'name'        => '审核状态',
359 407
                 'form_type'   => 'text',
360 408
                 'writeStatus' => 0,
361
-                'fieldName'   => 'pool_day'
362
-            ];
363
-        }
364
-
365
-        # 客户锁定状态
366
-        if ($param['types'] == 'crm_customer' && $param['action'] == 'index') {
367
-            $data[] = [
368
-                'field'     => "is_lock",
369
-                'fieldName' => "is_lock",
370
-                'form_type' => "text",
371
-                'name'      => "锁定状态",
372
-                'width'     => ""
409
+                'fieldName'   => 'check_status',
410
+                'value'     => $check[$dataInfo['check_status']],
373 411
             ];
374 412
         }
375
-
376 413
         # 合同自动编号设置
377 414
         if ($param['types'] == 'crm_contract') {
378 415
             foreach ($data AS $key => $value) {
@@ -436,7 +473,7 @@ class Field extends ApiCommon
436 473
                 case 'crm_leads' :
437 474
                     $leadsModel = new Leads();
438 475
                     $leadsData  = $leadsModel->getSystemInfo($action_id);
439
-                    $leadsArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'follow_time' => '最后跟进时间'];
476
+                    $leadsArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间'];
440 477
 
441 478
                     foreach ($leadsData AS $key => $value) {
442 479
                         if (empty($leadsArray[$key])) continue;
@@ -453,7 +490,7 @@ class Field extends ApiCommon
453 490
                 case 'crm_customer' :
454 491
                     $customerModel = new Customer();
455 492
                     $customerData  = $customerModel->getSystemInfo($action_id);
456
-                    $customerArray = ['obtain_time' => '负责人获取客户时间', 'create_time' => '创建时间', 'update_time' => '更新时间', 'follow_time' => '最后跟进时间', 'follow_record' => '最后跟进记录', 'deal_status' => '成交状态'];
493
+                    $customerArray = ['obtain_time' => '负责人获取客户时间', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间', 'last_record' => '最后跟进记录', 'deal_status' => '成交状态'];
457 494
 
458 495
                     foreach ($customerData AS $key => $value) {
459 496
                         if (empty($customerArray[$key])) continue;
@@ -470,7 +507,7 @@ class Field extends ApiCommon
470 507
                 case 'crm_contacts' :
471 508
                     $contactsModel = new Contacts();
472 509
                     $contactsData  = $contactsModel->getSystemInfo($action_id);
473
-                    $contactsArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'follow_time' => '最后跟进时间'];
510
+                    $contactsArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间'];
474 511
 
475 512
                     foreach ($contactsData AS $key => $value) {
476 513
                         if (empty($contactsArray[$key])) continue;
@@ -487,7 +524,7 @@ class Field extends ApiCommon
487 524
                 case 'crm_business' :
488 525
                     $businessModel = new Business();
489 526
                     $businessData  = $businessModel->getSystemInfo($action_id);
490
-                    $businessArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'follow_time' => '最后跟进时间'];
527
+                    $businessArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间'];
491 528
 
492 529
                     foreach ($businessData AS $key => $value) {
493 530
                         if (empty($businessArray[$key])) continue;
@@ -504,7 +541,7 @@ class Field extends ApiCommon
504 541
                 case 'crm_contract' :
505 542
                     $contractModel = new Contract();
506 543
                     $contractData  = $contractModel->getSystemInfo($action_id);
507
-                    $contractArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'follow_time' => '最后跟进时间', 'done_money' => '已收款金额', 'un_money' => '未收款金额'];
544
+                    $contractArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间', 'done_money' => '已收款金额', 'un_money' => '未收款金额'];
508 545
 
509 546
                     foreach ($contractData AS $key => $value) {
510 547
                         if (empty($contractArray[$key])) continue;
@@ -521,7 +558,7 @@ class Field extends ApiCommon
521 558
                 case 'crm_receivables' :
522 559
                     $receivablesModel = new Receivables();
523 560
                     $receivablesData  = $receivablesModel->getSystemInfo($action_id);
524
-                    $receivablesArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
561
+                    $receivablesArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
525 562
 
526 563
                     foreach ($receivablesData AS $key => $value) {
527 564
                         if (empty($receivablesArray[$key])) continue;
@@ -538,7 +575,7 @@ class Field extends ApiCommon
538 575
                 case 'crm_product' :
539 576
                     $productModel = new Product();
540 577
                     $productData  = $productModel->getSystemInfo($action_id);
541
-                    $productArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
578
+                    $productArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
542 579
 
543 580
                     foreach ($productData AS $key => $value) {
544 581
                         if (empty($productArray[$key])) continue;
@@ -555,7 +592,7 @@ class Field extends ApiCommon
555 592
                 case 'crm_visit' :
556 593
                     $visitLogic = new VisitLogic();
557 594
                     $visitData  = $visitLogic->getSystemInfo($action_id);
558
-                    $visitArray = ['create_user_name' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
595
+                    $visitArray = ['create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间'];
559 596
 
560 597
                     foreach ($visitData AS $key => $value) {
561 598
                         if (empty($visitArray[$key])) continue;
@@ -572,7 +609,8 @@ class Field extends ApiCommon
572 609
             }
573 610
         }
574 611
 
575
-        $data = $fieldModel->resetField($param['types'], $data);
612
+        $data = $fieldModel->resetField($user_id, $param['types'], $param['action'], $data);
613
+
576 614
         return resultArray(['data' => array_values($data)]);
577 615
     }
578 616
 

+ 8
- 2
application/admin/controller/Groups.php Zobrazit soubor

@@ -78,6 +78,7 @@ class Groups extends ApiCommon
78 78
      */    
79 79
     public function save(FieldGrantLogic $fieldGrantLogic)
80 80
     {
81
+        $userInfo=$this->userInfo;
81 82
         $groupModel = model('Group');
82 83
         $param = $this->param;
83 84
 		$param['rules'] = arrayToString($param['rules']);
@@ -85,7 +86,9 @@ class Groups extends ApiCommon
85 86
         if (!$lastInsId) {
86 87
             return resultArray(['error' => $groupModel->getError()]);
87 88
         }
88
-
89
+        # 添加记录
90
+        SystemActionLog($userInfo['id'], 'admin_group','role', $lastInsId, 'save', $param['title'], '', '', '添加了角色:' . $param['title']);
91
+    
89 92
         # 新增客户管理角色的字段授权数据
90 93
         if (isset($param['pid']) && $param['pid'] == 2) {
91 94
             $fieldGrantLogic->createCrmFieldGrant($lastInsId);
@@ -179,6 +182,7 @@ class Groups extends ApiCommon
179 182
     {        
180 183
         $groupModel = model('Group');
181 184
         $param = $this->param;
185
+        $userInfo = $this->userInfo;
182 186
         $dataInfo = $groupModel->getDataById($param['id']);
183 187
         if (!$dataInfo) {
184 188
             return resultArray(['error' => '参数错误']);
@@ -191,7 +195,9 @@ class Groups extends ApiCommon
191 195
         if (!$data) {
192 196
             return resultArray(['error' => $groupModel->getError()]);
193 197
         }
194
-
198
+        # 添加记录
199
+        SystemActionLog($userInfo['id'], 'admin_group','role', $data, 'copy', $dataInfo['title'], '', '', '添加了角色:' . $dataInfo['title']);
200
+    
195 201
         # 复制客户管理角色的字段授权数据
196 202
         if (!empty($dataInfo['pid']) && $dataInfo['pid'] == 2) {
197 203
             $fieldGrantLogic->copyCrmFieldGrant($param['id'], $data);

+ 8
- 0
application/admin/controller/Index.php Zobrazit soubor

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

+ 5
- 1
application/admin/controller/Initialize.php Zobrazit soubor

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

+ 26
- 6
application/admin/controller/Install.php Zobrazit soubor

@@ -47,19 +47,34 @@ class Install extends Controller
47 47
      */    
48 48
     public function index()
49 49
     {
50
+        $protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
51
+
52
+        if (strpos(request()->url(), "index.php") === false) {
53
+            $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
54
+            header("Location:" . $url);
55
+        }
56
+
50 57
         if (file_exists(CONF_PATH . "install.lock")) {
51
-            echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8'> <script>alert('请勿重复安装!');location.href='".$_SERVER["HTTP_HOST"]."';</script>";
58
+            echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8'> <script>alert('请勿重复安装!');location.href='".$protocol."://".$_SERVER["HTTP_HOST"]."';</script>";
52 59
             die();     
53 60
         }
61
+
54 62
         if (!file_exists(getcwd() . "/public/sql/5kcrm.sql")) {
55
-            echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8'> <script>alert('缺少必要的数据库文件!');location.href='".$_SERVER["HTTP_HOST"]."';</script>";
63
+            echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8'> <script>alert('缺少必要的数据库文件!');location.href='".$protocol."://".$_SERVER["HTTP_HOST"]."';</script>";
56 64
             die();     
57
-        }         
58
-        return $this->fetch('index');      
65
+        }
66
+
67
+        return $this->fetch('index');
59 68
     }
60 69
 
61 70
     public function step1()
62 71
     {
72
+        if (strpos(request()->url(), "index.php") === false) {
73
+            $protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
74
+            $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
75
+            header("Location:" . $url);
76
+        }
77
+
63 78
 		session('install_error',null);
64 79
         $data           = [];
65 80
         $data['env']    = self::checkNnv();
@@ -81,6 +96,11 @@ class Install extends Controller
81 96
             echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8'> <script>alert('环境检测未通过,不能进行下一步操作!');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
82 97
             die(); 
83 98
         }
99
+        if (strpos(request()->url(), "index.php") === false) {
100
+            $protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
101
+            $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
102
+            header("Location:" . $url);
103
+        }
84 104
         $data['os'] = PHP_OS;
85 105
         $data['php'] = phpversion();
86 106
         $data['version'] = $this->version();
@@ -352,13 +372,13 @@ INFO;
352 372
     {
353 373
         $items = [
354 374
             'os'      => ['操作系统', PHP_OS, '类Unix', 'ok'],
355
-            'php'     => ['PHP版本', PHP_VERSION, '7.3 ( <em style="color: #888; font-size: 12px;">>= 5.6</em> )', 'ok','性能更佳'],
375
+            'php'     => ['PHP版本', PHP_VERSION, '7.3 ( <em style="color: #888; font-size: 12px;">>= 7.0</em> )', 'ok','性能更佳'],
356 376
             'gd'      => ['gd', '开启', '开启', 'ok'],
357 377
             'openssl' => ['openssl', '开启', '开启', 'ok'],
358 378
             'pdo' => ['pdo', '开启', '开启', 'ok'],
359 379
         ];
360 380
         session('install_error','');
361
-        if (substr($items['php'][1],0,3) < '5.6') {
381
+        if (substr($items['php'][1],0,3) < '7.0') {
362 382
             $items['php'][3] = 'error';
363 383
             session('install_error', true);
364 384
         }

+ 78
- 1
application/admin/controller/Log.php Zobrazit soubor

@@ -24,7 +24,7 @@ class Log extends ApiCommon
24 24
     {
25 25
         $action = [
26 26
             'permission' => [''],
27
-            'allow' => ['dataRecord', 'systemRecord', 'loginRecord']
27
+            'allow' => ['dataRecord', 'systemRecord', 'loginRecord','excelImport']
28 28
         ];
29 29
         Hook::listen('check_auth',$action);
30 30
         $request = Request::instance();
@@ -45,6 +45,61 @@ class Log extends ApiCommon
45 45
      */
46 46
     public function dataRecord(LogLogic $logLogic)
47 47
     {
48
+        $this->param['startTime']= !empty($this->param['startTime'])?$this->param['startTime'].' 00:00:00':'';
49
+        $this->param['endTime']= !empty($this->param['endTime'])?$this->param['endTime'].' 23:59:59':'';
50
+        if(!empty($this->param['subModelLabels'])){
51
+            $this->param['modules']=$this->param['subModelLabels'];
52
+        }else{
53
+            switch ($this->param['model']){
54
+                case 'crm': //客户管理
55
+                    $this->param['modules']=array(
56
+                        'crm_leads'  ,
57
+                        'crm_customer',
58
+                        'crm_pool'     ,
59
+                        'crm_contacts'  ,
60
+                        'crm_product'    ,
61
+                        'crm_business'    ,
62
+                        'crm_contract'     ,
63
+                        'crm_receivables'  ,
64
+                        'crm_visit'        ,
65
+                        'crm_invoice'      ,
66
+                        'crm_activity'
67
+                    );
68
+                    break;
69
+                case 'oa' : //办公管理
70
+                    $this->param['modules']=array(
71
+                        'oa_log'  ,
72
+                        'oa_event',
73
+                    );
74
+                    break;
75
+                case 'work' ://项目管理
76
+                    $this->param['modules']=array(
77
+                        'work_task'  ,
78
+                        'work',
79
+                    );
80
+                    break;
81
+                default :
82
+                    $this->param['modules']=array(
83
+                        'crm_leads'  ,
84
+                        'crm_customer',
85
+                        'crm_pool'     ,
86
+                        'crm_contacts'  ,
87
+                        'crm_product'    ,
88
+                        'crm_business'    ,
89
+                        'crm_contract'     ,
90
+                        'crm_receivables'  ,
91
+                        'crm_visit'        ,
92
+                        'crm_invoice'      ,
93
+                        'crm_activity',
94
+                        'oa_log'  ,
95
+                        'oa_event',
96
+                        'work_task'  ,
97
+                        'work',
98
+                    );
99
+                    break;
100
+            }
101
+        }
102
+        
48 103
         $data['list']    = $logLogic->getRecordLogs($this->param);
49 104
         $data['count']   = $logLogic->getRecordLogCount($this->param);
50 105
         $data['modules'] = $logLogic->recordModules;
@@ -63,6 +118,11 @@ class Log extends ApiCommon
63 118
      */
64 119
     public function systemRecord(LogLogic $logLogic)
65 120
     {
121
+        $this->param['startTime']= !empty($this->param['startTime'])?$this->param['startTime'].' 00:00:00':'';
122
+        $this->param['endTime']= !empty($this->param['endTime'])?$this->param['endTime'].' 23:59:59':'';
123
+        if(!empty($this->param['subModelLabels'])){
124
+            $this->param['modules']=$this->param['subModelLabels'];
125
+        }
66 126
         $data['list']    = $logLogic->getSystemLogs($this->param);
67 127
         $data['count']   = $logLogic->getSystemLogCount($this->param);
68 128
         $data['modules'] = $logLogic->systemModules;
@@ -79,8 +139,25 @@ class Log extends ApiCommon
79 139
      */
80 140
     public function loginRecord(LogLogic $logLogic)
81 141
     {
142
+        $this->param['startTime']= !empty($this->param['startTime'])?$this->param['startTime'].' 00:00:00':'';
143
+        $this->param['endTime']= !empty($this->param['endTime'])?$this->param['endTime'].' 23:59:59':'';
82 144
         $data = $logLogic->getLoginRecord($this->param);
83 145
 
84 146
         return resultArray(['data' => $data]);
85 147
     }
148
+    
149
+    /**
150
+     * 日志导出
151
+     *
152
+     * @param LogLogic $logLogic
153
+     * @author      alvin guogaobo
154
+     * @version     1.0 版本号
155
+     * @since       2021/4/8 0008 16:36
156
+     */
157
+    public function excelImport()
158
+    {
159
+        $logLogic =new LogLogic;
160
+        $data = $logLogic->downExcel($this->param);
161
+        return $data;
162
+    }
86 163
 }

+ 1
- 0
application/admin/controller/Market.php Zobrazit soubor

@@ -0,0 +1 @@
1
+<?php

+ 4
- 7
application/admin/controller/Printing.php Zobrazit soubor

@@ -45,10 +45,7 @@ class Printing extends ApiCommon
45 45
      */
46 46
     public function index(PrintingLogic $printingLogic)
47 47
     {
48
-        $page  = !empty($this->param['page'])  ? $this->param['page']  : 1;
49
-        $limit = !empty($this->param['limit']) ? $this->param['limit'] : 15;
50
-
51
-        $data = $printingLogic->index($page, $limit);
48
+        $data = $printingLogic->index($this->param);
52 49
 
53 50
         return resultArray(['data' => $data]);
54 51
     }
@@ -65,7 +62,6 @@ class Printing extends ApiCommon
65 62
 
66 63
         if (empty($param['name']))    return resultArray(['error' => '缺少模板名称!']);
67 64
         if (empty($param['type']))    return resultArray(['error' => '缺少模板类型!']);
68
-        if (empty($param['content'])) return resultArray(['error' => '缺少模板详情!']);
69 65
 
70 66
         if (!$printingLogic->create($param)) return resultArray(['error' => '添加失败!']);
71 67
 
@@ -103,8 +99,9 @@ class Printing extends ApiCommon
103 99
         $param = $this->param;
104 100
 
105 101
         if (empty($param['id'])) return resultArray(['error' => '缺少模板ID!']);
102
+        if (isset($param['name']) && empty($param['name'])) return resultArray(['error' => '名称不能为空!']);
106 103
 
107
-        if (!$printingLogic->update($param)) return resultArray(['error' => '更新失败!']);
104
+        if ($printingLogic->update($param) === false) return resultArray(['error' => '更新失败!']);
108 105
 
109 106
         return resultArray(['data' => '更新成功!']);
110 107
     }
@@ -159,7 +156,7 @@ class Printing extends ApiCommon
159 156
      */
160 157
     public function field(PrintingLogic $printingLogic)
161 158
     {
162
-        # 打印类型:1商机;2合同;3回款
159
+        # 打印类型:5商机;6合同;7回款
163 160
         $type = !empty($this->param['type']) ? $this->param['type'] : 5;
164 161
 
165 162
         $data = $printingLogic->getFields($type);

+ 137
- 1
application/admin/controller/Setting.php Zobrazit soubor

@@ -8,6 +8,7 @@
8 8
 namespace app\admin\controller;
9 9
 
10 10
 use app\admin\controller\ApiCommon;
11
+use app\admin\logic\PoolConfigLogic;
11 12
 use think\Hook;
12 13
 use think\Request;
13 14
 
@@ -23,7 +24,7 @@ class Setting extends ApiCommon
23 24
     {
24 25
         $action = [
25 26
             'permission'=>[''],
26
-            'allow'=>['']            
27
+            'allow'=>['pool','setpool','readpool','changepool','deletepool','transferpool','customerlevel','poolfield']
27 28
         ];
28 29
         Hook::listen('check_auth',$action);
29 30
         $request = Request::instance();
@@ -40,4 +41,139 @@ class Setting extends ApiCommon
40 41
             exit(json_encode(['code'=>102,'error'=>'无权操作']));
41 42
         }           
42 43
     }
44
+
45
+    /**
46
+     * 公海配置列表
47
+     *
48
+     * @param PoolConfigLogic $poolConfigLogic
49
+     * @author fanqi
50
+     * @since 2021-03-30
51
+     * @return \think\response\Json
52
+     */
53
+    public function pool(PoolConfigLogic $poolConfigLogic)
54
+    {
55
+        $data = $poolConfigLogic->getPoolList($this->param);
56
+
57
+        return resultArray(['data' => $data]);
58
+    }
59
+
60
+    /**
61
+     * 设置公海规则
62
+     *
63
+     * @param
64
+     * @param PoolConfigLogic $poolConfigLogic 公海逻辑类
65
+     * @author fanqi
66
+     * @since 2021-03-29
67
+     * @return \think\response\Json
68
+     */
69
+    public function setPool(PoolConfigLogic $poolConfigLogic)
70
+    {
71
+        $userInfo = $this->userInfo;
72
+        $param = $this->param;
73
+        $param['user_id'] = $userInfo['id'];
74
+
75
+        if ($poolConfigLogic->setPoolConfig($param) === false) return resultArray(['error' => $poolConfigLogic->error]);
76
+
77
+        return resultArray(['data' => '操作成功!']);
78
+    }
79
+
80
+    /**
81
+     * 公海配置详情
82
+     *
83
+     * @param PoolConfigLogic $poolConfigLogic
84
+     * @author fanqi
85
+     * @since 2021-03-30
86
+     * @return \think\response\Json
87
+     */
88
+    public function readPool(PoolConfigLogic $poolConfigLogic)
89
+    {
90
+        $poolId = $this->param['pool_id'];
91
+
92
+        $data = $poolConfigLogic->readPool($poolId);
93
+
94
+        if ($data === false) return resultArray(['error' => $poolConfigLogic->error]);
95
+
96
+        return resultArray(['data' => $data]);
97
+    }
98
+
99
+    /**
100
+     * 变更公海配置状态
101
+     *
102
+     * @param PoolConfigLogic $poolConfigLogic
103
+     * @author fanqi
104
+     * @since 2021-03-30
105
+     * @return \think\response\Json
106
+     */
107
+    public function changePool(PoolConfigLogic $poolConfigLogic)
108
+    {
109
+        if ($poolConfigLogic->changePoolStatus($this->param) === false) return resultArray(['error' => $poolConfigLogic->error]);
110
+
111
+        return resultArray(['data' => '操作成功!']);
112
+    }
113
+
114
+    /**
115
+     * 删除公海配置
116
+     *
117
+     * @param PoolConfigLogic $poolConfigLogic
118
+     * @author fanqi
119
+     * @since 2021-03-30
120
+     * @return \think\response\Json
121
+     */
122
+    public function deletePool(PoolConfigLogic $poolConfigLogic)
123
+    {
124
+        $poolId = $this->param['pool_id'];
125
+
126
+        if ($poolConfigLogic->deletePool($poolId) === false) return resultArray(['error' => $poolConfigLogic->error]);
127
+
128
+        return resultArray(['data' => '操作成功!']);
129
+    }
130
+
131
+    /**
132
+     * 公海客户转移
133
+     *
134
+     * @param PoolConfigLogic $poolConfigLogic
135
+     * @author fanqi
136
+     * @since 2021-03-30
137
+     * @return \think\response\Json
138
+     */
139
+    public function transferPool(PoolConfigLogic $poolConfigLogic)
140
+    {
141
+        $param = $this->param;
142
+
143
+        if ($poolConfigLogic->transferPool($param) === false) {
144
+            return resultArray(['error' => $poolConfigLogic->error]);
145
+        }
146
+
147
+        return resultArray(['data' => '操作成功!']);
148
+    }
149
+
150
+    /**
151
+     * 客户级别列表
152
+     *
153
+     * @param PoolConfigLogic $poolConfigLogic
154
+     * @author fanqi
155
+     * @since 2021-04-22
156
+     * @return \think\response\Json
157
+     */
158
+    public function customerLevel(PoolConfigLogic $poolConfigLogic)
159
+    {
160
+        $data = $poolConfigLogic->getCustomerLevel();
161
+
162
+        return resultArray(['data' => $data]);
163
+    }
164
+
165
+    /**
166
+     * 公海字段
167
+     *
168
+     * @param PoolConfigLogic $poolConfigLogic
169
+     * @author fanqi
170
+     * @since 2021-04-29
171
+     * @return \think\response\Json
172
+     */
173
+    public function poolField(PoolConfigLogic $poolConfigLogic)
174
+    {
175
+        $data = $poolConfigLogic->getPoolFieldList($this->param);
176
+
177
+        return resultArray(['data' => $data]);
178
+    }
43 179
 }

+ 19
- 8
application/admin/controller/Structures.php Zobrazit soubor

@@ -10,7 +10,7 @@ namespace app\admin\controller;
10 10
 use think\Hook;
11 11
 use think\Request;
12 12
 use think\Db;
13
-
13
+use app\admin\model\Structure;
14 14
 class Structures extends ApiCommon
15 15
 {
16 16
     /**
@@ -130,17 +130,25 @@ class Structures extends ApiCommon
130 130
         if (!checkPerByAction('admin', 'users', 'structures_save')) {
131 131
             header('Content-Type:application/json; charset=utf-8');
132 132
             exit(json_encode(['code'=>102,'error'=>'无权操作']));
133
-        }        
133
+        }
134
+        $userInfo=$this->userInfo;
134 135
         $structureModel = model('Structure');
135 136
         $param = $this->param;
136 137
 		if(!$param['pid']){
137 138
 			resultArray(['error' => '请选择上级部门']);
138 139
 		}
139
-        $data = $structureModel->createData($param);
140
-        if (!$data) {
140
+		if(!$param['owner_user_id']){
141
+			resultArray(['error' => '请选择部门负责人']);
142
+		}
143
+        if ($structureModel->data($param)->allowField(true)->save()) {
144
+            $id = $structureModel->id;
145
+            # 添加记录
146
+            $content = '添加了部门:' . $param['name'];
147
+            SystemActionLog($userInfo['id'], 'admin_structure','structures', $id, 'save', $param['name'], '', '', $content);
148
+            return resultArray(['data' => '添加成功']);
149
+        }else{
141 150
             return resultArray(['error' => $structureModel->getError()]);
142
-        } 
143
-        return resultArray(['data' => '添加成功']);
151
+        }
144 152
     }
145 153
 
146 154
     /**
@@ -155,7 +163,8 @@ class Structures extends ApiCommon
155 163
         if (!checkPerByAction('admin', 'users', 'structures_update')) {
156 164
             header('Content-Type:application/json; charset=utf-8');
157 165
             exit(json_encode(['code'=>102,'error'=>'无权操作']));
158
-        }        
166
+        }
167
+        $userInfo=$this->userInfo;
159 168
         $structureModel = model('Structure');
160 169
         $param = $this->param;
161 170
         $dataInfo = $structureModel->getDataByID($param['id']);
@@ -165,7 +174,9 @@ class Structures extends ApiCommon
165 174
         $data = $structureModel->updateDataById($param, $param['id']);
166 175
         if (!$data) {
167 176
             return resultArray(['error' => $structureModel->getError()]);
168
-        } 
177
+        }
178
+        # 系统操作日志
179
+        SystemActionLog($userInfo['id'], 'admin_structure','structures', $param['id'], 'update', $param['name'], '', '','编辑了部门名称:'.$param['name']);
169 180
         return resultArray(['data' => '编辑成功']);
170 181
     }
171 182
 

+ 12
- 5
application/admin/controller/System.php Zobrazit soubor

@@ -39,16 +39,23 @@ class System extends ApiCommon
39 39
 	public function save()
40 40
 	{
41 41
         $param = $this->param;
42
-
42
+        $userInfo=$this->userInfo;
43
+        $field_name='';
44
+        $dataInfo=[];
43 45
         if (isset($param['logo'])) {
46
+            $system_id=2;
47
+            $field_name='企业logo';
44 48
             $logo = !empty($param['logo']) ? './public/uploads/'.$param['logo'] : '';
49
+            $dataInfo =  db('admin_system')->where('id', $system_id)->column('name,value');
45 50
             db('admin_system')->where('name', 'logo')->update(['value' => $logo]);
46
-        }
47
-
48
-        if (isset($param['name'])) {
51
+        }elseif (isset($param['name'])) {
52
+            $system_id=1;
53
+            $field_name='企业名称';
54
+            $dataInfo =  db('admin_system')->where('id', $system_id)->column('name,value');
49 55
             db('admin_system')->where('name', 'name')->update(['value' => $param['name']]);
50 56
         }
51
-
57
+        # 修改记录
58
+        SystemActionLog($userInfo['id'],'admin_system','company',1,'update','企业基本信息设置','','','编辑了:'.$field_name);
52 59
         return resultArray(['data' => '操作成功!']);
53 60
 	}
54 61
 }

+ 122
- 0
application/admin/controller/UpdateSql.php Zobrazit soubor

@@ -0,0 +1,122 @@
1
+<?php
2
+/**
3
+ * 更新sql(包含安装)
4
+ *
5
+ * @author fanqi
6
+ * @since 2021-05-08
7
+ */
8
+namespace app\admin\controller;
9
+
10
+use think\Db;
11
+use think\Exception;
12
+
13
+class UpdateSql
14
+{
15
+    /**
16
+     * 添加公海默认数据
17
+     *
18
+     * @author fanqi
19
+     * @since 2021-05-08
20
+     * @return bool
21
+     */
22
+    static public function addPoolDefaultData()
23
+    {
24
+        # 员工ID
25
+        $userIds = db('admin_user')->column('id');
26
+
27
+        # 公海主数据
28
+        $poolData = [
29
+            'pool_name'         => '系统默认公海',
30
+            'admin_user_ids'    => ',1,',
31
+            'user_ids'          => ','.implode(',', $userIds).',',
32
+            'department_ids'    => '',
33
+            'status'            => 1,
34
+            'before_owner_conf' => 0,
35
+            'before_owner_day'  => 0,
36
+            'receive_conf'      => 0,
37
+            'receive_count'     => 0,
38
+            'remind_conf'       => 0,
39
+            'remain_day'        => 0,
40
+            'recycle_conf'      => 1,
41
+            'create_user_id'    => 1,
42
+            'create_time'       => time()
43
+        ];
44
+
45
+        # 公海规则数据
46
+        $poolRuleData = [
47
+            'pool_id'         => 0,
48
+            'type'            => 1,
49
+            'deal_handle'     => 0,
50
+            'business_handle' => 0,
51
+            'level_conf'      => 1,
52
+            'level'           => json_encode([['level' => '所有客户', 'limit_day' => 30]]),
53
+            'limit_day'       => 0
54
+        ];
55
+
56
+        # 公海字段数据
57
+        $poolFieldData = [];
58
+        $fields = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden'])->where(['types' => 'crm_customer'])->select();
59
+        foreach ($fields AS $key => $value) {
60
+            $poolFieldData[] = [
61
+                'field_name' => $value['field'],
62
+                'name'       => $value['name'],
63
+                'form_type'  => $value['form_type'],
64
+                'is_hidden'  => $value['is_hidden']
65
+            ];
66
+        }
67
+        $poolFieldData[] = ['field_name' => 'address', 'name' => '省、市、区/县', 'form_type' => 'customer_address', 'is_hidden' => 0];
68
+        $poolFieldData[] = ['field_name' => 'detail_address', 'name' => '详细地址', 'form_type' => 'text', 'is_hidden' => 0];
69
+        $poolFieldData[] = ['field_name' => 'last_record', 'name' => '最后跟进记录', 'form_type' => 'text', 'is_hidden' => 0];
70
+        $poolFieldData[] = ['field_name' => 'last_time', 'name' => '最后跟进时间', 'form_type' => 'datetime', 'is_hidden' => 0];
71
+        $poolFieldData[] = ['field_name' => 'before_owner_user_id', 'name' => '前负责人', 'form_type' => 'user', 'is_hidden' => 0];
72
+        $poolFieldData[] = ['field_name' => 'into_pool_time', 'name' => '进入公海时间', 'form_type' => 'datetime', 'is_hidden' => 0];
73
+        $poolFieldData[] = ['field_name' => 'create_time', 'name' => '创建时间', 'form_type' => 'datetime', 'is_hidden' => 0];
74
+        $poolFieldData[] = ['field_name' => 'update_time', 'name' => '更新时间', 'form_type' => 'datetime', 'is_hidden' => 0];
75
+        $poolFieldData[] = ['field_name' => 'create_user_id', 'name' => '创建人', 'form_type' => 'user', 'is_hidden' => 0];
76
+
77
+        Db::startTrans();
78
+        try {
79
+            # 添加公海主数据
80
+            $poolId = Db::name('crm_customer_pool')->insert($poolData, false, true);
81
+
82
+            # 添加公海规则数据
83
+            $poolRuleData['pool_id'] = $poolId;
84
+            Db::name('crm_customer_pool_rule')->insert($poolRuleData);
85
+
86
+            # 添加公海字段数据
87
+            array_walk($poolFieldData, function (&$val) use ($poolId) {
88
+                $val['pool_id'] = $poolId;
89
+            });
90
+            Db::name('crm_customer_pool_field_setting')->insertAll($poolFieldData);
91
+
92
+            Db::commit();
93
+
94
+            return true;
95
+        } catch (Exception $e) {
96
+            Db::rollback();
97
+
98
+            return false;
99
+        }
100
+    }
101
+
102
+    /**
103
+     * 添加跟进记录的导入导出权限数据
104
+     *
105
+     * @author fanqi
106
+     * @since 2021-05-08
107
+     */
108
+    static public function addFollowRuleData()
109
+    {
110
+        # 删除旧版的跟进记录权限规则数据
111
+        db('admin_rule')->where(['types' => 2, 'title' => '跟进记录管理', 'name' => 'record', 'level' => 2, 'pid' => 1])->delete();
112
+
113
+        # 新版跟进记录权限规则增加导入导出
114
+        $activityPid = db('admin_rule')->where(['types' => 2, 'title' => '跟进记录', 'name' => 'activity', 'level' => 2])->value('id');
115
+        if (!db('admin_rule')->where(['types' => 2, 'pid' => $activityPid, 'name' => 'excelImport'])->value('id')) {
116
+            db('admin_rule')->insert(['types' => 2, 'title' => '导入', 'name' => 'excelImport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]);
117
+        }
118
+        if (!db('admin_rule')->where(['types' => 2, 'pid' => $activityPid, 'name' => 'excelExport'])->value('id')) {
119
+            db('admin_rule')->insert(['types' => 2, 'title' => '导出', 'name' => 'excelExport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]);
120
+        }
121
+    }
122
+}

+ 273
- 199
application/admin/controller/Users.php Zobrazit soubor

@@ -18,15 +18,17 @@ use app\admin\model\User as UserModel;
18 18
 use app\admin\logic\UserLogic;
19 19
 use app\admin\model\Admin as AdminModel;
20 20
 use app\crm\traits\StarTrait;
21
+
21 22
 class Users extends ApiCommon
22 23
 {
23 24
     use StarTrait;
25
+    
24 26
     /**
25 27
      * 用于判断权限
26 28
      * @permission 无限制
27 29
      * @allow 登录员工可访问
28 30
      * @other 其他根据系统设置
29
-    **/    
31
+     **/
30 32
     public function _initialize()
31 33
     {
32 34
         $action = [
@@ -52,38 +54,40 @@ class Users extends ApiCommon
52 54
                 'querylist',
53 55
                 'starlist',
54 56
                 'copyrole',
55
-                'subordinate'
57
+                'subordinate',
58
+                'countnumofuser',
59
+                'setuserdept'
56 60
             ]
57 61
         ];
58
-        Hook::listen('check_auth',$action);
59
-
62
+        Hook::listen('check_auth', $action);
63
+        
60 64
         $request = Request::instance();
61
-        $a = strtolower($request->action());        
65
+        $a = strtolower($request->action());
62 66
         if (!in_array($a, $action['permission'])) {
63 67
             parent::_initialize();
64
-        }        
68
+        }
65 69
     }
66
-
70
+    
67 71
     /**
68 72
      * 员工列表
69
-     * @param 
73
+     * @param
70 74
      * @return
71 75
      */
72 76
     public function index()
73
-    {   
77
+    {
74 78
         $userModel = model('User');
75
-        $param = $this->param;  
79
+        $param = $this->param;
76 80
         $data = $userModel->getDataList($param);
77 81
         return resultArray(['data' => $data]);
78 82
     }
79
-
83
+    
80 84
     /**
81 85
      * 员工详情
82
-     * @param 
86
+     * @param
83 87
      * @return
84 88
      */
85 89
     public function read()
86
-    {   
90
+    {
87 91
         $userModel = model('User');
88 92
         $param = $this->param;
89 93
         $userInfo = $this->userInfo;
@@ -92,30 +96,31 @@ class Users extends ApiCommon
92 96
         if (!$data) {
93 97
             return resultArray(['error' => $userModel->getError()]);
94 98
         }
95
-        $data['serverUserInfo'] = $this->queryLoginUser();
99
+        $serverUserInfo = $this->queryLoginUser();
100
+        if (!empty($serverUserInfo)) $data['serverUserInfo'] = $serverUserInfo;
96 101
         return resultArray(['data' => $data]);
97 102
     }
98
-
103
+    
99 104
     /**
100 105
      * 员工创建
101
-     * @param 
106
+     * @param
102 107
      * @return
103
-     */    
108
+     */
104 109
     public function save()
105 110
     {
106 111
         $userModel = model('User');
107 112
         $param = $this->param;
108
-		$userInfo = $this->userInfo;
113
+        $userInfo = $this->userInfo;
109 114
         $data = $userModel->createData($param);
110 115
         if (!$data) {
111 116
             return resultArray(['error' => $userModel->getError()]);
112 117
         }
113 118
         return resultArray(['data' => '添加成功']);
114 119
     }
115
-
120
+    
116 121
     /**
117 122
      * 员工编辑
118
-     * @param 
123
+     * @param
119 124
      * @return
120 125
      */
121 126
     public function update()
@@ -131,8 +136,8 @@ class Users extends ApiCommon
131 136
             //权限判断
132 137
             if (!checkPerByAction('admin', 'users', 'update')) {
133 138
                 header('Content-Type:application/json; charset=utf-8');
134
-                exit(json_encode(['code'=>102,'error'=>'无权操作']));
135
-            }             
139
+                exit(json_encode(['code' => 102, 'error' => '无权操作']));
140
+            }
136 141
         }
137 142
         unset($param['username']);
138 143
         $data = $userModel->updateDataById($param, $param['id']);
@@ -142,30 +147,30 @@ class Users extends ApiCommon
142 147
         $param['userInfo'] = $userData;
143 148
         $resSync = model('Sync')->syncData($param);
144 149
         return resultArray(['data' => '编辑成功']);
145
-    }    
146
-
147
-	//批量设置密码
148
-	public function updatePwd()
149
-	{
150
+    }
151
+    
152
+    //批量设置密码
153
+    public function updatePwd()
154
+    {
150 155
         //权限判断
151 156
         if (!checkPerByAction('admin', 'users', 'update')) {
152 157
             header('Content-Type:application/json; charset=utf-8');
153
-            exit(json_encode(['code'=>102,'error'=>'无权操作']));
154
-        }         
155
-		$param = $this->param;
156
-		if ($param['password'] && is_array($param['id'])) {
157
-			$userModel = model('User');
158
-			$ret = $userModel->updatePwdById($param);
159
-			if ($ret) {
160
-				return resultArray(['data'=>true]);
161
-			} else {
162
-				return resultArray(['error'=>$userModel->getError()]);
163
-			}
164
-		} else {
165
-			return resultArray(['error'=>'参数错误']);
166
-		}
167
-	}
168
-	
158
+            exit(json_encode(['code' => 102, 'error' => '无权操作']));
159
+        }
160
+        $param = $this->param;
161
+        if ($param['password'] && is_array($param['id'])) {
162
+            $userModel = model('User');
163
+            $ret = $userModel->updatePwdById($param);
164
+            if ($ret) {
165
+                return resultArray(['data' => true]);
166
+            } else {
167
+                return resultArray(['error' => $userModel->getError()]);
168
+            }
169
+        } else {
170
+            return resultArray(['error' => '参数错误']);
171
+        }
172
+    }
173
+    
169 174
     /**
170 175
      * 员工状态
171 176
      * @param status   0禁用,1启用,2禁止登陆,3未激活
@@ -181,102 +186,114 @@ class Users extends ApiCommon
181 186
             $ids = $param['id'];
182 187
         }
183 188
         //顶级管理员不能修改
184
-        foreach ($ids as $k=>$v) {
189
+        foreach ($ids as $k => $v) {
185 190
             if ((int)$v == 1 && $param['status'] == '0') {
186 191
                 unset($ids[$k]);
187 192
             }
188 193
         }
189
-        $data = $userModel->enableDatas($ids, $param['status']);  
194
+        $data = $userModel->enableDatas($ids, $param['status']);
190 195
         if (!$data) {
191 196
             return resultArray(['error' => $userModel->getError()]);
192
-        } 
193
-        return resultArray(['data' => '操作成功']);         
197
+        }
198
+        # 添加记录
199
+        if ($param['status'] == 0) {
200
+            $content = '禁用了:';
201
+        } elseif ($param['status'] == 1) {
202
+            $content = '激活了:';
203
+        }
204
+        $user = new ApiCommon();
205
+        $userInfo = $user->userInfo;
206
+        foreach ($ids as $key => $val) {
207
+            $dataInfo = db('admin_user')->where('id', $val)->find();
208
+            SystemActionLog($userInfo['id'], 'admin_user', 'employee', $val, 'update', '员工状态', '', '', $content . $dataInfo['realname']);
209
+        }
210
+        return resultArray(['data' => '操作成功']);
194 211
     }
195
-
212
+    
196 213
     /**
197 214
      * 获取权限范围内的员工数组
198
-     * @param  
215
+     * @param
199 216
      * @return
200 217
      */
201 218
     public function getUserList()
202 219
     {
203 220
         $userModel = model('User');
204 221
         $param = $this->param;
205
-        $by = $param['by'] ? : '';
206
-        $user_id = $param['user_id'] ? : '';
222
+        $by = $param['by'] ?: '';
223
+        $user_id = $param['user_id'] ?: '';
207 224
         $where = [];
208 225
         $belowIds = [];
209 226
         if ($param['m'] && $param['c'] && $param['a']) {
210 227
             if ($param['m'] == 'oa' && $param['c'] == 'task') {
211
-               $belowIds = getSubUserId(true, 1); 
228
+                $belowIds = getSubUserId(true, 1);
212 229
             } else {
213 230
                 $belowIds = $userModel->getUserByPer($param['m'], $param['c'], $param['a']);
214 231
             }
215
-            $where['user.id'] = ['in',$belowIds];
232
+            $where['user.id'] = ['in', $belowIds];
216 233
         } else {
217 234
             if ($by == 'sub') {
218 235
                 $userInfo = $this->userInfo;
219 236
                 $adminIds = $userModel->getAdminId();
220
-                if (in_array($userInfo['id'],$adminIds)) {
237
+                if (in_array($userInfo['id'], $adminIds)) {
221 238
                     $belowIds = getSubUserId(true, 1);
222 239
                 } else {
223 240
                     //下属id
224 241
                     $belowIds = getSubUserId();
225
-                } 
226
-                $where['user.id'] = ['in',$belowIds];
242
+                }
243
+                $where['user.id'] = ['in', $belowIds];
227 244
             } elseif ($by == 'parent') {
228 245
                 if ($user_id == 1) {
229 246
                     $where['user.id'] = 0;
230 247
                 } else {
231 248
                     $unUserId[] = $user_id;
232 249
                     $subUserId = getSubUser($user_id);
233
-                    $unUserId = $subUserId ? array_merge($subUserId,$unUserId) : $unUserId;
250
+                    $unUserId = $subUserId ? array_merge($subUserId, $unUserId) : $unUserId;
234 251
                 }
235
-                $where['user.id'] = ['not in',$unUserId];  
252
+                $where['user.id'] = ['not in', $unUserId];
236 253
             } else {
237 254
                 $belowIds = getSubUserId(true, 1);
238
-                $where['user.id'] = ['in',$belowIds];     
255
+                $where['user.id'] = ['in', $belowIds];
239 256
             }
240 257
         }
241 258
         $userList = db('admin_user')
242
-                    ->alias('user')
243
-                    ->where($where)
244
-                    ->where('user.status>0 and user.type=1')
245
-                    ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
246
-                    ->field('user.id,user.realname,user.thumb_img,structure.name as s_name')
247
-                    ->select();
248
-
259
+            ->alias('user')
260
+            ->where($where)
261
+            ->where('user.status>0 and user.type=1')
262
+            ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
263
+            ->field('user.id,user.realname,user.thumb_img,structure.name as s_name')
264
+            ->select();
265
+        
249 266
         # 角色数据
250 267
         $groupList = db('admin_access')->alias('access')
251
-                    ->join('__ADMIN_GROUP__ group', 'group.id = access.group_id', 'LEFT')
252
-                    ->field('group.id, group.title, access.user_id')->select();
268
+            ->join('__ADMIN_GROUP__ group', 'group.id = access.group_id', 'LEFT')
269
+            ->field('group.id, group.title, access.user_id')->select();
253 270
         $groupArray = [];
254
-        foreach ($groupList AS $key => $value) {
271
+        foreach ($groupList as $key => $value) {
255 272
             $groupArray[$value['user_id']]['roleId'][] = $value['id'];
256 273
             $groupArray[$value['user_id']]['roleName'][] = $value['title'];
257 274
         }
258
-
259
-        foreach ($userList as $k=>$v) {
260
-            $userList[$k]['username']  = $v['realname'];
275
+        
276
+        foreach ($userList as $k => $v) {
277
+            $userList[$k]['username'] = $v['realname'];
261 278
             $userList[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
262
-
279
+            
263 280
             # 员工新增角色ID和角色名称字段
264
-            $userList[$k]['roleId']    = !empty($groupArray[$v['id']]['roleId']) ? implode(',', $groupArray[$v['id']]['roleId']) : '';
265
-            $userList[$k]['roleName']  = !empty($groupArray[$v['id']]['roleName']) ? implode(',', $groupArray[$v['id']]['roleName']) : '';
281
+            $userList[$k]['roleId'] = !empty($groupArray[$v['id']]['roleId']) ? implode(',', $groupArray[$v['id']]['roleId']) : '';
282
+            $userList[$k]['roleName'] = !empty($groupArray[$v['id']]['roleName']) ? implode(',', $groupArray[$v['id']]['roleName']) : '';
266 283
             # 单独处理admin管理员的角色ID和角色名称字段
267 284
             if ($v['id'] == 1 && (empty($groupArray[$v['id']]['roleId']) || empty($groupArray[$v['id']]['roleName']))) {
268
-                $userList[$k]['roleId']   = '1';
285
+                $userList[$k]['roleId'] = '1';
269 286
                 $userList[$k]['roleName'] = '超级管理员角色';
270 287
             }
271 288
         }
272
-        return resultArray(['data' => $userList ? : []]); 
289
+        return resultArray(['data' => $userList ?: []]);
273 290
     }
274
-
291
+    
275 292
     /**
276 293
      * 修改头像
277
-     * @param 
294
+     * @param
278 295
      * @return
279
-     */ 
296
+     */
280 297
     public function updateImg()
281 298
     {
282 299
         $fileModel = model('File');
@@ -285,41 +302,41 @@ class Users extends ApiCommon
285 302
         //处理图片
286 303
         header('Access-Control-Allow-Origin: *');
287 304
         header('Access-Control-Allow-Methods: POST');
288
-        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); 
305
+        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
289 306
         $param['file'] = request()->file('file');
290
-		
307
+        
291 308
         $resImg = $fileModel->updateByField($param['file'], 'User', $param['id'], 'img', 'thumb_img', 150, 150);
292 309
         if (!$resImg) {
293 310
             return resultArray(['error' => $fileModel->getError()]);
294 311
         }
295 312
         return resultArray(['data' => '上传成功']);
296 313
     }
297
-
314
+    
298 315
     /**
299 316
      * 重置密码
300
-     * @param 
317
+     * @param
301 318
      * @return
302
-     */     
319
+     */
303 320
     public function resetPassword()
304
-    {   
321
+    {
305 322
         $param = $this->param;
306 323
         $userInfo = $this->userInfo;
307 324
         $userModel = model('User');
308
-
325
+        
309 326
         if (empty($param['new_pwd']) || empty($param['old_pwd'])) return resultArray(['error' => '密码不能为空!']);
310
-
327
+        
311 328
         if ($param['id'] && (int)$param['id'] !== $userInfo['id']) {
312 329
             //权限判断
313 330
             if (!checkPerByAction('admin', 'users', 'update')) {
314 331
                 header('Content-Type:application/json; charset=utf-8');
315
-                exit(json_encode(['code'=>102,'error'=>'无权操作']));
316
-            }  
332
+                exit(json_encode(['code' => 102, 'error' => '无权操作']));
333
+            }
317 334
             $user_id = $param['id'];
318 335
             if (!$param['new_pwd']) {
319 336
                 $this->error = '请输入重置密码';
320 337
                 return false;
321 338
             }
322
-
339
+            
323 340
             $userInfo = $userModel->getDataById($user_id);
324 341
             if (user_md5($param['new_pwd'], $userInfo['salt'], $userInfo['username']) == $userInfo['password']) {
325 342
                 $this->error = '密码没改变';
@@ -331,11 +348,13 @@ class Users extends ApiCommon
331 348
                 $syncData['user_id'] = $userInfo['id'];
332 349
                 $syncData['salt'] = $userInfo['salt'];
333 350
                 $syncData['password'] = user_md5($param['new_pwd'], $userInfo['salt'], $userInfo['username']);
334
-                $resSync = $syncModel->syncData($syncData);                
351
+                $resSync = $syncModel->syncData($syncData);
352
+                # 添加记录
353
+                SystemActionLog($userInfo['id'], 'admin_user', 'employee', $userInfo['id'],  'update', $userInfo['realname'], '', '', '重置了密码:' . $userInfo['realname']);
335 354
                 return resultArray(['data' => '密码重置成功']);
336 355
             } else {
337 356
                 return resultArray(['error' => '密码重置失败,请重试']);
338
-            }      
357
+            }
339 358
         } else {
340 359
             $userModel = model('User');
341 360
             $old_pwd = $param['old_pwd'];
@@ -343,14 +362,14 @@ class Users extends ApiCommon
343 362
             $data = $userModel->updatePaw($userInfo, $old_pwd, $new_pwd);
344 363
             if (!$data) {
345 364
                 return resultArray(['error' => $userModel->getError()]);
346
-            } 
347
-            return resultArray(['data' => $data]);            
365
+            }
366
+            return resultArray(['data' => $data]);
348 367
         }
349 368
     }
350
-
369
+    
351 370
     /**
352 371
      * 员工角色关系
353
-     * @param 
372
+     * @param
354 373
      * @return
355 374
      */
356 375
     public function groups()
@@ -358,8 +377,8 @@ class Users extends ApiCommon
358 377
         //权限判断
359 378
         if (!checkPerByAction('admin', 'groups', 'update')) {
360 379
             header('Content-Type:application/json; charset=utf-8');
361
-            exit(json_encode(['code'=>102,'error'=>'无权操作']));
362
-        }        
380
+            exit(json_encode(['code' => 102, 'error' => '无权操作']));
381
+        }
363 382
         $param = $this->param;
364 383
         if (!$param['users'] && !$param['structures']) {
365 384
             return resultArray(['error' => '请选择员工']);
@@ -373,7 +392,7 @@ class Users extends ApiCommon
373 392
         if (is_array($param['structures'])) {
374 393
             foreach ($param['structures'] as $v) {
375 394
                 $userArr[] = $userModel->getSubUserByStr($v);
376
-            }            
395
+            }
377 396
         }
378 397
         if ($userArr) $userArr = call_user_func_array('array_merge', $userArr); //数组合并
379 398
         if ($userArr && $param['users']) {
@@ -385,24 +404,29 @@ class Users extends ApiCommon
385 404
         }
386 405
         $userIds = array_unique($userIds);
387 406
         $groups = $param['groups'];
388
-        $accessModel = model('Access');       
407
+        $accessModel = model('Access');
389 408
         $resData = true;
390
-        foreach ($userIds as $k=>$v) {
409
+        $user_id = $this->userInfo;
410
+        foreach ($userIds as $k => $v) {
391 411
             //角色员工关系处理
392 412
             $res = $accessModel->userGroup($v, $param['groups']);
393 413
             if (!$res) {
394 414
                 $resData = false;
395
-            }            
415
+            }
416
+            $userInfo = Db::name('admin_user')->where('id', $v)->find();
417
+            $user_id=$this->userInfo;
418
+            SystemActionLog($user_id['id'], 'admin_user', 'employee', $v,  'update', $userInfo['realname'], '', '', '员工关联了角色:' . $userInfo['realname']);
419
+            
396 420
         }
397 421
         // if ($resData == false) {
398 422
         //     return resultArray(['error' => '操作失败,请重试']);      
399 423
         // }
400
-        return resultArray(['data' => '创建成功']);       
424
+        return resultArray(['data' => '创建成功']);
401 425
     }
402
-
426
+    
403 427
     /**
404 428
      * 员工角色关系(删除)
405
-     * @param 
429
+     * @param
406 430
      * @return
407 431
      */
408 432
     public function groupsDel()
@@ -410,8 +434,8 @@ class Users extends ApiCommon
410 434
         //权限判断
411 435
         if (!checkPerByAction('admin', 'groups', 'update')) {
412 436
             header('Content-Type:application/json; charset=utf-8');
413
-            exit(json_encode(['code'=>102,'error'=>'无权操作']));
414
-        }        
437
+            exit(json_encode(['code' => 102, 'error' => '无权操作']));
438
+        }
415 439
         $param = $this->param;
416 440
         if (!$param['user_id']) {
417 441
             return resultArray(['error' => '请选择员工']);
@@ -419,69 +443,70 @@ class Users extends ApiCommon
419 443
         if (!$param['group_id']) {
420 444
             return resultArray(['error' => '参数错误']);
421 445
         }
422
-
446
+        
423 447
         # 员工至少保留一个角色
424 448
         $count = db('admin_access')->where(['user_id' => $param['user_id']])->count();
425 449
         if ($count == 1) return resultArray(['error' => '员工至少保留一个角色!']);
426
-
427
-        $res = db('admin_access')->where(['user_id' => $param['user_id'],'group_id' => $param['group_id']])->delete();
450
+        
451
+        $res = db('admin_access')->where(['user_id' => $param['user_id'], 'group_id' => $param['group_id']])->delete();
428 452
         if (!$res) {
429
-            return resultArray(['error' => '操作失败,请重试']);      
453
+            return resultArray(['error' => '操作失败,请重试']);
430 454
         }
431
-        return resultArray(['data' => '删除成功']);         
455
+        return resultArray(['data' => '删除成功']);
432 456
     }
433
-
457
+    
434 458
     /**
435 459
      * [structureUserList 部门员工混合数据]
436
-     * @param 
460
+     * @param
437 461
      * @return
438
-     */ 
462
+     */
439 463
     public function structureUserList()
440 464
     {
441 465
         $structure_list = db('admin_structure')->select();
442 466
         $structureList = getSubObj(0, $structure_list, '', 1);
443
-        foreach ($structureList as $k=>$v) {
467
+        foreach ($structureList as $k => $v) {
444 468
             $userList = [];
445
-            $userList = db('admin_user')->where(['structure_id' => $v['id'],'status' => array('in',['1','3'])])->field('id,realname')->select();
469
+            $userList = db('admin_user')->where(['structure_id' => $v['id'], 'status' => array('in', ['1', '3'])])->field('id,realname')->select();
446 470
             $structureList[$k]['userList'] = $userList;
447 471
         }
448 472
         return $structureList;
449
-    }    
450
-	
451
-	//人资员工导入
452
-	public function tobeusers(){
453
-		$userModel = model('User');
454
-		$param = $this->param;
455
-		$flag = $userModel->beusers($param);
456
-		if ($flag) {
457
-			return resultArray(['data'=>$flag]);
458
-		} else {
459
-			return resultArray(['error'=>$userModel->getError()]);
460
-		}
461
-	}
462
-	
463
-	//根据部门ID获取员工列表
464
-	public function userListByStructId()
465
-	{
466
-		$usermodel = model('User');
467
-		$param = $this->param;
468
-		$structure_id = $param['structure_id']?:'';
469
-		$ret = $usermodel->getUserListByStructureId($structure_id) ? : [];
470
-        return resultArray(['data'=>$ret]);
471
-	}
472
-
473
+    }
474
+    
475
+    //人资员工导入
476
+    public function tobeusers()
477
+    {
478
+        $userModel = model('User');
479
+        $param = $this->param;
480
+        $flag = $userModel->beusers($param);
481
+        if ($flag) {
482
+            return resultArray(['data' => $flag]);
483
+        } else {
484
+            return resultArray(['error' => $userModel->getError()]);
485
+        }
486
+    }
487
+    
488
+    //根据部门ID获取员工列表
489
+    public function userListByStructId()
490
+    {
491
+        $usermodel = model('User');
492
+        $param = $this->param;
493
+        $structure_id = $param['structure_id'] ?: '';
494
+        $ret = $usermodel->getUserListByStructureId($structure_id) ?: [];
495
+        return resultArray(['data' => $ret]);
496
+    }
497
+    
473 498
     /**
474 499
      * 员工账号修改
475
-     * @param 
500
+     * @param
476 501
      * @return
477
-     */    
502
+     */
478 503
     public function usernameEdit()
479 504
     {
480 505
         //权限判断
481 506
         if (!checkPerByAction('admin', 'users', 'update')) {
482 507
             header('Content-Type:application/json; charset=utf-8');
483
-            exit(json_encode(['code'=>102,'error'=>'无权操作']));
484
-        }        
508
+            exit(json_encode(['code' => 102, 'error' => '无权操作']));
509
+        }
485 510
         $param = $this->param;
486 511
         $userInfo = $this->userInfo;
487 512
         //权限判断
@@ -489,17 +514,17 @@ class Users extends ApiCommon
489 514
             return resultArray(['error' => '管理员账号暂不能修改']);
490 515
         }
491 516
         $adminTypes = adminGroupTypes($userInfo['id']);
492
-        if (!in_array(3,$adminTypes) && !in_array(1,$adminTypes) && !in_array(2,$adminTypes)) {
517
+        if (!in_array(3, $adminTypes) && !in_array(1, $adminTypes) && !in_array(2, $adminTypes)) {
493 518
             header('Content-Type:application/json; charset=utf-8');
494
-            exit(json_encode(['code'=>102,'error'=>'无权操作']));
495
-        }         
519
+            exit(json_encode(['code' => 102, 'error' => '无权操作']));
520
+        }
496 521
         if (!$param['id'] || !$param['username'] || !$param['password']) {
497 522
             return resultArray(['error' => '参数错误!']);
498 523
         }
499
-        if (db('admin_user')->where(['id' => ['neq',$param['id']],'username' => $param['username']])->find()) {
524
+        if (db('admin_user')->where(['id' => ['neq', $param['id']], 'username' => $param['username']])->find()) {
500 525
             return resultArray(['error' => '手机号码已存在!']);
501 526
         }
502
-        $userData = db('admin_user')->where(['id' => $param['id']])->field('username,salt,password')->find();
527
+        $userData = db('admin_user')->where(['id' => $param['id']])->field('username,salt,password,realname')->find();
503 528
         $data = [];
504 529
         $data['username'] = $param['username'];
505 530
         $data['password'] = user_md5($param['password'], $userData['salt'], $param['username']);
@@ -509,12 +534,13 @@ class Users extends ApiCommon
509 534
         if ($resSync) {
510 535
             unset($data['userInfo']);
511 536
             $res = db('admin_user')->where(['id' => $param['id']])->update($data);
537
+            SystemActionLog($userInfo['id'], 'admin_user', 'employee', $param['id'], 'update', $userData['realname'], '', '', '员工账号修改:' . $userData['realname']);
512 538
             return resultArray(['data' => '修改成功!']);
513 539
         } else {
514 540
             return resultArray(['error' => '修改失败,请重试!']);
515 541
         }
516 542
     }
517
-
543
+    
518 544
     /**
519 545
      * 登录记录
520 546
      */
@@ -524,12 +550,12 @@ class Users extends ApiCommon
524 550
             header('Content-Type:application/json; charset=utf-8');
525 551
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
526 552
         }
527
-
553
+        
528 554
         $loginRecordModel = new LoginRecord();
529 555
         $where = [];
530 556
         getWhereUserByParam($where, 'create_user_id');
531 557
         getWhereTimeByParam($where, 'create_time');
532
-
558
+        
533 559
         $limit = $this->param['limit'] ?: 15;
534 560
         $data = $loginRecordModel
535 561
             ->where($where)
@@ -547,24 +573,24 @@ class Users extends ApiCommon
547 573
             ],
548 574
         ]);
549 575
     }
550
-
576
+    
551 577
     /**
552 578
      * 员工导入模板下载
553
-     * @author Michael_xu
554 579
      * @param string $save_path 本地保存路径     用于错误数据导出,在 Admin\Model\Excel::batchImportData()调用
555 580
      * @return
581
+     * @author Michael_xu
556 582
      */
557 583
     public function excelDownload($save_path = '')
558 584
     {
559 585
         $param = $this->param;
560 586
         $userInfo = $this->userInfo;
561 587
         $excelModel = new \app\admin\model\Excel();
562
-
588
+        
563 589
         // 导出的字段列表
564 590
         $field_list = UserModel::$import_field_list;
565 591
         $excelModel->excelImportDownload($field_list, 'admin_user', $save_path);
566 592
     }
567
-
593
+    
568 594
     /**
569 595
      * 员工导入
570 596
      */
@@ -580,16 +606,16 @@ class Users extends ApiCommon
580 606
         $param['types'] = 'admin_user';
581 607
         $file = request()->file('file');
582 608
         $res = $excelModel->batchImportData($file, $param, $this);
583
-        $list=[];
584
-        $list[]=$excelModel->getError();
585
-        $item=$list[0];
609
+        $list = [];
610
+        $list[] = $excelModel->getError();
611
+        $item = $list[0];
586 612
         if (!$res) {
587 613
             return resultArray(['data' => $item]);
588 614
         }
589 615
         Cache::clear('user_info');
590 616
         return resultArray(['data' => $item]);
591 617
     }
592
-
618
+    
593 619
     /**
594 620
      * 批量设置直属上级
595 621
      *
@@ -602,29 +628,29 @@ class Users extends ApiCommon
602 628
         if (false === UserModel::checkUserGroup([1, 2, 3])) {
603 629
             return resultArray(['error' => '没有该权限']);
604 630
         }
605
-        $parent_id = (int) $this->param['parent_id'];
631
+        $parent_id = (int)$this->param['parent_id'];
606 632
         $parent_user = UserModel::find($parent_id);
607 633
         if (!$parent_user) {
608 634
             return resultArray(['error' => '请选择直属上级']);
609 635
         }
610
-        $user_id_list = (array) $this->param['id_list'];
636
+        $user_id_list = (array)$this->param['id_list'];
611 637
         if (empty($user_id_list)) {
612 638
             return resultArray(['error' => '请选择员工']);
613 639
         }
614 640
         if (in_array(1, $user_id_list)) {
615 641
             return resultArray(['error' => '超级管理员不能设置上级']);
616 642
         }
617
-
643
+        
618 644
         if (in_array($parent_id, $user_id_list)) {
619 645
             return resultArray(['error' => '直属上级不能为员工自己']);
620 646
         }
621 647
         
622 648
         foreach ($user_id_list as $val) {
623
-            if (in_array($parent_id, getSubUserId(true, 0, (int) $val))) {
649
+            if (in_array($parent_id, getSubUserId(true, 0, (int)$val))) {
624 650
                 return resultArray(['error' => '直属上级不能是自己下属(包含下属的下属)']);
625 651
             }
626 652
         }
627
-
653
+        
628 654
         $a = new UserModel;
629 655
         if ($a->where(['id' => ['IN', $user_id_list]])->update(['parent_id' => $parent_id])) {
630 656
             Cache::clear('user_info');
@@ -633,33 +659,36 @@ class Users extends ApiCommon
633 659
             return resultArray(['error' => '员工直属上级设置失败' . $a->getError()]);
634 660
         }
635 661
     }
636
-
662
+    
637 663
     /**
638 664
      * 通讯录列表
639 665
      * @return mixed
640 666
      */
641
-    public function queryList(){
667
+    public function queryList()
668
+    {
642 669
         $param = $this->param;
643 670
         $userInfo = $this->userInfo;
644
-        $param['user_id']=$userInfo['id'];
645
-        $userLogic=new UserLogic();
646
-        $data=$userLogic->getDataList($param);
671
+        $param['user_id'] = $userInfo['id'];
672
+        $userLogic = new UserLogic();
673
+        $data = $userLogic->getDataList($param);
647 674
         return resultArray(['data' => $data]);
648
-
675
+        
649 676
     }
650
-
677
+    
651 678
     /**
652 679
      * 关注的通讯录列表
653 680
      * @return mixed
654 681
      */
655
-    public function starList(){
682
+    public function starList()
683
+    {
656 684
         $param = $this->param;
657 685
         $userInfo = $this->userInfo;
658
-        $param['user_id']=$userInfo['id'];
659
-        $userLogic=new UserLogic();
660
-        $data=$userLogic->queryList($param);
686
+        $param['user_id'] = $userInfo['id'];
687
+        $userLogic = new UserLogic();
688
+        $data = $userLogic->queryList($param);
661 689
         return resultArray(['data' => $data]);
662 690
     }
691
+    
663 692
     /**
664 693
      * 设置关注
665 694
      *
@@ -667,19 +696,19 @@ class Users extends ApiCommon
667 696
     public function userStar()
668 697
     {
669 698
         $userInfo = $this->userInfo;
670
-        $userId   =  $userInfo['id'];
699
+        $userId = $userInfo['id'];
671 700
         $targetId = $this->param['target_id'];
672
-        $type     = $this->param['type'];
673
-
701
+        $type = $this->param['type'];
702
+        
674 703
         if (empty($userId) || empty($targetId) || empty($type)) return resultArray(['error' => '缺少必要参数!']);
675
-
704
+        
676 705
         if (!$this->setStar($type, $userId, $targetId)) {
677 706
             return resultArray(['error' => '设置关注失败!']);
678 707
         }
679
-
708
+        
680 709
         return resultArray(['data' => '设置关注成功!']);
681 710
     }
682
-
711
+    
683 712
     /**
684 713
      * 复制员工角色
685 714
      *
@@ -688,17 +717,16 @@ class Users extends ApiCommon
688 717
     public function copyRole()
689 718
     {
690 719
         $param = $this->param;
691
-
692 720
         if (empty($param['user_id']) && empty($param['structure_id'])) return resultArray(['error' => '请选择员工或部门!']);
693 721
         if (empty($param['group_id'])) return resultArray(['error' => '请选择角色!']);
694
-
722
+        
695 723
         $userModel = new User();
696
-
724
+        
697 725
         if (!$userModel->copyRole($param)) return resultArray(['error' => '操作失败!']);
698
-
726
+        
699 727
         return resultArray(['data' => '操作成功!']);
700 728
     }
701
-
729
+    
702 730
     /**
703 731
      * 获取下属(全部层级)
704 732
      *
@@ -706,33 +734,79 @@ class Users extends ApiCommon
706 734
     public function subordinate()
707 735
     {
708 736
         $userId = $this->userInfo['id'];
709
-
737
+        
710 738
         # 获取下属的ID
711 739
         $subIds = getSubUserId(false, 0, $userId);
712
-
740
+        
713 741
         $data = Db::name('admin_user')->field(['id', 'realname', 'thumb_img as img'])->whereIn('id', $subIds)->select();
714
-
715
-        foreach ($data AS $key => $value) {
742
+        
743
+        foreach ($data as $key => $value) {
716 744
             $data[$key]['img'] = !empty($data[$key]['img']) ? getFullPath($data[$key]['img']) : '';
717 745
         }
718
-
746
+        
719 747
         return resultArray(['data' => $data]);
720 748
     }
721
-
749
+    
722 750
     /**
723 751
      * 获取当前登录人信息
724 752
      *
725
-     */    
753
+     */
726 754
     public function queryLoginUser()
727 755
     {
728 756
         $resData = [];
729
-        $wkcode = file_get_contents(CONF_PATH.'license.dat'); 
757
+        $wkcode = file_get_contents(CONF_PATH . 'license.dat');
730 758
         if ($wkcode) {
731 759
             $resCheckData = checkWkCode($wkcode);
732 760
             if ($resCheckData) {
733 761
                 $resData = object_to_array(json_decode($resCheckData));
734
-            }            
762
+            }
735 763
         }
736
-        return $resData;      
764
+        return $resData;
765
+    }
766
+    
767
+    /**
768
+     * 批量重设部门
769
+     *
770
+     * @author      alvin guogaobo
771
+     * @version     1.0 版本号
772
+     * @since       2021/4/15 0015 16:37
773
+     */
774
+    public function setUserDept()
775
+    {
776
+        //权限判断
777
+        // 仅允许超管,系统管理员,部门与员工管理员 导入
778
+        if (false === UserModel::checkUserGroup([1, 2, 3])) {
779
+            return resultArray(['error' => '没有该权限']);
780
+        }
781
+        $userModel = model('User');
782
+        $param = $this->param;
783
+        if (!is_array($param['id'])) {
784
+            $ids[] = $param['id'];
785
+        } else {
786
+            $ids = $param['id'];
787
+        }
788
+        $data = $userModel->setUserDept($ids, $param);
789
+        if (!$data) {
790
+            return resultArray(['error' => $userModel->getError()]);
791
+        }
792
+        # 添加记录
793
+        $userInfo = $this->userInfo;
794
+        foreach ($ids as $key => $val) {
795
+            $dataInfo = db('admin_user')->where('id', $val)->find();
796
+            SystemActionLog($userInfo['id'], 'admin_user', 'employee', $val, 'update',  $dataInfo['realname'], '', '','重置了部门: ' . $dataInfo['realname']);
797
+        }
798
+        return resultArray(['data' => '操作成功']);
799
+    }
800
+    
801
+    /**
802
+     * 员工分类后面跟的数据
803
+     * @author      alvin guogaobo
804
+     * @version     1.0 版本号
805
+     * @since       2021/4/24 0024 14:42
806
+     */
807
+    public function countNumOfUser(){
808
+        $userModel = model('User');
809
+        $data=$userModel->countNumOfUser();
810
+        return resultArray(['data' => $data['list']]);
737 811
     }
738 812
 }

+ 8
- 5
application/admin/controller/Work.php Zobrazit soubor

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

+ 8
- 8
application/admin/logic/DailyRuleLogic.php Zobrazit soubor

@@ -125,7 +125,7 @@ class DailyRuleLogic
125 125
             'userIds' => $param['userIds'],
126 126
             'start_time' => $param['start_time'],
127 127
             'end_time' => $param['end_time'],
128
-            'status' => $param['status']
128
+            'status' => $param['status']?:''
129 129
         ];
130 130
 
131 131
         if (Db::name('admin_oalog_rule')->where('type', 2)->value('id')) {
@@ -150,7 +150,7 @@ class DailyRuleLogic
150 150
             'userIds' => $param['userIds'],
151 151
             'start_time' => $param['start_time'],
152 152
             'end_time' => $param['end_time'],
153
-            'status' => $param['status']
153
+            'status' => $param['status']?:''
154 154
         ];
155 155
 
156 156
         if (Db::name('admin_oalog_rule')->where('type', 3)->value('id')) {
@@ -178,8 +178,8 @@ class DailyRuleLogic
178 178
             'userIds' => $day['userIds'],
179 179
             'user' => $this->getUsers($day['userIds']),
180 180
             'effective_day' => $day['effective_day'],
181
-            'start_time' => $day['start_time'],
182
-            'end_time' => $day['end_time']
181
+            'start_time' => $day['start_time']?:null,
182
+            'end_time' => $day['end_time']?:null
183 183
         ];
184 184
     }
185 185
 
@@ -201,8 +201,8 @@ class DailyRuleLogic
201 201
             'userIds' => $week['userIds'],
202 202
             'user' => $this->getUsers($week['userIds']),
203 203
             'effective_day' => $week['effective_day'],
204
-            'start_time' => $week['start_time'],
205
-            'end_time' => $week['end_time']
204
+            'start_time' => $week['start_time']?:1,
205
+            'end_time' => $week['end_time']?:3
206 206
         ];
207 207
     }
208 208
 
@@ -224,8 +224,8 @@ class DailyRuleLogic
224 224
             'userIds' => $month['userIds'],
225 225
             'user' => $this->getUsers($month['userIds']),
226 226
             'effective_day' => $month['effective_day'],
227
-            'start_time' => $month['start_time'],
228
-            'end_time' => $month['end_time']
227
+            'start_time' => $month['start_time']?:1,
228
+            'end_time' => $month['end_time']?:3
229 229
         ];
230 230
     }
231 231
 

+ 269
- 165
application/admin/logic/FieldGrantLogic.php Zobrazit soubor

@@ -12,6 +12,43 @@ use think\Db;
12 12
 
13 13
 class FieldGrantLogic
14 14
 {
15
+    private $except = [
16
+        'leads' => [
17
+            'name', 'email', 'source', 'mobile', 'telephone', 'detail_address', 'industry', 'level', 'next_time',
18
+            'remark', 'owner_user_id', 'last_record', 'create_user_id', 'create_time', 'update_time', 'last_time'
19
+        ],
20
+        'customer' => [
21
+            'name', 'source', 'mobile', 'telephone', 'website', 'industry', 'level', 'next_time', 'remark', 'email',
22
+            'owner_user_id', 'last_record', 'create_user_id', 'create_time', 'update_time', 'last_time', 'obtain_time',
23
+            'deal_status', 'is_lock', 'pool_day'
24
+        ],
25
+        'contacts' => [
26
+            'name', 'customer_id', 'mobile', 'telephone', 'email', 'post', 'decision', 'detail_address', 'next_time',
27
+            'remark', 'sex', 'owner_user_id', 'create_user_id', 'create_time', 'update_time', 'last_time', 'last_record'
28
+        ],
29
+        'business' => [
30
+            'name', 'customer_id', 'money', 'deal_date', 'remark', 'status_id', 'type_id', 'owner_user_id',
31
+            'create_user_id', 'create_time', 'update_time', 'last_time', 'last_record'
32
+        ],
33
+        'contract' => [
34
+            'name', 'num', 'customer_id', 'business_id', 'money', 'order_date', 'start_time', 'end_time', 'contacts_id',
35
+            'order_user_id', 'remark', 'owner_user_id', 'create_user_id', 'create_time', 'update_time', 'last_time',
36
+            'last_record', 'done_money', 'un_money', 'check_status'
37
+        ],
38
+        'receivables' => [
39
+            'number', 'customer_id', 'contract_id', 'plan_id', 'return_time', 'money', 'return_type', 'remark',
40
+            'owner_user_id', 'create_user_id', 'create_time', 'update_time', 'check_status'
41
+        ],
42
+        'product' => [
43
+            'name', 'category_id', 'unit', 'num', 'price', 'description', 'status', 'owner_user_id', 'create_user_id',
44
+            'create_time', 'update_time'
45
+        ],
46
+        'visit' => [
47
+            'number', 'visit_time', 'owner_user_id', 'shape', 'customer_id', 'contacts_id', 'contract_id', 'satisfaction',
48
+            'feedback', 'create_user_id', 'create_time', 'update_time'
49
+        ]
50
+    ];
51
+
15 52
     /**
16 53
      * 字段授权列表
17 54
      *
@@ -43,20 +80,6 @@ class FieldGrantLogic
43 80
         return !empty($data) ? $data : [];
44 81
     }
45 82
 
46
-    /**
47
-     * 更新授权字段
48
-     *
49
-     * @param $grantId
50
-     * @param $content
51
-     * @return int|string
52
-     * @throws \think\Exception
53
-     * @throws \think\exception\PDOException
54
-     */
55
-    public function update($grantId, $content)
56
-    {
57
-        return Db::name('admin_field_grant')->where('grant_id', $grantId)->update(['content' => serialize(array_values($content))]);
58
-    }
59
-
60 83
     /**
61 84
      * 添加字段授权信息
62 85
      *
@@ -76,7 +99,7 @@ class FieldGrantLogic
76 99
         # 添加商机字段授权数据
77 100
         $this->createBusinessFieldGrant($roleId);
78 101
         # 添加合同字段授权数据
79
-        $this->createContractfieldGrant($roleId);
102
+        $this->createContractFieldGrant($roleId);
80 103
         # 添加回款字段授权数据
81 104
         $this->createReceivablesFieldGrant($roleId);
82 105
         # 添加产品字段授权信息
@@ -85,6 +108,20 @@ class FieldGrantLogic
85 108
         $this->createVisitFieldGrant($roleId);
86 109
     }
87 110
 
111
+    /**
112
+     * 更新授权字段
113
+     *
114
+     * @param $grantId
115
+     * @param $content
116
+     * @return int|string
117
+     * @throws \think\Exception
118
+     * @throws \think\exception\PDOException
119
+     */
120
+    public function update($grantId, $content)
121
+    {
122
+        return Db::name('admin_field_grant')->where('grant_id', $grantId)->update(['content' => serialize(array_values($content))]);
123
+    }
124
+
88 125
     /**
89 126
      * 删除授权字段数据
90 127
      *
@@ -149,6 +186,9 @@ class FieldGrantLogic
149 186
         $fieldBaseData = [];
150 187
         $fieldList = Db::name('admin_field')->field(['name', 'field'])->where('types', $types)->select();
151 188
         foreach ($fieldList AS $key => $value) {
189
+            # 排除掉固定字段
190
+            if (in_array($value['field'], $this->except[$typesArray[1]])) continue;
191
+
152 192
             $fieldBaseData[$value['field']] = $value;
153 193
         }
154 194
 
@@ -168,9 +208,8 @@ class FieldGrantLogic
168 208
                     # 【处理删除:】没有在$fieldData找到,说明自定义字段被删除,则进行同步删除。
169 209
                     unset($content[(int)$k]);
170 210
                 } else {
171
-
172 211
                     # 【处理更新:】如果在$fieldData找到,则进行同步更新。
173
-                    $content[$k]['name'] = $fieldData[$v['field']]['name'];
212
+                    $content[$k]['name']  = $fieldData[$v['field']]['name'];
174 213
                     $content[$k]['field'] = $fieldData[$v['field']]['field'];
175 214
 
176 215
                     # 删除$fieldData的数据,方便统计新增的自定义字段。
@@ -194,7 +233,6 @@ class FieldGrantLogic
194 233
                 }
195 234
             }
196 235
 
197
-            # todo 暂时将数据库操作写在循环中!!!
198 236
             Db::name('admin_field_grant')->where('grant_id', $value['grant_id'])->update(['content' => serialize(array_values($content))]);
199 237
         }
200 238
 
@@ -202,39 +240,51 @@ class FieldGrantLogic
202 240
     }
203 241
 
204 242
     /**
205
-     * 添加线索字段授权数据
243
+     * 处理线索字段授权数据
206 244
      *
207
-     * @param $roleId
208
-     * @throws \think\db\exception\DataNotFoundException
209
-     * @throws \think\db\exception\ModelNotFoundException
210
-     * @throws \think\exception\DbException
245
+     * @param int $roleId 角色ID
246
+     * @author fanqi
247
+     * @date 2021-03-22
211 248
      */
212 249
     private function createLeadsFieldGrant($roleId)
213 250
     {
214
-        $content = [];
251
+        # 固定字段
252
+        $content = [
253
+            ['field' => 'name',           'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '线索名称'],
254
+            ['field' => 'email',          'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '邮箱'],
255
+            ['field' => 'source',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '线索来源'],
256
+            ['field' => 'mobile',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '手机'],
257
+            ['field' => 'telephone',      'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '电话'],
258
+            ['field' => 'detail_address', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '地址'],
259
+            ['field' => 'industry',       'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户行业'],
260
+            ['field' => 'level',          'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户级别'],
261
+            ['field' => 'next_time',      'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '下次联系时间'],
262
+            ['field' => 'remark',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
263
+            ['field' => 'owner_user_id',  'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
264
+            ['field' => 'last_record',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进记录'],
265
+            ['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
266
+            ['field' => 'create_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
267
+            ['field' => 'update_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
268
+            ['field' => 'last_time',      'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进时间'],
269
+        ];
215 270
 
216 271
         $leadsList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_leads')->select();
217 272
 
218
-        # 处理自定义字段
273
+        # 自定义字段
219 274
         foreach ($leadsList AS $key => $value) {
275
+            if (in_array($value['field'], $this->except['leads'])) continue;
276
+
220 277
             $content[] = [
221 278
                 'name'            => $value['name'],
222 279
                 'field'           => $value['field'],
223 280
                 'read'            => 1,
224
-                'read_operation'  => in_array($value['field'], ['name', 'next_time']) ? 0 : 1,
281
+                'read_operation'  => 1,
225 282
                 'write'           => 1,
226
-                'write_operation' => $value['field'] == 'next_time' ? 0 : 1,
283
+                'write_operation' => 1,
227 284
                 'is_diy'          => 1
228 285
             ];
229 286
         }
230 287
 
231
-        # 处理固定字段
232
-        $content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
233
-        $content[] = ['name' => '最后跟进记录', 'field' => 'record', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
234
-        $content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
235
-        $content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
236
-        $content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
237
-
238 288
         Db::name('admin_field_grant')->insert([
239 289
             'role_id'     => $roleId,
240 290
             'module'      => 'crm',
@@ -246,44 +296,55 @@ class FieldGrantLogic
246 296
     }
247 297
 
248 298
     /**
249
-     * 添加客户字段授权数据
299
+     * 处理客户字段授权数据
250 300
      *
251
-     * @param $roleId
252
-     * @throws \think\db\exception\DataNotFoundException
253
-     * @throws \think\db\exception\ModelNotFoundException
254
-     * @throws \think\exception\DbException
301
+     * @param int $roleId 角色ID
302
+     * @author fanqi
303
+     * @date 2021-03-22
255 304
      */
256 305
     private function createCustomerFieldGrant($roleId)
257 306
     {
258
-        $content = [];
307
+        # 固定字段
308
+        $content = [
309
+            ['field' => 'name',           'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户名称'],
310
+            ['field' => 'source',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户来源'],
311
+            ['field' => 'mobile',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '手机'],
312
+            ['field' => 'telephone',      'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '电话'],
313
+            ['field' => 'website',        'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '网址'],
314
+            ['field' => 'industry',       'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户行业'],
315
+            ['field' => 'level',          'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户级别'],
316
+            ['field' => 'next_time',      'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '下次联系时间'],
317
+            ['field' => 'remark',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
318
+            ['field' => 'email',          'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '邮箱'],
319
+            ['field' => 'owner_user_id',  'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
320
+            ['field' => 'last_record',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进记录'],
321
+            ['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
322
+            ['field' => 'create_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
323
+            ['field' => 'update_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
324
+            ['field' => 'last_time',      'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进时间'],
325
+            ['field' => 'obtain_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人获取客户时间'],
326
+            ['field' => 'deal_status',    'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '成交状态'],
327
+            ['field' => 'is_lock',        'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '锁定状态'],
328
+            ['field' => 'pool_day',       'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '距进入公海天数'],
329
+        ];
259 330
 
260 331
         $customerList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_customer')->select();
261 332
 
262
-        # 处理自定义字段
333
+        # 自定义字段
263 334
         foreach ($customerList AS $key => $value) {
335
+            if (in_array($value['field'], $this->except['customer'])) continue;
336
+
264 337
             $content[] = [
265 338
                 'name'            => $value['name'],
266 339
                 'field'           => $value['field'],
267 340
                 'read'            => 1,
268
-                'read_operation'  => in_array($value['field'], ['name', 'deal_status']) ? 0 : 1,
341
+                'read_operation'  => 1,
269 342
                 'write'           => 1,
270
-                'write_operation' => $value['field'] == 'deal_status' ? 0 : 1,
343
+                'write_operation' => 1,
344
+                'is_diy'          => 1
271 345
             ];
272 346
         }
273 347
 
274
-        # 处理固定字段
275
-        $content[] = ['name' => '合同编号', 'field' => 'contract', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
276
-        $content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0];
277
-        $content[] = ['name' => '最后跟进记录', 'field' => 'record', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
278
-        $content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
279
-        $content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
280
-        $content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
281
-        $content[] = ['name' => '最后跟进时间', 'field' => 'record_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
282
-        $content[] = ['name' => '负责人获取客户时间', 'field' => 'deal_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
283
-        $content[] = ['name' => '成交状态', 'field' => 'deal_status', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0];
284
-        $content[] = ['name' => '锁定状态', 'field' => 'is_lock', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
285
-        $content[] = ['name' => '距进入公海天数', 'field' => 'pool_day', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0];
286
-
287 348
         Db::name('admin_field_grant')->insert([
288 349
             'role_id'     => $roleId,
289 350
             'module'      => 'crm',
@@ -295,38 +356,51 @@ class FieldGrantLogic
295 356
     }
296 357
 
297 358
     /**
298
-     * 添加联系人字段授权数据
359
+     * 处理联系人字段授权数据
299 360
      *
300
-     * @param $roleId
301
-     * @throws \think\db\exception\DataNotFoundException
302
-     * @throws \think\db\exception\ModelNotFoundException
303
-     * @throws \think\exception\DbException
361
+     * @param int $roleId 角色ID
362
+     * @author fanqi
363
+     * @date 2021-03-22
304 364
      */
305 365
     private function createContactsFieldGrant($roleId)
306 366
     {
307
-        $content = [];
367
+        # 固定字段
368
+        $content = [
369
+            ['field' => 'name',           'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '姓名'],
370
+            ['field' => 'customer_id',    'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '客户名称'],
371
+            ['field' => 'mobile',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '手机'],
372
+            ['field' => 'telephone',      'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '电话'],
373
+            ['field' => 'email',          'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '邮箱'],
374
+            ['field' => 'post',           'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '职务'],
375
+            ['field' => 'decision',       'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '是否关键决策人'],
376
+            ['field' => 'detail_address', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '地址'],
377
+            ['field' => 'next_time',      'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '下次联系时间'],
378
+            ['field' => 'remark',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
379
+            ['field' => 'sex',            'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '性别'],
380
+            ['field' => 'owner_user_id',  'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
381
+            ['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
382
+            ['field' => 'create_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
383
+            ['field' => 'update_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
384
+            ['field' => 'last_time',      'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进时间'],
385
+        ];
308 386
 
309 387
         $contactsList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_contacts')->select();
310 388
 
311
-        # 处理自定义字段
389
+        # 自定义字段
312 390
         foreach ($contactsList AS $key => $value) {
391
+            if (in_array($value['field'], $this->except['contacts'])) continue;
392
+
313 393
             $content[] = [
314 394
                 'name'            => $value['name'],
315 395
                 'field'           => $value['field'],
316 396
                 'read'            => 1,
317
-                'read_operation'  => in_array($value['field'], ['name', 'next_time']) ? 0 : 1,
397
+                'read_operation'  => 1,
318 398
                 'write'           => 1,
319
-                'write_operation' => $value['field'] == 'next_time' ? 0 : 1,
399
+                'write_operation' => 1,
320 400
                 'is_diy'          => 1
321 401
             ];
322 402
         }
323 403
 
324
-        # 处理固定字段
325
-        $content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
326
-        $content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
327
-        $content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
328
-        $content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
329
-
330 404
         Db::name('admin_field_grant')->insert([
331 405
             'role_id'     => $roleId,
332 406
             'module'      => 'crm',
@@ -338,39 +412,47 @@ class FieldGrantLogic
338 412
     }
339 413
 
340 414
     /**
341
-     * 添加商机字段授权数据
415
+     * 处理商机字段授权数据
342 416
      *
343
-     * @param $roleId
344
-     * @throws \think\db\exception\DataNotFoundException
345
-     * @throws \think\db\exception\ModelNotFoundException
346
-     * @throws \think\exception\DbException
417
+     * @param int $roleId 角色ID
418
+     * @author fanqi
419
+     * @date 2021-03-22
347 420
      */
348 421
     private function createBusinessFieldGrant($roleId)
349 422
     {
350
-        $content = [];
423
+        # 固定字段
424
+        $content = [
425
+            ['field' => 'name',           'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '商机名称'],
426
+            ['field' => 'customer_id',    'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '客户名称'],
427
+            ['field' => 'money',          'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '商机金额'],
428
+            ['field' => 'deal_date',      'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '预计成交日期'],
429
+            ['field' => 'remark',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
430
+            ['field' => 'status_id',      'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '商机阶段'],
431
+            ['field' => 'type_id',        'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '商机状态组'],
432
+            ['field' => 'owner_user_id',  'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
433
+            ['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
434
+            ['field' => 'create_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
435
+            ['field' => 'update_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
436
+            ['field' => 'last_time',      'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进时间'],
437
+        ];
351 438
 
352 439
         $BusinessList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_business')->select();
353 440
 
354
-        # 处理自定义字段
441
+        # 自定义字段
355 442
         foreach ($BusinessList AS $key => $value) {
443
+            if (in_array($value['field'], $this->except['business'])) continue;
444
+
356 445
             $content[] = [
357 446
                 'name'            => $value['name'],
358 447
                 'field'           => $value['field'],
359 448
                 'read'            => 1,
360
-                'read_operation'  => in_array($value['field'], ['customer_id', 'type_id', 'status_id']) == '' ? 0 : 1,
449
+                'read_operation'  => 1,
361 450
                 'write'           => 1,
362
-                'write_operation' => in_array($value['field'], ['customer_id', 'type_id', 'status_id']) ? 0 : 1,
451
+                'write_operation' => 1,
363 452
                 'is_diy'          => 1
364 453
             ];
365 454
         }
366 455
 
367
-        # 处理固定字段
368
-        $content[] = ['name' => '整单折扣', 'field' => 'discount_rate', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
369
-        $content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
370
-        $content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
371
-        $content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
372
-        $content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
373
-
374 456
         Db::name('admin_field_grant')->insert([
375 457
             'role_id'     => $roleId,
376 458
             'module'      => 'crm',
@@ -382,43 +464,55 @@ class FieldGrantLogic
382 464
     }
383 465
 
384 466
     /**
385
-     * 添加合同字段授权数据
467
+     * 处理合同字段授权数据
386 468
      *
387
-     * @param $roleId
388
-     * @throws \think\db\exception\DataNotFoundException
389
-     * @throws \think\db\exception\ModelNotFoundException
390
-     * @throws \think\exception\DbException
469
+     * @param int $roleId 角色ID
470
+     * @author fanqi
471
+     * @date 2021-03-22
391 472
      */
392
-    private function createContractfieldGrant($roleId)
473
+    private function createContractFieldGrant($roleId)
393 474
     {
394
-        $content = [];
475
+        # 固定字段
476
+        $content = [
477
+            ['field' => 'name',           'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同名称'],
478
+            ['field' => 'num',            'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同编号'],
479
+            ['field' => 'customer_id',    'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户名称'],
480
+            ['field' => 'business_id',    'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '商机名称'],
481
+            ['field' => 'money',          'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同金额'],
482
+            ['field' => 'order_date',     'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '下单时间'],
483
+            ['field' => 'start_time',     'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同开始时间'],
484
+            ['field' => 'end_time',       'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同结束时间'],
485
+            ['field' => 'contacts_id',    'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户签约人'],
486
+            ['field' => 'order_user_id',  'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '公司签约人'],
487
+            ['field' => 'remark',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
488
+            ['field' => 'owner_user_id',  'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
489
+            ['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
490
+            ['field' => 'create_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
491
+            ['field' => 'update_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
492
+            ['field' => 'last_time',      'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进时间'],
493
+            ['field' => 'last_record',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '最后跟进记录'],
494
+            ['field' => 'done_money',     'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '已收款金额'],
495
+            ['field' => 'un_money',       'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '未收款金额'],
496
+            ['field' => 'check_status',   'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '审核状态'],
497
+        ];
395 498
 
396 499
         $contractList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_contract')->select();
397 500
 
398
-        # 处理自定义字段
501
+        # 自定义字段
399 502
         foreach ($contractList AS $key => $value) {
503
+            if (in_array($value['field'], $this->except['contract'])) continue;
504
+
400 505
             $content[] = [
401 506
                 'name'            => $value['name'],
402 507
                 'field'           => $value['field'],
403 508
                 'read'            => 1,
404
-                'read_operation'  => $value['field'] == 'num' ? 0 : 1,
509
+                'read_operation'  => 1,
405 510
                 'write'           => 1,
406 511
                 'write_operation' => 1,
407 512
                 'is_diy'          => 1
408 513
             ];
409 514
         }
410 515
 
411
-        # 处理固定字段
412
-        $content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
413
-        $content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
414
-        $content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
415
-        $content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
416
-        $content[] = ['name' => '最后跟进记录', 'field' => 'record', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
417
-        $content[] = ['name' => '最后跟进记录', 'field' => 'record_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
418
-        $content[] = ['name' => '已收款金额', 'field' => 'received', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
419
-        $content[] = ['name' => '未收款金额', 'field' => 'uncollected', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
420
-        $content[] = ['name' => '审核状态', 'field' => 'check_status', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
421
-
422 516
         Db::name('admin_field_grant')->insert([
423 517
             'role_id'     => $roleId,
424 518
             'module'      => 'crm',
@@ -430,21 +524,38 @@ class FieldGrantLogic
430 524
     }
431 525
 
432 526
     /**
433
-     * 添加回款字段授权数据
527
+     * 处理回款字段授权数据
434 528
      *
435
-     * @param $roleId
436
-     * @throws \think\db\exception\DataNotFoundException
437
-     * @throws \think\db\exception\ModelNotFoundException
438
-     * @throws \think\exception\DbException
529
+     * @param int $roleId 角色ID
530
+     * @author fanqi
531
+     * @date 2021-03-22
439 532
      */
440 533
     private function createReceivablesFieldGrant($roleId)
441 534
     {
442
-        $content = [];
535
+        # 固定字段
536
+        $content = [
537
+            ['field' => 'number',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回款编号'],
538
+            ['field' => 'customer_id',    'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户名称'],
539
+            ['field' => 'contract_id',    'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '合同编号'],
540
+            ['field' => 'plan_id',        'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '期数'],
541
+            ['field' => 'return_time',    'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回款日期'],
542
+            ['field' => 'money',          'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回款金额'],
543
+            ['field' => 'return_type',    'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回款方式'],
544
+            ['field' => 'remark',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
545
+            ['field' => 'contract_money', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '合同金额'],
546
+            ['field' => 'owner_user_id',  'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
547
+            ['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
548
+            ['field' => 'create_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
549
+            ['field' => 'update_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
550
+            ['field' => 'check_status',   'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '审核状态'],
551
+        ];
443 552
 
444 553
         $receivablesList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_receivables')->select();
445 554
 
446
-        # 处理自定义字段
555
+        # 自定义字段
447 556
         foreach ($receivablesList AS $key => $value) {
557
+            if (in_array($value['field'], $this->except['receivables'])) continue;
558
+
448 559
             $content[] = [
449 560
                 'name'            => $value['name'],
450 561
                 'field'           => $value['field'],
@@ -456,14 +567,6 @@ class FieldGrantLogic
456 567
             ];
457 568
         }
458 569
 
459
-        # 处理固定字段
460
-        $content[] = ['name' => '合同金额', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
461
-        $content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
462
-        $content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
463
-        $content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
464
-        $content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
465
-        $content[] = ['name' => '审核状态', 'field' => 'check_status', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
466
-
467 570
         Db::name('admin_field_grant')->insert([
468 571
             'role_id'     => $roleId,
469 572
             'module'      => 'crm',
@@ -475,44 +578,46 @@ class FieldGrantLogic
475 578
     }
476 579
 
477 580
     /**
478
-     * 添加产品字段授权信息
581
+     * 处理产品字段授权信息
479 582
      *
480
-     * @param $roleId
481
-     * @throws \think\db\exception\DataNotFoundException
482
-     * @throws \think\db\exception\ModelNotFoundException
483
-     * @throws \think\exception\DbException
583
+     * @param int $roleId 角色ID
584
+     * @author fanqi
585
+     * @date 2021-03-22
484 586
      */
485 587
     private function createProductFieldGrant($roleId)
486 588
     {
487
-        $content = [];
589
+        # 固定字段
590
+        $content = [
591
+            ['field' => 'name',           'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '产品名称'],
592
+            ['field' => 'category_id',    'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '产品类型'],
593
+            ['field' => 'unit',           'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '产品单位'],
594
+            ['field' => 'num',            'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '产品编码'],
595
+            ['field' => 'price',          'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '价格'],
596
+            ['field' => 'description',    'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '产品描述'],
597
+            ['field' => 'status',         'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '是否上下架'],
598
+            ['field' => 'owner_user_id',  'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '负责人'],
599
+            ['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
600
+            ['field' => 'create_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
601
+            ['field' => 'update_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
602
+        ];
488 603
 
489 604
         $productList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_product')->select();
490 605
 
491
-        # 处理自定义字段
606
+        # 自定义字段
492 607
         foreach ($productList AS $key => $value) {
493
-            $readOperation  = 1;
494
-            $writeOperation = 1;
495
-
496
-            if (in_array($value['field'], ['name', 'category_id', 'unit', 'price', 'status'])) $readOperation = 0;
497
-            if (in_array($value['field'], ['status'])) $writeOperation = 0;
608
+            if (in_array($value['field'], $this->except['product'])) continue;
498 609
 
499 610
             $content[] = [
500 611
                 'name'            => $value['name'],
501 612
                 'field'           => $value['field'],
502 613
                 'read'            => 1,
503
-                'read_operation'  => $readOperation,
614
+                'read_operation'  => 1,
504 615
                 'write'           => 1,
505
-                'write_operation' => $writeOperation,
616
+                'write_operation' => 1,
506 617
                 'is_diy'          => 1
507 618
             ];
508 619
         }
509 620
 
510
-        # 处理固定字段
511
-        $content[] = ['name' => '负责人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
512
-        $content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
513
-        $content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
514
-        $content[] = ['name' => '更新时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
515
-
516 621
         Db::name('admin_field_grant')->insert([
517 622
             'role_id'     => $roleId,
518 623
             'module'      => 'crm',
@@ -524,21 +629,35 @@ class FieldGrantLogic
524 629
     }
525 630
 
526 631
     /**
527
-     * 添加回访字段授权信息
632
+     * 处理回访字段授权信息
528 633
      *
529
-     * @param $roleId
530
-     * @throws \think\db\exception\DataNotFoundException
531
-     * @throws \think\db\exception\ModelNotFoundException
532
-     * @throws \think\exception\DbException
634
+     * @param int $roleId
635
+     * @author fanqi
636
+     * @date 2021-03-22
533 637
      */
534 638
     private function createVisitFieldGrant($roleId)
535 639
     {
536
-        $content = [];
537
-
538
-        $visitList = Db::name('admin_field')->field(['name', 'field'])->where(['type' => 'crm_visit', 'operating' => 0])->select();
640
+        $content = [
641
+            ['field' => 'number',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回访编号'],
642
+            ['field' => 'visit_time',     'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回访时间'],
643
+            ['field' => 'owner_user_id',  'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '回访人'],
644
+            ['field' => 'shape',          'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '回访形式'],
645
+            ['field' => 'customer_id',    'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '客户名称'],
646
+            ['field' => 'contacts_id',    'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '联系人'],
647
+            ['field' => 'contract_id',    'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '合同编号'],
648
+            ['field' => 'satisfaction',   'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户满意度'],
649
+            ['field' => 'feedback',       'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '客户反馈'],
650
+            ['field' => 'create_user_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建人'],
651
+            ['field' => 'create_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '创建时间'],
652
+            ['field' => 'update_time',    'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0, 'name' => '更新时间'],
653
+        ];
654
+
655
+        $visitList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_visit')->select();
539 656
 
540 657
         # 处理自定义字段
541 658
         foreach ($visitList AS $key => $value) {
659
+            if (in_array($value['field'], $this->except['visit'])) continue;
660
+
542 661
             $content[] = [
543 662
                 'name'            => $value['name'],
544 663
                 'field'           => $value['field'],
@@ -550,21 +669,6 @@ class FieldGrantLogic
550 669
             ];
551 670
         }
552 671
 
553
-        # 处理固定字段
554
-        $content[] = ['name' => '回访编号', 'field' => 'number', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
555
-        $content[] = ['name' => '回访形式', 'field' => 'shape', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
556
-        $content[] = ['name' => '客户满意度', 'field' => 'satisfaction', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
557
-        $content[] = ['name' => '回访时间', 'field' => 'visit_time', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
558
-        $content[] = ['name' => '客户名称', 'field' => 'customer_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
559
-        $content[] = ['name' => '联系人', 'field' => 'contacts_id', 'read' => 1, 'read_operation' => 1, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
560
-        $content[] = ['name' => '合同编号', 'field' => 'contract_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
561
-        $content[] = ['name' => '客户反馈', 'field' => 'feedback', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
562
-        $content[] = ['name' => '回访人', 'field' => 'owner_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0];
563
-        $content[] = ['name' => '创建时间', 'field' => 'create_time', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
564
-        $content[] = ['name' => '编辑时间', 'field' => 'update_time', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
565
-        $content[] = ['name' => '创建人', 'field' => 'create_user_id', 'read' => 1, 'read_operation' => 0, 'write' => 0, 'write_operation' => 0, 'is_diy' => 0];
566
-
567
-
568 672
         Db::name('admin_field_grant')->insert([
569 673
             'role_id'     => $roleId,
570 674
             'module'      => 'crm',

+ 44
- 10
application/admin/logic/InitializeLogic.php Zobrazit soubor

@@ -8,6 +8,7 @@
8 8
 
9 9
 namespace app\admin\logic;
10 10
 
11
+use app\admin\controller\UpdateSql;
11 12
 use think\Db;
12 13
 use think\Exception;
13 14
 
@@ -275,6 +276,32 @@ class InitializeLogic
275 276
             # ------ 重置联系人数据 END ------ #
276 277
 
277 278
 
279
+            # ------ 重置公海数据 START ------ #
280
+
281
+            # 清除公海主数据并重置自增ID
282
+            Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool");
283
+
284
+            # 清除公海字段数据并重置自增ID
285
+            Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool_field_setting");
286
+
287
+            # 清除公海用户自定义字段样式数据并重置自增ID
288
+            Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool_field_style");
289
+
290
+            # 清除公海操作记录数据并重置自增ID
291
+            Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool_record");
292
+
293
+            # 清除公海关联数据并重置自增ID
294
+            Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool_relation");
295
+
296
+            # 清除公海规则数据并重置自增ID
297
+            Db::query("TRUNCATE TABLE ".$prefix."crm_customer_pool_rule");
298
+
299
+            # 添加公海默认数据
300
+            UpdateSql::addPoolDefaultData();
301
+
302
+            # ------ 重置公海数据 END ------ #
303
+
304
+
278 305
             # ------ 重置客户数据 START ------ #
279 306
 
280 307
             # 获取客户附件ID
@@ -355,15 +382,10 @@ class InitializeLogic
355 382
             # ------ 清除数据操作日志数据 END ------ #
356 383
 
357 384
 
358
-            # ------ 清除模板打印记录数据 START ------ #
385
+            # ------ 清除客户配置表(锁定、拥有)数据 START ------ #
359 386
             Db::query("TRUNCATE TABLE ".$prefix."crm_customer_config");
360
-            # ------ 清除模板打印记录数据 END ------ #
361
-
362
-
363
-            # ------ 清除模板打印记录数据 START ------ #
364
-            Db::query("TRUNCATE TABLE ".$prefix."crm_printing_record");
365
-            # ------ 清除模板打印记录数据 END ------ #
366
-
387
+            # ------ 清除客户配置表(锁定、拥有)数据 END ------ #
388
+            
367 389
 
368 390
             # ------ 清除导入数据记录表 START ------ #
369 391
             Db::name('admin_import_record')->where(['type' => ['like', 'crm_%']])->delete();
@@ -400,7 +422,7 @@ class InitializeLogic
400 422
             # ------ 清除跟客户模块有关的管理数据表 END ------ #
401 423
 
402 424
 
403
-            # ------ 清除自动编号数据 START ------ #
425
+            # ------ 重置自动编号数据 START ------ #
404 426
             $time = time();
405 427
             Db::query("TRUNCATE TABLE ".$prefix."crm_number_sequence");
406 428
             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
415 437
             Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (10, 1, 2, 'yyyyMMdd', null, null, null, null, ".$time.", 1, null, 0, 4)");
416 438
             Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (11, 2, 1, 'FP', null, null, null, null, ".$time.", 1, null, 0, 4)");
417 439
             Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (12, 3, 3, 1, 1, 1, 1, ".$time.", ".$time.", 1, null, 0, 4)");
418
-            # ------ 清除自动编号数据 END ------ #
440
+            # ------ 重置自动编号数据 END ------ #
419 441
 
420 442
 
421 443
             # ------ 设置跟进记录常用语 START ------ #
@@ -435,6 +457,12 @@ class InitializeLogic
435 457
             # ------ 设置跟进记录常用语 END ------ #
436 458
 
437 459
 
460
+            # ------ 清除打印相关数据 START ------ #
461
+            Db::query("TRUNCATE TABLE ".$prefix."admin_printing_data");
462
+            Db::query("TRUNCATE TABLE ".$prefix."crm_printing_record");
463
+            # ------ 清除打印相关数据 END ------ #
464
+
465
+
438 466
             # ------ 删除审批记录 START ------ #
439 467
             Db::name('admin_examine_record')->whereLike('types', 'crm%')->delete();
440 468
             Db::query("ALTER TABLE ".$prefix."admin_examine_record AUTO_INCREMENT = 1");
@@ -830,6 +858,12 @@ class InitializeLogic
830 858
 //            # 重置自增ID
831 859
 //            Db::query("ALTER TABLE ".$prefix."task AUTO_INCREMENT = 1");
832 860
 
861
+            # 清除项目排序数据
862
+            Db::query("TRUNCATE TABLE ".$prefix."work_order");
863
+
864
+            # 清除标签排序数据
865
+            Db::query("TRUNCATE TABLE ".$prefix."work_lable_order");
866
+
833 867
             # 清除项目数据
834 868
             Db::query("TRUNCATE TABLE ".$prefix."work");
835 869
 

+ 274
- 50
application/admin/logic/LogLogic.php Zobrazit soubor

@@ -31,11 +31,10 @@ class LogLogic
31 31
         'crm_visit'       => '回访',
32 32
         'crm_invoice'     => '回款',
33 33
         'oa_log'          => '办公日志',
34
-        'oa_examine'      => '办公审批',
35 34
         'work_task'       => '任务',
36 35
         'work'            => '项目',
37
-        'label'           => '标签',
38
-        'calendar'        => '日历'
36
+        'oa_event'        => '日程',
37
+        'crm_activity'        => '跟进记录',
39 38
     ];
40 39
 
41 40
     public $systemModules = [
@@ -47,19 +46,53 @@ class LogLogic
47 46
         'approval'    => '审批流程管理',
48 47
         'workbench'   => '工作台',
49 48
         'project'     => '项目管理',
50
-        'customer'    => '客户管理'
49
+        'customer'    => '客户管理',
50
+        'work_task'    => '其他设置'
51
+    ];
52
+    public $systemAction=[
53
+        'admin_oalog_rule'=>'日志',
54
+        'admin_group'=>'角色',
55
+        'crm_leads'       => '线索',
56
+        'crm_customer'    => '客户',
57
+        'crm_pool'        => '客户公海',
58
+        'crm_contacts'    => '联系人',
59
+        'crm_product'     => '产品',
60
+        'crm_business'    => '商机',
61
+        'crm_contract'    => '合同',
62
+        'crm_receivables' => '回款',
63
+        'crm_visit'       => '回访',
64
+        'crm_invoice'     => '回款',
65
+        'oa_log'          => '办公日志',
66
+        'oa_examine'      => '办公审批',
67
+        'crm_config'      => '客户管理系统设置',
68
+        'crm_number_sequence'      => '业绩目标',
69
+        'admin_structure'      => '部门',
70
+        'admin_config'      => '应用管理',
71
+        'work_task'    => '其他设置'
51 72
     ];
52
-
53 73
     /**
54 74
      * 日志记录中的行为所对应的中文名称
55 75
      *
56 76
      * @var string[]
57 77
      */
58 78
     private $action = [
59
-        'index'  => '查看数据',
60 79
         'save'   => '添加数据',
61 80
         'update' => '编辑数据',
62
-        'delete' => '删除数据'
81
+        'delete' => '删除数据',
82
+        'excel' => '导入数据',
83
+        'excelexport' => '导出数据',
84
+        'lock' => '锁定',
85
+        'islock' => '解锁',
86
+        'status' => '更改成交状态',
87
+        'receive' => '领取',
88
+        'transfer' => '转移',
89
+        'teamSave' => '添加团队成员',
90
+        'distribute' => '分配',
91
+        'up' => '上架',
92
+        'down' => '下架',
93
+        'recover' => '归档恢复',
94
+        'archiveData' => '归档',
95
+        'copy' => '复制',
63 96
     ];
64 97
     private $loginType = [
65 98
         '成功', '密码错误', '账号禁用'
@@ -73,20 +106,34 @@ class LogLogic
73 106
      */
74 107
     public function getLoginRecord($param)
75 108
     {
76
-        $loginRecordModel = new LoginRecord();
77
-
78
-        $limit = !empty($param['limit']) ? $param['limit'] : 15;
79
-
80
-        $data  = $loginRecordModel->where(function ($query) use ($param) {
81
-            if (!empty($param['startTime'])) $query->where('create_time', '>=', strtotime($param['startTime']));
82
-            if (!empty($param['endTime'])) $query->where('create_time', '<=', strtotime($param['endTime']));
83
-            if (!empty($param['userIds'])) $query->whereIn('create_user_id', $param['userIds']);
84
-        })->order('id', 'desc')->paginate($limit)->each(function ($value) {
85
-            $value['username']  = $value->create_user_info['realname'];
86
-            $value['type'] = $this->loginType[$value['type']];
87
-        })->toArray();
88
-
89
-        return ['list' => $data['data'], 'count' => $data['total']];
109
+        $res= db('admin_login_record')
110
+            ->alias('login')
111
+            ->join('__ADMIN_USER__ user','user.id=login.create_user_id','LEFT')
112
+            ->where(function ($query) use ($param) {
113
+                if (!empty($param['startTime'])) $query->where('login.create_time', '>=', strtotime($param['startTime']));
114
+                if (!empty($param['endTime'])) $query->where('login.create_time', '<=', strtotime($param['endTime']));
115
+                if (!empty($param['userIds'])) $query->whereIn('login.create_user_id', $param['userIds']);
116
+            })
117
+            ->field('login.*,user.realname as username')
118
+            ->page($param['page'],$param['limit'])
119
+            ->order('login.id', 'desc')
120
+            ->select();
121
+        foreach ($res as $k =>$v){
122
+            $res[$k]['create_time']=!empty($v['create_time'])?date('Y-m-d H:i:s',$v['create_time']):null;
123
+            $res[$k]['type']=$this->loginType[$v['type']];
124
+        }
125
+        $total= db('admin_login_record')
126
+            ->alias('login')
127
+            ->join('__ADMIN_USER__ user','user.id=login.create_user_id','LEFT')
128
+            ->where(function ($query) use ($param) {
129
+                if (!empty($param['startTime'])) $query->where('login.create_time', '>=', strtotime($param['startTime']));
130
+                if (!empty($param['endTime'])) $query->where('login.create_time', '<=', strtotime($param['endTime']));
131
+                if (!empty($param['userIds'])) $query->whereIn('login.create_user_id', $param['userIds']);
132
+            })->count();
133
+        $data=[];
134
+        $data['list']=$res;
135
+        $data['dataCount']=$total;
136
+        return $data;
90 137
     }
91 138
 
92 139
 
@@ -102,15 +149,19 @@ class LogLogic
102 149
      */
103 150
     public function getSystemLogs($param)
104 151
     {
105
-        $data = SystemLog::with(['toAdminUser'])
152
+        $data = db('admin_system_log')
153
+            ->alias('system')
154
+            ->join('__ADMIN_USER__ user','user.id=system.user_id','LEFT')
106 155
             ->where(function ($query) use ($param) {
107
-                if (!empty($param['startTime'])) $query->where('create_time', '>=', strtotime($param['startTime']));
108
-                if (!empty($param['endTime']))   $query->where('create_time', '<=', strtotime($param['endTime']));
109
-                if (!empty($param['modules']))   $query->whereIn('modules', $param['modules']);
110
-                if (!empty($param['userIds']))   $query->whereIn('user_id', $param['userIds']);
111
-            })->limit(($param['page'] - 1) * $param['limit'])->order('log_id', 'desc')->select();
112
-
113
-        return $this->setSystemData($data);
156
+                if (!empty($param['startTime'])) $query->where('system.create_time', '>=', strtotime($param['startTime']));
157
+                if (!empty($param['endTime']))   $query->where('system.create_time', '<=', strtotime($param['endTime']));
158
+                if (!empty($param['modules']))   $query->whereIn('system.module_name', $param['modules']);
159
+                if (!empty($param['userIds']))   $query->whereIn('system.user_id', $param['userIds']);
160
+            })
161
+            ->page($param['page'], $param['limit'])
162
+            ->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')
163
+            ->order('system.log_id', 'desc')->select();
164
+            return $this->setSystemData($data);
114 165
     }
115 166
 
116 167
     /**
@@ -140,15 +191,18 @@ class LogLogic
140 191
      */
141 192
     public function getRecordLogs($param)
142 193
     {
143
-        $data = OperationLog::with(['toAdminUser'])
194
+        $data = db('admin_operation_log')
195
+            ->alias('operation')
196
+            ->join('__ADMIN_USER__ user','user.id=operation.user_id','LEFT')
144 197
             ->where(function ($query) use ($param) {
145
-                if (!empty($param['startTime'])) $query->where('create_time', '>=', strtotime($param['startTime']));
146
-                if (!empty($param['endTime']))   $query->where('create_time', '<=', strtotime($param['endTime']));
147
-                if (!empty($param['modules']))   $query->whereIn('module', $param['modules']);
148
-                if (!empty($param['userIds']))   $query->whereIn('user_id', $param['userIds']);
198
+                if (!empty($param['startTime'])) $query->where('operation.create_time', '>=', strtotime($param['startTime']));
199
+                if (!empty($param['endTime']))   $query->where('operation.create_time', '<=', strtotime($param['endTime']));
200
+                if (!empty($param['modules']))   $query->whereIn('operation.module', arrayToString($param['modules']));
201
+                if (!empty($param['userIds']))   $query->whereIn('operation.user_id', $param['userIds']);
149 202
             })
150
-            ->limit(($param['page'] - 1) * $param['limit'])->order('log_id', 'desc')->select();
151
-
203
+            ->field('operation.*,user.realname')
204
+            ->page($param['page'], $param['limit'])
205
+            ->order('operation.log_id', 'desc')->select();
152 206
         return $this->setRecordData($data);
153 207
     }
154 208
 
@@ -160,12 +214,15 @@ class LogLogic
160 214
      */
161 215
     public function getRecordLogCount($param)
162 216
     {
163
-        return OperationLog::where(function ($query) use ($param) {
164
-            if (!empty($param['startTime'])) $query->where('create_time', '>=', strtotime($param['startTime']));
165
-            if (!empty($param['endTime'])) $query->where('create_time', '<=', strtotime($param['endTime']));
166
-            if (!empty($param['modules'])) $query->whereIn('module', $param['module']);
167
-            if (!empty($param['userIds'])) $query->whereIn('user_id', $param['userIds']);
168
-        })->count();
217
+        return db('admin_operation_log')
218
+            ->alias('operation')
219
+            ->join('__ADMIN_USER__ user','user.id=operation.user_id','LEFT')
220
+            ->where(function ($query) use ($param) {
221
+                if (!empty($param['startTime'])) $query->where('operation.create_time', '>=', strtotime($param['startTime']));
222
+                if (!empty($param['endTime']))   $query->where('operation.create_time', '<=', strtotime($param['endTime']));
223
+                if (!empty($param['modules']))   $query->whereIn('operation.module', arrayToString($param['modules']));
224
+                if (!empty($param['userIds']))   $query->whereIn('operation.user_id', $param['userIds']);
225
+            })->count();
169 226
     }
170 227
 
171 228
     /**
@@ -181,11 +238,15 @@ class LogLogic
181 238
         foreach ($data AS $key => $value) {
182 239
             $result[] = [
183 240
                 'log_id'      => $value['log_id'],
184
-                'source_name' => $value['source_name'],
241
+                'source_name' => $value['target_name'],
185 242
                 'create_time' => date('Y-m-d H:i:s', $value['create_time']),
186 243
                 'ip'          => $value['client_ip'],
187 244
                 'module'      => $this->recordModules[$value['module']],
188
-                'content'     => $value['content']
245
+                'action'      => in_array('crm',explode('_',$value['module']))==1?
246
+                    '客户管理':(in_array('oa',explode('_',$value['module']))==1?'办公管理':'项目管理'),
247
+                'content'     => $value['content'],
248
+                'user_name'     => $value['realname'],
249
+                'action_name'     =>  $this->action[$value['action_name']],
189 250
             ];
190 251
         }
191 252
 
@@ -193,7 +254,7 @@ class LogLogic
193 254
     }
194 255
 
195 256
     /**
196
-     * 组装数据操作日志数据
257
+     * 组装系统操作数据操作日志数据
197 258
      *
198 259
      * @param $data
199 260
      * @return mixed
@@ -201,18 +262,181 @@ class LogLogic
201 262
     private function setSystemData($data)
202 263
     {
203 264
         $result = [];
204
-
205 265
         foreach ($data AS $key => $value) {
206 266
             $result[] = [
207 267
                 'log_id'      => $value['log_id'],
208
-                'source_name' => $value['source_name'],
268
+                'source_name' => $value['target_name'],
209 269
                 'create_time' => date('Y-m-d H:i:s', $value['create_time']),
210 270
                 'ip'          => $value['client_ip'],
211
-                'module'      => $this->systemModules[$value['module']],
212
-                'content'     => $value['content']
271
+                'action'      => $this->systemModules[$value['module_name']],
272
+                'content'     => $value['content'],
273
+                'user_name'     => $value['realname'],
274
+                'action_name'     => $this->action[$value['action_name']],
275
+                'module'     => '后台管理',
276
+                'action_down'     => $this->recordModules[$value['controller_name']]?:'',
213 277
             ];
214 278
         }
215
-
279
+        
216 280
         return $result;
217 281
     }
282
+    
283
+    /**
284
+     * 导出方法
285
+     * @param $param
286
+     *
287
+     * @author      alvin guogaobo
288
+     * @version     1.0 版本号
289
+     * @since       2021/4/8 0008 16:37
290
+     */
291
+    public function downExcel($param){
292
+        $excelModel = new \app\admin\model\Excel();
293
+        $file_name='sysLogs';
294
+        $field_list=[];
295
+        $type='';
296
+        $action=$param['action'];
297
+        unset($param['action']);
298
+        unset($param['page']);
299
+        unset($param['limit']);
300
+        $param['startTime']= !empty($param['startTime'])?$param['startTime'].' 00:00:00':'';
301
+        $param['endTime']= !empty($param['endTime'])?$param['endTime'].' 23:59:59':'';
302
+        switch ($action){
303
+            case 'getSystemLogs':
304
+                $type='系统日志';
305
+                $field_list = [
306
+                    '0' => ['name' => '用户', 'field' => 'user_name'],
307
+                    '1' => ['name' => '时间', 'field' => 'create_time'],
308
+                    '2' => ['name' => 'ip地址', 'field' => 'ip'],
309
+                    '3' => ['name' => '模块', 'field' => 'module'],
310
+                    '4' => ['name' => '子模块', 'field' => 'action'],
311
+                    '5' => ['name' => '行为', 'field' => 'action_name'],
312
+                    '6' => ['name' => '对象', 'field' => 'source_name'],
313
+                    '7' => ['name' => '操作详情', 'field' => 'content'],
314
+                ];
315
+                $modules = $this->systemModules;
316
+                if(!empty($param['subModelLabels'])){
317
+                    $param['modules']=$param['subModelLabels'];
318
+                }
319
+                $list = db('admin_system_log')
320
+                    ->alias('system')
321
+                    ->join('__ADMIN_USER__ user','user.id=system.user_id','LEFT')
322
+                    ->where(function ($query) use ($param) {
323
+                        if (!empty($param['startTime'])) $query->where('system.create_time', '>=', strtotime($param['startTime']));
324
+                        if (!empty($param['endTime']))   $query->where('system.create_time', '<=', strtotime($param['endTime']));
325
+                        if (!empty($param['modules']))   $query->whereIn('system.module_name', $param['modules']);
326
+                        if (!empty($param['userIds']))   $query->whereIn('system.user_id', $param['userIds']);
327
+                    })
328
+                    ->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')
329
+                    ->order('system.log_id', 'desc')->select();
330
+                 $data=$this->setSystemData($list);
331
+                break;
332
+            case 'getRecordLogs':
333
+                $type='系统日志';
334
+                $field_list = [
335
+                    '0' => ['name' => '用户', 'field' => 'user_name'],
336
+                    '1' => ['name' => '时间', 'field' => 'create_time'],
337
+                    '2' => ['name' => 'ip地址', 'field' => 'ip'],
338
+                    '3' => ['name' => '模块', 'field' => 'action'],
339
+                    '4' => ['name' => '子模块', 'field' => 'module'],
340
+                    '5' => ['name' => '行为', 'field' => 'action_name'],
341
+                    '6' => ['name' => '对象', 'field' => 'source_name'],
342
+                    '7' => ['name' => '操作详情', 'field' => 'content'],
343
+                ];
344
+                if(!empty($param['subModelLabels'])){
345
+                    $param['modules']=$param['subModelLabels'];
346
+                }else{
347
+                    switch ($param['model']){
348
+                        case 'crm': //客户管理
349
+                            $param['modules']=array(
350
+                                'crm_leads'  ,
351
+                                'crm_customer',
352
+                                'crm_pool'     ,
353
+                                'crm_contacts'  ,
354
+                                'crm_product'    ,
355
+                                'crm_business'    ,
356
+                                'crm_contract'     ,
357
+                                'crm_receivables'  ,
358
+                                'crm_visit'        ,
359
+                                'crm_invoice'      ,
360
+                                'crm_activity'
361
+                            );
362
+                            break;
363
+                        case 'oa' : //办公管理
364
+                            $param['modules']=array(
365
+                                'oa_log'  ,
366
+                                'oa_event',
367
+                            );
368
+                            break;
369
+                        case 'work' ://项目管理
370
+                            $param['modules']=array(
371
+                                'work_task'  ,
372
+                                'work',
373
+                            );
374
+                            break;
375
+                        default :
376
+                            $param['modules']=array(
377
+                                'crm_leads'  ,
378
+                                'crm_customer',
379
+                                'crm_pool'     ,
380
+                                'crm_contacts'  ,
381
+                                'crm_product'    ,
382
+                                'crm_business'    ,
383
+                                'crm_contract'     ,
384
+                                'crm_receivables'  ,
385
+                                'crm_visit'        ,
386
+                                'crm_invoice'      ,
387
+                                'crm_activity',
388
+                                'oa_log'  ,
389
+                                'oa_event',
390
+                                'work_task'  ,
391
+                                'work',
392
+                            );
393
+                            break;
394
+                    }
395
+                }
396
+    
397
+                $list = db('admin_operation_log')
398
+                    ->alias('operation')
399
+                    ->join('__ADMIN_USER__ user','user.id=operation.user_id','LEFT')
400
+                    ->where(function ($query) use ($param) {
401
+                        if (!empty($param['startTime'])) $query->where('operation.create_time', '>=', strtotime($param['startTime']));
402
+                        if (!empty($param['endTime']))   $query->where('operation.create_time', '<=', strtotime($param['endTime']));
403
+                        if (!empty($param['modules']))   $query->whereIn('operation.module', arrayToString($param['modules']));
404
+                        if (!empty($param['userIds']))   $query->whereIn('operation.user_id', $param['userIds']);
405
+                    })
406
+                    ->field('operation.*,user.realname')
407
+                    ->order('operation.log_id', 'desc')->select();
408
+                $data=$this->setRecordData($list);
409
+                break;
410
+            case 'getLoginRecord':
411
+                $type='登陆日志';
412
+                $field_list = [
413
+                    '0' => ['name' => '用户', 'field' => 'username'],
414
+                    '1' => ['name' => '时间', 'field' => 'create_time'],
415
+                    '2' => ['name' => 'ip地址', 'field' => 'ip'],
416
+                    '3' => ['name' => '登陆地点', 'field' => 'address'],
417
+                    '4' => ['name' => '设备类型', 'field' => 'remark'],
418
+                    '5' => ['name' => '终端内核', 'field' => 'browser'],
419
+                    '6' => ['name' => '平台', 'field' => 'os'],
420
+                    '7' => ['name' => '成功', 'field' => 'type'],
421
+                ];
422
+                $res  = db('admin_login_record')
423
+                    ->alias('login')
424
+                    ->join('__ADMIN_USER__ user','user.id=login.create_user_id','LEFT')
425
+                    ->where(function ($query) use ($param) {
426
+                        if (!empty($param['startTime'])) $query->where('login.create_time', '>=', strtotime($param['startTime']));
427
+                        if (!empty($param['endTime'])) $query->where('login.create_time', '<=', strtotime($param['endTime']));
428
+                        if (!empty($param['userIds'])) $query->whereIn('login.create_user_id', $param['userIds']);
429
+                })
430
+                    ->field('login.*,user.realname as username')
431
+                    ->order('login.id', 'desc')
432
+                    ->select();
433
+                foreach ($res as $k =>$v){
434
+                    $res[$k]['create_time']=!empty($v['create_time'])?date('Y-m-d H:i:s',$v['create_time']):null;
435
+                    $res[$k]['type']=$this->loginType[$v['type']];
436
+                }
437
+                $data=$res;
438
+                break;
439
+        }
440
+        return $excelModel->biExportExcel($file_name, $field_list, $type, $data);
441
+    }
218 442
 }

+ 1
- 0
application/admin/logic/MarketLogic.php Zobrazit soubor

@@ -0,0 +1 @@
1
+<?php

+ 1
- 1
application/admin/logic/MessageLogic.php Zobrazit soubor

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

+ 481
- 0
application/admin/logic/PoolConfigLogic.php Zobrazit soubor

@@ -0,0 +1,481 @@
1
+<?php
2
+
3
+namespace app\admin\logic;
4
+
5
+use PDOStatement;
6
+use think\Collection;
7
+use think\Db;
8
+
9
+class PoolConfigLogic
10
+{
11
+    public $error = '操作失败!';
12
+
13
+    /**
14
+     * 公海配置列表
15
+     *
16
+     * @param array $param page 页码,limit 每页条数
17
+     * @author fanqi
18
+     * @since 2021-03-30
19
+     * @return array
20
+     */
21
+    public function getPoolList($param)
22
+    {
23
+        $page = !empty($param['page']) ? $param['page'] : 1;
24
+        $limit = !empty($param['limit']) ? $param['limit'] : 15;
25
+
26
+        $count = db('crm_customer_pool')->count();
27
+
28
+        # 公海列表
29
+        $list = db('crm_customer_pool')->field([
30
+            'pool_id', 'pool_name', 'admin_user_ids', 'user_ids', 'department_ids', 'status'
31
+        ])->limit(($page - 1) * $limit, $limit)->select();
32
+
33
+        # 统计公海下的客户数量
34
+        $customerData = [];
35
+        $customerList = db('crm_customer_pool_relation')->field(['pool_id', 'count(customer_id) AS customer_count'])->group('pool_id')->select();
36
+        foreach ($customerList AS $key => $value) {
37
+            $customerData[$value['pool_id']] = $value['customer_count'];
38
+        }
39
+
40
+        foreach ($list AS $key => $value) {
41
+            # 公海管理员
42
+            $adminUserIds = trim($value['admin_user_ids'], ',');
43
+            $adminUserNames = db('admin_user')->whereIn('id', $adminUserIds)->column('realname');
44
+
45
+            # 公海成员
46
+            $userIds = trim($value['user_ids'], ',');
47
+            $userNames = db('admin_user')->whereIn('id', $userIds)->column('realname');
48
+
49
+            # 部门
50
+            $structureIds = trim($value['department_ids'], ',');
51
+            $structureNames = db('admin_structure')->whereIn('id', $structureIds)->column('name');
52
+
53
+            # 公海成员
54
+            $poolMembers = array_merge($structureNames, $userNames);
55
+
56
+            $list[$key]['admin_user_names'] = implode(',', $adminUserNames);
57
+            $list[$key]['user_names'] = implode(',', array_unique($poolMembers));
58
+
59
+            $list[$key]['customer_count'] = !empty($customerData[$value['pool_id']]) ? $customerData[$value['pool_id']] : 0;
60
+        }
61
+
62
+        return ['count' => $count, 'list' => !empty($list) ? $list : []];
63
+    }
64
+
65
+    /**
66
+     * 设置多公海配置
67
+     *
68
+     * @param $param
69
+     * @author fanqi
70
+     * @since 2021-03-30
71
+     * @return bool
72
+     */
73
+    public function setPoolConfig($param)
74
+    {
75
+        if (empty($param['pool_name'])) {
76
+            $this->error = '请填写公海名称!';
77
+            return false;
78
+        }
79
+
80
+        if (!empty($param['pool_name']) && mb_strlen($param['pool_name']) > 100) {
81
+            $this->error = '公海名称最多只能输入100个字符!';
82
+            return false;
83
+        }
84
+
85
+        if (empty($param['admin_user_ids'])) {
86
+            $this->error = '请选择公海管理员!';
87
+            return false;
88
+        }
89
+
90
+        if (empty($param['user_ids']) && empty($param['department_ids'])) {
91
+            $this->error = '请选择公海成员!';
92
+            return false;
93
+        }
94
+
95
+        if (!empty($param['recycle_conf']) && empty($param['rule'])) {
96
+            $this->error = '请设置回收规则!';
97
+            return false;
98
+        }
99
+
100
+        $repeatWhere['pool_name'] = $param['pool_name'];
101
+        if (!empty($param['pool_id'])) $repeatWhere['pool_id'] = ['neq', $param['pool_id']];
102
+        if (db('crm_customer_pool')->where($repeatWhere)->value('pool_id')) {
103
+            $this->error = '公海名称重复';
104
+            return false;
105
+        }
106
+
107
+        $poolData = [
108
+            'pool_name' => $param['pool_name'],
109
+            'admin_user_ids' => ',' . $param['admin_user_ids'] . ',',
110
+            'user_ids' => ',' . $param['user_ids'] . ',',
111
+            'department_ids' => !empty($param['department_ids']) ? ',' . $param['department_ids'] . ',' : '',
112
+            'status' => 1,
113
+            'before_owner_conf' => $param['before_owner_conf'],
114
+            'before_owner_day'  => $param['before_owner_day'],
115
+            'receive_conf' => $param['receive_conf'],
116
+            'receive_count' => $param['receive_count'],
117
+            'remind_conf' => $param['remind_conf'],
118
+            'remain_day' => $param['remain_day'],
119
+            'recycle_conf' => $param['recycle_conf'],
120
+            'create_user_id' => $param['user_id'],
121
+            'create_time' => time()
122
+        ];
123
+
124
+        Db::startTrans();
125
+        try {
126
+            if (!empty($param['pool_id'])) {
127
+                # 编辑
128
+                $poolId = $param['pool_id'];
129
+                Db::name('crm_customer_pool')->where('pool_id', $poolId)->update($poolData);
130
+            } else {
131
+                # 创建
132
+                $poolId = Db::name('crm_customer_pool')->insert($poolData, false, true);
133
+            }
134
+
135
+            # 公海字段
136
+            $fieldData = $this->getPoolField($param['field'], $poolId);
137
+            if (!empty($fieldData)) {
138
+                Db::name('crm_customer_pool_field_setting')->where('pool_id', $poolId)->delete();
139
+                Db::name('crm_customer_pool_field_setting')->insertAll($fieldData);
140
+            }
141
+
142
+            # 公海规则
143
+            $ruleData = $this->getPoolRule($param['rule'], $poolId);
144
+            if (!empty($ruleData)) {
145
+                Db::name('crm_customer_pool_rule')->where('pool_id', $poolId)->delete();
146
+                Db::name('crm_customer_pool_rule')->insertAll($ruleData);
147
+            }
148
+
149
+            Db::commit();
150
+
151
+            return true;
152
+        } catch (\Exception $e) {
153
+            Db::rollback();
154
+
155
+            $this->error = '创建公海失败!';
156
+            return false;
157
+        }
158
+    }
159
+
160
+    /**
161
+     * 公海配置详情
162
+     *
163
+     * @param int $poolId 公海ID
164
+     * @author fanqi
165
+     * @since 2021-03-30
166
+     * @return array|bool
167
+     */
168
+    public function readPool($poolId)
169
+    {
170
+        $data = db('crm_customer_pool')->where('pool_id', $poolId)->find();
171
+
172
+        if (empty($data['pool_id'])) {
173
+            $this->error = '没有查询到数据!';
174
+            return false;
175
+        }
176
+
177
+        # 时间格式
178
+        $data['create_time'] = date('Y-m-d H:i:s', $data['create_time']);
179
+
180
+        # 公海管理员
181
+        $adminUserIds = trim($data['admin_user_ids'], ',');
182
+        $data['admin_user_ids'] = $adminUserIds;
183
+        $data['admin_user_info'] = db('admin_user')->field(['id', 'realname', 'thumb_img'])->whereIn('id', $adminUserIds)->select();
184
+        foreach ($data['admin_user_info'] AS $key => $value) {
185
+            $data['admin_user_info'][$key]['thumb_img'] = getFullPath($value['thumb_img']);
186
+        }
187
+
188
+        # 公海成员
189
+        $userIds = trim($data['user_ids'], ',');
190
+        $data['user_ids'] = $userIds;
191
+        $data['user_info'] = db('admin_user')->field(['id', 'realname', 'thumb_img'])->whereIn('id', $userIds)->select();
192
+        foreach ($data['user_info'] AS $key => $value) {
193
+            $data['user_info'][$key]['thumb_img'] = getFullPath($value['thumb_img']);
194
+        }
195
+
196
+        # 公海部门
197
+        $departmentIds = trim($data['department_ids'], ',');
198
+        $data['department_ids'] = $departmentIds;
199
+        $data['department_info'] = db('admin_structure')->field(['id', 'name'])->whereIn('id', $departmentIds)->select();
200
+
201
+        # 公海字段
202
+        $data['field'] = db('crm_customer_pool_field_setting')->where('pool_id', $data['pool_id'])->select();
203
+
204
+        # 公海规则
205
+        $data['rule'] = db('crm_customer_pool_rule')->where('pool_id', $data['pool_id'])->select();
206
+        foreach ($data['rule'] AS $key => $value) {
207
+            if (!empty($value['level'])) {
208
+                $data['rule'][$key]['level'] = json_decode($value['level'], true);
209
+                $data['rule'][$key]['level_setting'] = json_decode($value['level'], true);
210
+            }
211
+        }
212
+
213
+        # 客户数量
214
+        $data['customer_count'] = db('crm_customer_pool_relation')->where('pool_id', $poolId)->count();
215
+
216
+        return $data;
217
+    }
218
+
219
+    /**
220
+     * 变更公海配置状态
221
+     *
222
+     * @param array $param pool_id 公海ID, status 状态(1启用、0停用)
223
+     * @author fanqi
224
+     * @since 2021-03-30
225
+     * @return false|int|string
226
+     */
227
+    public function changePoolStatus($param)
228
+    {
229
+        $poolId = $param['pool_id'];
230
+        $status = $param['status'];
231
+
232
+        if ($status == 0 && db('crm_customer_pool_relation')->where('pool_id', $poolId)->count() > 0) {
233
+            $this->error = '公海内有客户,不能停用!';
234
+            return false;
235
+        }
236
+
237
+        if ($status == 0 && db('crm_customer_pool')->where(['pool_id' => ['neq', $poolId], 'status' => 1])->count() < 1) {
238
+            $this->error = '至少要开启一个公海!';
239
+            return false;
240
+        }
241
+
242
+        return db('crm_customer_pool')->where('pool_id', $poolId)->update(['status' => $status]);
243
+    }
244
+
245
+    /**
246
+     * 删除公海配置
247
+     *
248
+     * @param int $poolId 公海ID
249
+     * @author fanqi
250
+     * @since 2021-03-30
251
+     * @return bool
252
+     */
253
+    public function deletePool($poolId)
254
+    {
255
+        if (db('crm_customer_pool_relation')->where('pool_id', $poolId)->count() > 0) {
256
+            $this->error = '公海内有客户,不能删除!';
257
+            return false;
258
+        }
259
+
260
+        if (db('crm_customer_pool')->where(['pool_id' => ['neq', $poolId], 'status' => 1])->count() < 1) {
261
+            $this->error = '至少要保留一个开启的公海!';
262
+            return false;
263
+        }
264
+
265
+        Db::startTrans();
266
+        try {
267
+            # 删除公海规则数据
268
+            Db::name('crm_customer_pool_rule')->where('pool_id', $poolId)->delete();
269
+
270
+            # 删除公海字段数据
271
+            Db::name('crm_customer_pool_field_setting')->where('pool_id', $poolId)->delete();
272
+
273
+            # 删除用户保存的公海字段数据
274
+            Db::name('crm_customer_pool_field_style')->where('pool_id', $poolId)->delete();
275
+
276
+            # 删除公海数据
277
+            Db::name('crm_customer_pool')->where('pool_id', $poolId)->delete();
278
+
279
+            Db::commit();
280
+
281
+            return true;
282
+        } catch (\Exception $e) {
283
+            Db::rollback();
284
+
285
+            $this->error = '删除公海配置失败!';
286
+            return false;
287
+        }
288
+    }
289
+
290
+    /**
291
+     * 转移公海客户
292
+     *
293
+     * @param array $param source_pool_id 源公海ID,target_pool_id 目标公海ID
294
+     * @author fanqi
295
+     * @since 2021-03-30
296
+     * @return bool
297
+     */
298
+    public function transferPool($param)
299
+    {
300
+        if (empty($param['source_pool_id']) || empty($param['target_pool_id'])) {
301
+            $this->error = '缺少源ID或目标ID';
302
+            return false;
303
+        }
304
+
305
+        # 源
306
+        $sourceCustomerIds = Db::name('crm_customer_pool_relation')->where('pool_id', $param['source_pool_id'])->column('customer_id');
307
+        # 目标
308
+        $targetCustomerIds = Db::name('crm_customer_pool_relation')->where('pool_id', $param['target_pool_id'])->column('customer_id');
309
+        # 差异
310
+        $diffCustomerIds = array_diff($sourceCustomerIds, $targetCustomerIds);
311
+
312
+        $data = [];
313
+        foreach ($diffCustomerIds AS $key => $value) {
314
+            $data[] = [
315
+                'customer_id' => $value,
316
+                'pool_id' => $param['target_pool_id']
317
+            ];
318
+        }
319
+
320
+        Db::startTrans();
321
+        try {
322
+            Db::name('crm_customer_pool_relation')->where('pool_id', $param['source_pool_id'])->delete();
323
+
324
+            if (!empty($data)) Db::name('crm_customer_pool_relation')->insertAll($data);
325
+
326
+            Db::commit();
327
+
328
+            return true;
329
+        } catch (\Exception $e) {
330
+            Db::rollback();
331
+
332
+            $this->error = '转移失败!';
333
+            return false;
334
+        }
335
+    }
336
+
337
+    /**
338
+     * 获取客户级别列表
339
+     *
340
+     * @author fanqi
341
+     * @since 2021-04-22
342
+     * @return array
343
+     */
344
+    public function getCustomerLevel()
345
+    {
346
+        $setting = db('admin_field')->where(['types' => 'crm_customer', 'field' => 'level'])->value('setting');
347
+
348
+        $data = explode(chr(10), $setting);
349
+
350
+        return !empty($data) ? $data : [];
351
+    }
352
+
353
+    /**
354
+     * 获取公海字段列表
355
+     *
356
+     * @param array $param pool_id 公海ID
357
+     * @author fanqi
358
+     * @since 2021-04-29
359
+     * @return bool|PDOStatement|string|Collection
360
+     */
361
+    public function getPoolFieldList($param)
362
+    {
363
+        if (!empty($param['pool_id'])) {
364
+            return db('crm_customer_pool_field_setting')->field(['field_name AS field', 'name', 'form_type', 'is_hidden'])->where('pool_id', $param['pool_id'])->select();
365
+        } else {
366
+            $data = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden'])->where(['types' => 'crm_customer'])->select();
367
+
368
+            $address = [
369
+                'field'     => 'address',
370
+                'name'      => '省、市、区/县',
371
+                'form_type' => 'customer_address',
372
+                'is_hidden' => 0
373
+            ];
374
+            $detailAddress = [
375
+                'field'     => 'detail_address',
376
+                'name'      => '详细地址',
377
+                'form_type' => 'text',
378
+                'is_hidden' => 0
379
+            ];
380
+            $lastRecord = [
381
+                'field'     => 'last_record',
382
+                'name'      => '最后跟进记录',
383
+                'form_type' => 'text',
384
+                'is_hidden' => 0
385
+            ];
386
+            $lastTime = [
387
+                'field'     => 'last_time',
388
+                'name'      => '最后跟进时间',
389
+                'form_type' => 'datetime',
390
+                'is_hidden' => 0
391
+            ];
392
+            $beforeOwnerUser = [
393
+                'field'     => 'before_owner_user_id',
394
+                'name'      => '前负责人',
395
+                'form_type' => 'user',
396
+                'is_hidden' => 0
397
+            ];
398
+            $intoPoolTime = [
399
+                'field'     => 'into_pool_time',
400
+                'name'      => '进入公海时间',
401
+                'form_type' => 'datetime',
402
+                'is_hidden' => 0
403
+            ];
404
+            $createTime = [
405
+                'field'     => 'create_time',
406
+                'name'      => '创建时间',
407
+                'form_type' => 'datetime',
408
+                'is_hidden' => 0
409
+            ];
410
+            $updateTime = [
411
+                'field'     => 'update_time',
412
+                'name'      => '更新时间',
413
+                'form_type' => 'datetime',
414
+                'is_hidden' => 0
415
+            ];
416
+            $createUser = [
417
+                'field'     => 'create_user_id',
418
+                'name'      => '创建人',
419
+                'form_type' => 'user',
420
+                'is_hidden' => 0
421
+            ];
422
+            array_push($data, $address, $detailAddress, $lastRecord, $lastTime, $createTime, $updateTime, $createUser, $beforeOwnerUser, $intoPoolTime);
423
+
424
+            return $data;
425
+        }
426
+    }
427
+
428
+    /**
429
+     * 处理公海规则数据
430
+     *
431
+     * @param array $rules 规则数据
432
+     * @param int $poolId 公海ID
433
+     * @author fanqi
434
+     * @since 2021-03-30
435
+     * @return array
436
+     */
437
+    private function getPoolRule($rules, $poolId)
438
+    {
439
+        $result = [];
440
+
441
+        foreach ($rules AS $key => $value) {
442
+            $result[] = [
443
+                'pool_id' => $poolId,
444
+                'type' => $value['type'],
445
+                'deal_handle' => $value['deal_handle'],
446
+                'business_handle' => $value['business_handle'],
447
+                'level_conf' => $value['level_conf'],
448
+                'level' => json_encode($value['level']),
449
+                'limit_day' => !empty($value['limit_day']) ? $value['limit_day'] : 0
450
+            ];
451
+        }
452
+
453
+        return $result;
454
+    }
455
+
456
+    /**
457
+     * 处理公海字段数据
458
+     *
459
+     * @param array $fields 字段列表
460
+     * @param int $poolId 公海ID
461
+     * @author fanqi
462
+     * @since 2021-03-30
463
+     * @return array
464
+     */
465
+    private function getPoolField($fields, $poolId)
466
+    {
467
+        $result = [];
468
+
469
+        foreach ($fields AS $key => $value) {
470
+            $result[] = [
471
+                'pool_id' => $poolId,
472
+                'name' => $value['name'],
473
+                'field_name' => $value['field'],
474
+                'form_type' => $value['form_type'],
475
+                'is_hidden' => $value['is_hidden']
476
+            ];
477
+        }
478
+
479
+        return $result;
480
+    }
481
+}

+ 63
- 42
application/admin/logic/PrintingLogic.php Zobrazit soubor

@@ -16,20 +16,27 @@ class PrintingLogic
16 16
     /**
17 17
      * 打印模板列表
18 18
      *
19
-     * @param $page
20
-     * @param $limit
19
+     * @param array $param : int $page 页码; int $limit 每页记录条数; string $type 打印模板类型
20
+     * @author fanqi
21
+     * @date 2021-03-26
21 22
      * @return array
22
-     * @throws \think\db\exception\DataNotFoundException
23
-     * @throws \think\db\exception\ModelNotFoundException
24
-     * @throws \think\exception\DbException
25 23
      */
26
-    public function index($page, $limit)
24
+    public function index($param)
27 25
     {
26
+        $page  = !empty($param['page'])  ? $param['page']             : 1;
27
+        $limit = !empty($param['limit']) ? $param['limit']            : 500;
28
+        $where = !empty($param['type'])  ? ['type' => $param['type']] : [];
29
+
28 30
         $result = [];
29
-        $type   = [1 => '商机', 2 => '合同', 3 => '回款'];
31
+        $type   = [5 => '商机', 6 => '合同', 7 => '回款'];
30 32
         $field  = ['id', 'name', 'type', 'user_name', 'create_time', 'update_time'];
31
-        $count  = Db::name('admin_printing')->count();
32
-        $data   = Db::name('admin_printing')->field($field)->order('id', 'desc')->limit(($page - 1) * $limit, $limit)->select();
33
+        $count  = Db::name('admin_printing')->where($where)->count();
34
+        $data   = Db::name('admin_printing')
35
+            ->field($field)
36
+            ->where($where)
37
+            ->order('id', 'desc')
38
+            ->limit(($page - 1) * $limit, $limit)
39
+            ->select();
33 40
 
34 41
         foreach ($data AS $key => $value) {
35 42
             $result[] = [
@@ -63,7 +70,8 @@ class PrintingLogic
63 70
             'user_name'   => $userName,
64 71
             'name'        => $param['name'],
65 72
             'type'        => $param['type'],
66
-            'content'     => htmlspecialchars($param['content']),
73
+            'content'     => json_encode(['data' => $param['content']]),
74
+//            'content'     => htmlspecialchars($param['content']),
67 75
             'create_time' => time(),
68 76
             'update_time' => time()
69 77
         ];
@@ -81,7 +89,9 @@ class PrintingLogic
81 89
     {
82 90
         $content = Db::name('admin_printing')->where('id', $id)->value('content');
83 91
 
84
-        return ['id' => $id, 'content' => htmlspecialchars_decode($content)];
92
+        $contentArray = json_decode($content, true);
93
+
94
+        return ['id' => $id, 'content' => $contentArray['data']];
85 95
     }
86 96
 
87 97
     /**
@@ -94,7 +104,7 @@ class PrintingLogic
94 104
      */
95 105
     public function update($param)
96 106
     {
97
-        if (!empty($param['content'])) $param['content'] = htmlspecialchars($param['content']);
107
+        if (!empty($param['content'])) $param['content'] = json_encode(['data' => $param['content']]);
98 108
 
99 109
         return Db::name('admin_printing')->update($param);
100 110
     }
@@ -149,7 +159,7 @@ class PrintingLogic
149 159
     /**
150 160
      * 获取打印模板需要的字段
151 161
      *
152
-     * @param $type 1商机;2合同;3回款
162
+     * @param $type 5商机;6合同;7回款
153 163
      * @return array[]
154 164
      * @throws \think\db\exception\DataNotFoundException
155 165
      * @throws \think\db\exception\ModelNotFoundException
@@ -160,31 +170,26 @@ class PrintingLogic
160 170
         $result = [];
161 171
 
162 172
         switch ($type) {
163
-            case 1:
173
+            case 5:
164 174
                 $result['business'] = $this->getBusinessFields();
165
-                $result['customer'] = $this->getCustomerFields();
166
-                $result['product']  = $this->getProductFields();
175
+                $result['customer'] = $this->getCustomerFields(5);
176
+                $result['product']  = $this->getProductFields(5);
167 177
 
168 178
                 break;
169
-            case 2:
170
-                $result['contract'] = $this->getContractFields();
171
-                $result['customer'] = $this->getCustomerFields();
179
+            case 6:
180
+                $result['contract'] = $this->getContractFields(6);
181
+                $result['customer'] = $this->getCustomerFields(6);
172 182
                 $result['contacts'] = $this->getContactsFields();
173
-                $result['product']  = $this->getProductFields();
183
+                $result['product']  = $this->getProductFields(6);
174 184
 
175 185
                 break;
176
-            case 3:
177
-                $result['receivables'] = $this->getReceivablesFields();
178
-                $result['contract']    = $this->getContractFields();
186
+            case 7:
187
+                $result['receivables'] = $this->getReceivablesFields(7);
188
+                $result['contract']    = $this->getContractFields(7);
179 189
 
180 190
                 break;
181 191
             default:
182
-                $result['business']    = $this->getBusinessFields();
183
-                $result['customer']    = $this->getCustomerFields();
184
-                $result['product']     = $this->getProductFields();
185
-                $result['contract']    = $this->getContractFields();
186
-                $result['contacts']    = $this->getContactsFields();
187
-                $result['receivables'] = $this->getReceivablesFields();
192
+                $result[] = [];
188 193
         }
189 194
 
190 195
         return $result;
@@ -231,7 +236,7 @@ class PrintingLogic
231 236
      * @throws \think\db\exception\ModelNotFoundException
232 237
      * @throws \think\exception\DbException
233 238
      */
234
-    private function getCustomerFields()
239
+    private function getCustomerFields($type)
235 240
     {
236 241
         $result = [];
237 242
 
@@ -239,7 +244,8 @@ class PrintingLogic
239 244
 
240 245
         # 处理自定义字段
241 246
         foreach ($customerList AS $key => $value) {
242
-            if (in_array($value['field'], ['next_time', 'remark'])) continue;
247
+            if (in_array($value['field'], ['next_time'])) continue;
248
+            if (in_array($type, [5, 6]) && in_array($value['field'], ['deal_status'])) continue;
243 249
 
244 250
             $result[] = [
245 251
                 'name'  => $value['name'],
@@ -247,6 +253,12 @@ class PrintingLogic
247 253
             ];
248 254
         }
249 255
 
256
+        # 处理固定字段
257
+        if (in_array($type, [5, 6])) {
258
+            $result[] = ['name' => '详细地址', 'field' => 'address'];
259
+            $result[] = ['name' => '区域', 'field' => 'detail_address'];
260
+        }
261
+
250 262
         return $result;
251 263
     }
252 264
 
@@ -258,7 +270,7 @@ class PrintingLogic
258 270
      * @throws \think\db\exception\ModelNotFoundException
259 271
      * @throws \think\exception\DbException
260 272
      */
261
-    private function getProductFields()
273
+    private function getProductFields($type)
262 274
     {
263 275
         $result = [];
264 276
 
@@ -266,7 +278,8 @@ class PrintingLogic
266 278
 
267 279
         # 处理自定义字段
268 280
         foreach ($productList AS $key => $value) {
269
-            if ($value['field'] == 'status') continue;
281
+            if (in_array($value['field'], ['status'])) continue;
282
+            if (in_array($type, [5, 6]) && in_array($value['field'], ['description'])) continue;
270 283
 
271 284
             $result[] = [
272 285
                 'name'  => $value['name'],
@@ -280,6 +293,7 @@ class PrintingLogic
280 293
         $result[] = ['name' => '折扣', 'field' => 'discount'];
281 294
         $result[] = ['name' => '整单折扣', 'field' => 'discount_rate'];
282 295
         $result[] = ['name' => '合计', 'field' => 'subtotal'];
296
+        $result[] = ['name' => '产品总金额', 'field' => 'total_price'];
283 297
 
284 298
         return $result;
285 299
     }
@@ -292,7 +306,7 @@ class PrintingLogic
292 306
      * @throws \think\db\exception\ModelNotFoundException
293 307
      * @throws \think\exception\DbException
294 308
      */
295
-    private function getContractFields()
309
+    private function getContractFields($type)
296 310
     {
297 311
         $result = [];
298 312
 
@@ -300,19 +314,23 @@ class PrintingLogic
300 314
 
301 315
         # 处理自定义字段
302 316
         foreach ($contractList AS $key => $value) {
317
+            if (in_array($type, [6, 7]) && in_array($value['field'], ['customer_id'])) continue;
318
+            if ($type == 7 && in_array($value['field'], ['business_id'])) continue;
319
+
303 320
             $result[] = [
304 321
                 'name'  => $value['name'],
305 322
                 'field' => $value['field']
306 323
             ];
307 324
         }
308 325
 
309
-        # 处理固定字段
310
-        $result[] = ['name' => '负责人', 'field' => 'owner_user_id'];
311
-        $result[] = ['name' => '创建人', 'field' => 'create_user_id'];
312
-        $result[] = ['name' => '创建日期', 'field' => 'create_time'];
313
-        $result[] = ['name' => '更新日期', 'field' => 'update_time'];
314
-        $result[] = ['name' => '已收款金额', 'field' => 'received'];
315
-        $result[] = ['name' => '未收款金额', 'field' => 'uncollected'];
326
+        if (!in_array($type, [7])) {
327
+            $result[] = ['name' => '负责人', 'field' => 'create_user_id'];
328
+            $result[] = ['name' => '创建人', 'field' => 'owner_user_id'];
329
+            $result[] = ['name' => '创建日期', 'field' => 'create_time'];
330
+            $result[] = ['name' => '更新日期', 'field' => 'update_time'];
331
+            $result[] = ['name' => '已收款金额', 'field' => 'done_money'];
332
+            $result[] = ['name' => '未收款金额', 'field' => 'uncollected_money'];
333
+        }
316 334
 
317 335
         return $result;
318 336
     }
@@ -352,7 +370,7 @@ class PrintingLogic
352 370
      * @throws \think\db\exception\ModelNotFoundException
353 371
      * @throws \think\exception\DbException
354 372
      */
355
-    private function getReceivablesFields()
373
+    private function getReceivablesFields($type)
356 374
     {
357 375
         $result = [];
358 376
 
@@ -360,6 +378,9 @@ class PrintingLogic
360 378
 
361 379
         # 处理自定义字段
362 380
         foreach ($receivablesList AS $key => $value) {
381
+            if (in_array($value['field'], ['contract_id'])) continue;
382
+            if (in_array($type, [7]) && in_array($value['field'], ['contract_id'])) continue;
383
+
363 384
             $result[] = [
364 385
                 'name'  => $value['name'],
365 386
                 'field' => $value['field']

+ 21
- 6
application/admin/logic/WorkLogic.php Zobrazit soubor

@@ -8,6 +8,7 @@
8 8
 
9 9
 namespace app\admin\logic;
10 10
 
11
+use app\admin\controller\ApiCommon;
11 12
 use think\Db;
12 13
 
13 14
 class WorkLogic
@@ -58,8 +59,8 @@ class WorkLogic
58 59
         $param['type']   = 0;
59 60
         $param['types']  = 7;
60 61
         $param['system'] = 0;
61
-
62
-        return Db::name('admin_group')->insert($param);
62
+        $data=Db::name('admin_group')->insertGetId($param);
63
+        return $data;
63 64
     }
64 65
 
65 66
     /**
@@ -90,7 +91,18 @@ class WorkLogic
90 91
      */
91 92
     public function updateRole($param)
92 93
     {
93
-        return Db::name('admin_group')->update($param);
94
+        $res=Db::name('admin_group')->where('id',$param['id'])->find();
95
+        if(!$res){
96
+            return false;
97
+        }else{
98
+            $data=Db::name('admin_group')->update($param);
99
+            # 添加系统操作日志
100
+            $user=new ApiCommon();
101
+            $userInfo=$user->userInfo;
102
+            SystemActionLog($userInfo['id'], 'admin_group','project', $param['id'], 'update',$res['title'] , '', '','编辑了项目管理权限:'.$res['title']);
103
+            return $data;
104
+        }
105
+       
94 106
     }
95 107
 
96 108
     /**
@@ -103,9 +115,9 @@ class WorkLogic
103 115
      */
104 116
     public function deleteRole($id)
105 117
     {
106
-        $system = Db::name('admin_group')->where('id', $id)->value('system');
118
+        $system = Db::name('admin_group')->where('id', $id)->find();
107 119
 
108
-        if (!empty($system)) return ['status' => false, 'error' => '不允许删除系统默认角色!'];
120
+        if (!empty($system['system'])) return ['status' => false, 'error' => '不允许删除系统默认角色!'];
109 121
 
110 122
         if (!Db::name('admin_group')->where('id', $id)->delete()) return ['status' => false, 'error' => '操作失败!'];
111 123
 
@@ -115,7 +127,10 @@ class WorkLogic
115 127
             db('work')->where('group_id', $id)->update(['group_id' => $readOnlyId]);      # 处理公开项目的权限
116 128
             db('work_user')->where('group_id', $id)->update(['group_id' => $readOnlyId]); # 处理私有项目的权限
117 129
         }
118
-
130
+        # 添加系统操作日志
131
+        $user=new ApiCommon();
132
+        $userInfo=$user->userInfo;
133
+        SystemActionLog($userInfo['id'], 'admin_group','project', $id, 'update',$system['title'] , '', '','删除了项目管理权限:'.$system['title']);
119 134
         return ['status' => true];
120 135
     }
121 136
 }

+ 10
- 0
application/admin/model/Config.php Zobrazit soubor

@@ -37,7 +37,17 @@ class Config extends Common
37 37
 	{
38 38
 		$data = [];
39 39
 		$data['status'] = $param['status'] ? : '0';
40
+        $dataInfo=db('admin_config')->where('id',$param['id'])->find();
41
+        $user_id=$param['user_id'];
42
+        unset($param['user_id']);
40 43
 		if ($this->where(['id' => $id])->update($data)) {
44
+            # 修改记录
45
+            if($param['status']==0){
46
+                $data='停用了'.$dataInfo['name'];
47
+            }else{
48
+                $data='启用了'.$dataInfo['name'];
49
+            }
50
+            SystemActionLog($user_id,'admin_config','application',$id,'update','应用管理','','',$data);
41 51
 			return true;
42 52
 		}
43 53
 		$this->error = '操作失败';

+ 2
- 1
application/admin/model/ExamineFlow.php Zobrazit soubor

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

+ 27
- 20
application/admin/model/ExamineRecord.php Zobrazit soubor

@@ -55,16 +55,22 @@ class ExamineRecord extends Common
55 55
         }
56 56
 
57 57
         $result = [];
58
+        
59
+        # 获取创建者信息(业务审批)
60
+        if (in_array($param['types'], ['crm_contract', 'crm_receivables', 'crm_invoice'])) {
61
+            $model      = db($param['types']);
62
+            $primaryKey = null;
63
+            if ($param['types'] == 'crm_contract')    $primaryKey = 'contract_id';
64
+            if ($param['types'] == 'crm_receivables') $primaryKey = 'receivables_id';
65
+            if ($param['types'] == 'crm_invoice')     $primaryKey = 'invoice_id';
58 66
 
59
-        # 获取创建者信息(办公审批)
60
-        if ($param['types'] == 'oa_examine' && !empty($param['is_record'])) {
61
-            $info     = db('oa_examine')->field(['create_time', 'create_user_id'])->where('examine_id', $param['types_id'])->find();
62
-            $userInfo = $userModel->getUserById($info['create_user_id']);
67
+            $info     = $model->field(['create_time', 'owner_user_id'])->where($primaryKey, $param['types_id'])->find();
68
+            $userInfo = $userModel->getUserById($info['owner_user_id']);
63 69
 
64 70
             $result[] = [
65 71
                 'check_date'         => date('Y-m-d H:i:s', $info['create_time']),
66 72
                 'check_time'         => $info['create_time'],
67
-                'check_user_id'      => $info['create_user_id'],
73
+                'check_user_id'      => $info['owner_user_id'],
68 74
                 'check_user_id_info' => $userInfo,
69 75
                 'content'            => '',
70 76
                 'flow_id'            => 0,
@@ -75,23 +81,20 @@ class ExamineRecord extends Common
75 81
                 'types'              => $param['types'],
76 82
                 'types_id'           => $param['types_id']
77 83
             ];
78
-        }
79
-
80
-        # 获取创建者信息(业务审批)
81
-        if (in_array($param['types'], ['crm_contract', 'crm_receivables', 'crm_invoice']) && !empty($param['is_record'])) {
82
-            $model      = db($param['types']);
83
-            $primaryKey = null;
84
-            if ($param['types'] == 'crm_contract')    $primaryKey = 'contract_id';
85
-            if ($param['types'] == 'crm_receivables') $primaryKey = 'receivables_id';
86
-            if ($param['types'] == 'crm_invoice')     $primaryKey = 'invoice_id';
87
-
88
-            $info     = $model->field(['create_time', 'owner_user_id'])->where($primaryKey, $param['types_id'])->find();
89
-            $userInfo = $userModel->getUserById($info['owner_user_id']);
90
-
84
+        }else{
85
+            unset($param['action']);
86
+            # 获取创建者信息(办公审批)
87
+    
88
+            $info     = db('oa_examine')->field(['create_time', 'create_user_id','update_time,check_status'])->where('examine_id', $param['types_id'])->find();
89
+            $userInfo = $userModel->getUserById($info['create_user_id']);
90
+            #撤销之后修改再次审批 审批流程过滤之前的审批记录
91
+            if($info['check_status']<2){
92
+                $param['check_time']=['>',$info['update_time']?:$info['create_time']];
93
+            }
91 94
             $result[] = [
92 95
                 'check_date'         => date('Y-m-d H:i:s', $info['create_time']),
93 96
                 'check_time'         => $info['create_time'],
94
-                'check_user_id'      => $info['owner_user_id'],
97
+                'check_user_id'      => $info['create_user_id'],
95 98
                 'check_user_id_info' => $userInfo,
96 99
                 'content'            => '',
97 100
                 'flow_id'            => 0,
@@ -102,9 +105,13 @@ class ExamineRecord extends Common
102 105
                 'types'              => $param['types'],
103 106
                 'types_id'           => $param['types_id']
104 107
             ];
108
+    
109
+    
105 110
         }
106 111
         unset($param['is_record']);
107
-
112
+        # 多次撤销使用 只显示最后一次撤销数据条件  is_end 0
113
+        $param['is_end']=0;
114
+        
108 115
         $list = db('admin_examine_record')->where($param)->order('check_time asc')->select();
109 116
         foreach ($list as $k=>$v) {
110 117
             $list[$k]['check_user_id_info'] = $userModel->getUserById($v['check_user_id']);

+ 17
- 16
application/admin/model/ExamineStep.php Zobrazit soubor

@@ -320,11 +320,11 @@ class ExamineStep extends Common
320 320
         //创建人或负责人或管理员有撤销权限
321 321
         //if ($dataInfo['create_user_id'] == $check_user_id || $dataInfo['owner_user_id'] == $check_user_id || in_array($check_user_id, $admin_user_ids)) {
322 322
         if ($dataInfo['create_user_id'] == $check_user_id || $dataInfo['owner_user_id'] == $check_user_id) {
323
-            if (!in_array($dataInfo['check_status'],['2','3','4'])) {
323
+            if (!in_array($dataInfo['check_status'],['2','3','4','6'])) {
324 324
                 $is_recheck = 1;
325 325
             }
326 326
         }
327
-        if (in_array($check_user_id, stringToArray($dataInfo['check_user_id'])) && !in_array($dataInfo['check_status'],['2','3','4'])) {
327
+        if (in_array($check_user_id, stringToArray($dataInfo['check_user_id'])) && !in_array($dataInfo['check_status'],['2','3','4','6'])) {
328 328
             $is_check = 1;
329 329
         }
330 330
 
@@ -468,21 +468,22 @@ class ExamineStep extends Common
468 468
         $where['types_id'] = $types_id;
469 469
         $where['is_end'] = 0;
470 470
         $recordList = $examineRecordModel->getDataList($where);
471
-    
472 471
         $typeInfo = $this->getDataByTypes($types, $types_id);
473 472
         $dataInfo = $typeInfo['dataInfo'];
474
-        $createUserInfo = $userModel->getUserById($dataInfo['create_user_id']);
475
-        $userList[0]['userInfo'] = $createUserInfo;
476
-        $userList[0]['type'] = 3; //创建
477
-        $userList[0]['time'] = $dataInfo['update_time'] ? : '';
478
- 
479 473
         //type 0失败,1通过,2撤销,3创建,4待审核,5未提交
480
-        $i = 1;
481
-        foreach ($recordList as $k=>$v) {
482
-            $userList[$i]['userInfo'] = $userModel->getUserById($v['check_user_id']);
483
-            $userList[$i]['type'] = $v['status'];
484
-            $userList[$i]['time'] = $v['check_time'];
485
-            $i++;
474
+        $i = 0;
475
+        if(empty($recordList)){
476
+            $createUserInfo = $userModel->getUserById($dataInfo['create_user_id']);
477
+            $userList[0]['userInfo'] = $createUserInfo;
478
+            $userList[0]['type'] = 3; //创建
479
+            $userList[0]['time'] = $dataInfo['update_time'] ? : '';
480
+        }else{
481
+            foreach ($recordList as $k=>$v) {
482
+                $userList[$i]['userInfo'] = $userModel->getUserById($v['check_user_id']);
483
+                $userList[$i]['type'] = $v['status'];
484
+                $userList[$i]['time'] = $v['check_time'];
485
+                $i++;
486
+            }
486 487
         }
487 488
         if ($dataInfo['check_status'] <= 1 && $dataInfo['check_user_id']) {
488 489
             $check_user_id_arr = stringToArray($dataInfo['check_user_id']);
@@ -502,11 +503,11 @@ class ExamineStep extends Common
502 503
         //创建人或负责人或管理员有撤销权限
503 504
 //        if ($dataInfo['create_user_id'] == $check_user_id || $dataInfo['owner_user_id'] == $check_user_id || in_array($check_user_id, $admin_user_ids)) {
504 505
         if ($dataInfo['create_user_id'] == $check_user_id || $dataInfo['owner_user_id'] == $check_user_id) {
505
-            if (!in_array($dataInfo['check_status'],['2','3','4','5'])) {
506
+            if (!in_array($dataInfo['check_status'],['2','3','4','5','6'])) {
506 507
                 $is_recheck = 1;
507 508
             }
508 509
         }
509
-        if (in_array($check_user_id, stringToArray($dataInfo['check_user_id'])) && !in_array($dataInfo['check_status'],['2','3','4','5'])) {
510
+        if (in_array($check_user_id, stringToArray($dataInfo['check_user_id'])) && !in_array($dataInfo['check_status'],['2','3','4','5','6'])) {
510 511
             $is_check = 1;
511 512
         }
512 513
 

+ 607
- 61
application/admin/model/Excel.php Zobrazit soubor

@@ -13,7 +13,7 @@ use app\work\model\Task;
13 13
 use com\PseudoQueue as Queue;
14 14
 use think\Cache;
15 15
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
16
-
16
+use think\cache\driver\Redis;
17 17
 class Excel extends Common
18 18
 {
19 19
     /**
@@ -72,7 +72,7 @@ class Excel extends Common
72 72
     public function excelImportDownload($field_list, $types, $save_path = '')
73 73
     {
74 74
         $fieldModel = new \app\admin\model\Field();
75
-        
75
+    
76 76
         //实例化主文件
77 77
         $objPHPExcel = new Spreadsheet();
78 78
         $objProps = $objPHPExcel->getProperties(); // 设置excel文档的属性
@@ -86,7 +86,7 @@ class Excel extends Common
86 86
         $objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet
87 87
         $objActSheet = $objPHPExcel->getActiveSheet();
88 88
         $objActSheet->setTitle('导入模板' . date('Y-m-d', time())); //设置sheet的标题
89
-        
89
+    
90 90
         //存储Excel数据源到其他工作薄
91 91
         $objPHPExcel->createSheet();
92 92
         $subObject = $objPHPExcel->getSheet(1);
@@ -121,11 +121,13 @@ class Excel extends Common
121 121
                 }
122 122
             } else {
123 123
                 $objActSheet->getColumnDimension($this->stringFromColumnIndex($k))->setWidth(20); //设置单元格宽度
124
-                if ($field['form_type'] == 'select' || $field['form_type'] == 'checkbox' || $field['form_type'] == 'radio' || $field['form_type'] == 'category') {
124
+                if ($field['form_type'] == 'select' || $field['form_type'] == 'checkbox' || $field['form_type'] == 'radio' || $field['form_type'] == 'category' || $field['form_type']=='user') {
125 125
                     //产品类别
126 126
                     if ($field['form_type'] == 'category' && $field['types'] == 'crm_product') {
127 127
                         $setting = db('crm_product_category')->order('pid asc')->column('name');
128
-                    } else {
128
+                    } elseif($field['form_type']=='user' && $field['field'] == 'owner_user_id') {
129
+                        $setting = db('admin_user')->order('id asc')->column('realname');
130
+                    }else{
129 131
                         $setting = $field['setting'] ?: [];
130 132
                     }
131 133
                     $select_value = implode(',', $setting);
@@ -554,16 +556,16 @@ class Excel extends Common
554 556
             $save_path = UPLOAD_PATH . $save_name;
555 557
             
556 558
             // 队列-判断是否需要排队
557
-            if (!$queue->canExec()) {
558
-                $this->error = [
559
-                    'temp_file' => $save_name,
560
-                    'page' => -2,
561
-                    'import_queue_index' => $import_queue_index,
562
-                    'info' => $queue->error
563
-                ];
564
-                return true;
565
-            }
566
-            
559
+//            if (!$queue->canExec()) {
560
+//                $this->error = [
561
+//                    'temp_file' => $save_name,
562
+//                    'page' => -2,
563
+//                    'import_queue_index' => $import_queue_index,
564
+//                    'info' => $queue->error
565
+//                ];
566
+//                return true;
567
+//            }
568
+
567 569
             // 加载类库
568 570
             vendor("phpexcel.PHPExcel");
569 571
             vendor("phpexcel.PHPExcel.Writer.Excel5");
@@ -647,10 +649,16 @@ class Excel extends Common
647 649
                     break;
648 650
             }
649 651
             // 字段
652
+    
650 653
             $fieldModel = new \app\admin\model\Field();
651 654
             $fieldParam['types'] = $types;
652 655
             $fieldParam['action'] = 'excel';
653 656
             $field_list = $fieldModel->field($fieldParam);
657
+            if(!empty($param['pool_id'])){
658
+                $pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select();
659
+                $merge_list = $fieldModel->field($fieldParam);
660
+                $field_list=array_intersect($merge_list,$pool_list);
661
+            }
654 662
             $field_list = array_map(function ($val) {
655 663
                 if (method_exists($val, 'toArray')) {
656 664
                     return $val->toArray();
@@ -659,6 +667,40 @@ class Excel extends Common
659 667
                 }
660 668
             }, $field_list);
661 669
             $field_key_name_list = array_column($field_list, 'name', 'field');
670
+            # 下次升级
671
+//            $fieldModel = new \app\admin\model\Field();
672
+//            $fieldParam['types'] = $types;
673
+//            $fieldParam['action'] = 'excel';
674
+//            if(!empty($param['pool_id'])){
675
+//                $pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select();
676
+//                $merge_list = $fieldModel->field($fieldParam);
677
+//                $field_list=array_intersect($merge_list,$pool_list);
678
+//            }else{
679
+//                $field_list = $fieldModel->field($fieldParam);
680
+//                $field=[1=>[
681
+//                    'field'=>'owner_user_id',
682
+//                    'types'=>'crm_leads',
683
+//                    'name'=>'负责人',
684
+//                    'form_type'=>'user',
685
+//                    'default_value'=>'',
686
+//                    'is_unique' => 1,
687
+//                    'is_null' => 1,
688
+//                    'input_tips' =>'',
689
+//                    'setting' => Array(),
690
+//                    'is_hidden'=>0,
691
+//                    'writeStatus' => 1,
692
+//                    'value' => '']
693
+//                ];
694
+//                $first_array = array_splice($field_list, 0, 2);
695
+//            }
696
+//            $field_list = array_map(function ($val) {
697
+//                if (method_exists($val, 'toArray')) {
698
+//                    return $val->toArray();
699
+//                } else {
700
+//                    return $val;
701
+//                }
702
+//            }, $field_list);
703
+//            $field_key_name_list = array_column($field_list, 'name', 'field');
662 704
             // 加载导入数据文件
663 705
             $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
664 706
             $objRender->setReadDataOnly(true);
@@ -675,6 +717,7 @@ class Excel extends Common
675 717
             // 检测导入文件是否使用最新模板
676 718
             $header = $sheet->rangeToArray("A2:{$max_col}2")[0];
677 719
             $temp = 0;
720
+           
678 721
             for ($i = 0; $i < count($field_list); $i++) {
679 722
                 if (
680 723
                     $header[$i] == $field_list[$i]['name']
@@ -725,20 +768,31 @@ class Excel extends Common
725 768
             // 数据重复时的处理方式 0跳过  1覆盖
726 769
             $config = $param['config'] ?: 0;
727 770
             // 默认数据
728
-            
729
-            $default_data = [
730
-                'create_user_id' => $param['create_user_id'],
731
-                'owner_user_id' => $param['owner_user_id'],
732
-                'create_time' => time(),
733
-                'update_time' => time(),
734
-            ];
735
-            
771
+            if(!empty($param['pool_id'])){
772
+                //公海导入
773
+                $default_data = [
774
+                    'create_user_id' => $param['create_user_id'],
775
+                    'create_time' => time(),
776
+                    'update_time' => time(),
777
+                    'owner_user_id' => 0,
778
+                    'before_owner_user_id'=>$param['create_user_id'],
779
+                    'into_pool_time'=>time(),
780
+                    'pool_id' => $param['pool_id'],
781
+                ];
782
+            }else{
783
+                $default_data = [
784
+                    'create_user_id' => $param['create_user_id'],
785
+                    'owner_user_id' => $param['owner_user_id'],
786
+                    'create_time' => time(),
787
+                    'update_time' => time(),
788
+                ];
789
+            }
736 790
             if ($temp !== count($field_list)) {
737 791
 //                $this->error = '请使用最新导入模板';
738 792
                 @unlink($save_path);
739 793
                 $queue->dequeue();
740 794
                 foreach ($dataList as $val) {
741
-                    $error_data_func($val, '请使用最新导入模板');
795
+                    $error_data_func($val, '请使用最新导入模板1');
742 796
                 }
743 797
                 $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
744 798
                 $objWriter->save($error_path);
@@ -833,22 +887,26 @@ class Excel extends Common
833 887
                             $old_data_id_list = $dataModel->whereOr($unique_where)->column($db_id);
834 888
                         }
835 889
                     }
890
+                    #下次升级
891
+//                    if(empty($param['pool_id'])){
892
+//                        $user_id=db('admin_user')->where('realname',$val[2])->value('id');
893
+//                        $data['owner_user_id']=$user_id?:0;
894
+//                    }
895
+                    $owner = db('crm_customer_pool')->where(['pool_id' => $param['pool_id']])->value('admin_user_ids');
896
+                    $auth=db('admin_access')->where('user_id',$param['create_user_id'])->column('group_id');
836 897
                     // 数据重复时
837
-                    if ($old_data_id_list) {
838
-                        // 是否覆盖
898
+                    if (!empty($old_data_id_list) && empty($param['pool_id'])) {
839 899
                         if ($config) {
840 900
                             $data = array_merge($data, $default_data);
841
-                            $data['user_id'] = $param['create_user_id'];
842
-                            $data['update_time'] = time();
901
+                            $data['create_user_id'] = $param['create_user_id'];
843 902
                             $data['update_time'] = time();
844 903
                             $dataModel->startTrans();
845 904
                             try {
846 905
                                 $up_success_count = 0;
847 906
                                 foreach ($old_data_id_list as $id) {
848 907
                                     if ($types == 'crm_customer') {
849
-                                        $owner = db('crm_customer')->where(['name' => $data['name']])->find();
850
-                                        if (!empty($owner) && $owner['owner_user_id'] == 0) {
851
-                                            $temp_error = $owner['name'] . ' ' . '公海数据,无覆盖权限';
908
+                                        if (!in_array($param['create_user_id'],trim(stringToArray($owner),',')) && !in_array(1, $auth) && $param['create_user_id']!=1) {
909
+                                            $temp_error ='当前导入人员对该公海数据,无导入权限';
852 910
                                             $error_data_func($val, $temp_error);
853 911
                                             break;
854 912
                                         }
@@ -886,11 +944,21 @@ class Excel extends Common
886 944
                             $unique_field = array_unique($unique_field);
887 945
                             $error_data_func($val, implode(', ', $unique_field) . ' 根据查重规则,该条数据重复');
888 946
                         }
947
+                    }elseif(!empty($old_data_id_list) && !empty($param['pool_id'])){
948
+                        $error_data_func($val,  ' 重复数据不在当前公海,无权覆盖');
889 949
                     } else {
890
-                        $data = array_merge($data, $default_data);
891
-                        if (!$resData = $dataModel->createData($data)) {
892
-                            $error_data_func($val, $dataModel->getError());
950
+                        if ($types == 'crm_customer') {
951
+                        if (!in_array($param['create_user_id'],trim(stringToArray($owner),',')) && !in_array(1, $auth) && $param['create_user_id']!=1) {
952
+                            $temp_error = '当前导入人员对该公海数据,无导入权限';
953
+                            $error_data_func($val, $temp_error);
954
+                        }
955
+                        }else{
956
+                            $data = array_merge($data, $default_data);
957
+                            if (!$resData = $dataModel->createData($data)) {
958
+                                $error_data_func($val, $dataModel->getError());
959
+                            }
893 960
                         }
961
+                        
894 962
                     }
895 963
                 }
896 964
                 
@@ -933,6 +1001,7 @@ class Excel extends Common
933 1001
                     'error' => $error
934 1002
                 ]);
935 1003
                 // 执行完成
1004
+                $redis= new Redis();
936 1005
                 if ($done >= $total) {
937 1006
                     // 出队
938 1007
                     $queue->dequeue();
@@ -955,6 +1024,9 @@ class Excel extends Common
955 1024
                         'user_id' => $user_id,
956 1025
                         'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
957 1026
                     ]);
1027
+                  
1028
+                    Cache::rm('item');
1029
+                    Cache::rm('excel_item');
958 1030
                     Cache::set('item', 1, config('import_cache_time'));
959 1031
                     Cache::set('excel_item', serialize($this->error), config('import_cache_time'));
960 1032
                 } else {
@@ -969,6 +1041,8 @@ class Excel extends Common
969 1041
                     $excelData['config'] = $config;
970 1042
                     $excelData['owner_user_id'] = $user_id;
971 1043
                     $excelData['base'] = 'batchImportData';
1044
+                    Cache::rm('item');
1045
+                    Cache::rm('excel');
972 1046
                     Cache::set('item', 0, config('import_cache_time'));
973 1047
                     Cache::set('excel', $excelData, config('import_cache_time'));
974 1048
                 }
@@ -1701,8 +1775,8 @@ class Excel extends Common
1701 1775
         }
1702 1776
         // 将标题名称通过fputcsv写到文件句柄
1703 1777
         fputcsv($fp, $title_cell);
1704
-        $export_data = $callback(0);
1705
-        foreach ($export_data as $item) {
1778
+//        $export_data = $callback(0);
1779
+        foreach ($callback as $item) {
1706 1780
             $rows = [];
1707 1781
             foreach ($field_list as $rule) {
1708 1782
                 $rows[] = $item[$rule['field']];
@@ -1727,7 +1801,7 @@ class Excel extends Common
1727 1801
      *
1728 1802
      * @author Ymob
1729 1803
      */
1730
-    public function batchTaskImportData($file,$field_list, $param, $controller = null)
1804
+    public function batchTaskImportData($file, $field_list, $param, $controller = null)
1731 1805
     {
1732 1806
         // 导入模块
1733 1807
         $types = $param['types'];
@@ -1892,8 +1966,8 @@ class Excel extends Common
1892 1966
                 // return false;
1893 1967
             }
1894 1968
             
1895
-            // 开始行  +3 跳过表头
1896
-            $start_row = ($page - 1) * $page_size + 3;
1969
+            // 开始行  +2 跳过表头
1970
+            $start_row = ($page - 1) * $page_size + 2;
1897 1971
             // 结束行
1898 1972
             $end_row = $start_row + $page_size - 1;
1899 1973
             if ($end_row > $max_row) {
@@ -2075,12 +2149,13 @@ class Excel extends Common
2075 2149
         $objActSheet = $objPHPExcel->getActiveSheet(0);
2076 2150
         $objPHPExcel->getActiveSheet()->mergeCells('A1:' . $cellKey[count($field_list) - 1] . '1');//合并单元格(如果要拆分单元格是需要先合并再拆分的,否则程序会报错)
2077 2151
         $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $title);
2152
+        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
2078 2153
         $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(18);//所有单元格(行)默认高度
2079 2154
         $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
2080 2155
         $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
2081
-        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(16);
2082
-        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2083
-        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
2156
+        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
2157
+        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2158
+        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2084 2159
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFont()->getColor()->setARGB('FF000000');
2085 2160
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
2086 2161
         
@@ -2088,10 +2163,12 @@ class Excel extends Common
2088 2163
         foreach ($field_list as $k => $v) {
2089 2164
             $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellKey[$k] . $topNumber, $v['name']);//设置表头数据
2090 2165
             $objPHPExcel->getActiveSheet()->freezePane($cellKey[$k] . ($topNumber + 1));//冻结窗口
2166
+            $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
2167
+            $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
2091 2168
             $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getFont()->setBold(true);//设置是否加粗
2092
-            $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
2093
-            $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2094
-            $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
2169
+            $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//垂直居中
2170
+            $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2171
+            $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2095 2172
             if ($v[3] > 0)//大于0表示需要设置宽度
2096 2173
             {
2097 2174
                 $objPHPExcel->getActiveSheet()->getColumnDimension($cellKey[$k])->setWidth($v[3]);//设置列宽度
@@ -2153,12 +2230,13 @@ class Excel extends Common
2153 2230
         $objActSheet = $objPHPExcel->getActiveSheet(0);
2154 2231
         $objPHPExcel->getActiveSheet()->mergeCells('A1:' . $cellKey[count($field_list) - 1] . '1');//合并单元格(如果要拆分单元格是需要先合并再拆分的,否则程序会报错)
2155 2232
         $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $title);
2233
+        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
2156 2234
         $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(18);//所有单元格(行)默认高度
2157 2235
         $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
2158 2236
         $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
2159
-        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(16);
2237
+        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
2160 2238
         $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2161
-        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
2239
+        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2162 2240
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFont()->getColor()->setARGB('FF000000');
2163 2241
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
2164 2242
         
@@ -2166,11 +2244,13 @@ class Excel extends Common
2166 2244
         foreach ($field_list as $k => $v) {
2167 2245
             $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellKey[$k] . $topNumber, $v['name']);//设置表头数据
2168 2246
             $objPHPExcel->getActiveSheet()->freezePane($cellKey[$k] . ($topNumber + 1));//冻结窗口
2247
+            $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
2169 2248
             $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getFont()->setBold(true);//设置是否加粗
2170
-            $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
2249
+            $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
2250
+            $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//垂直居中
2171 2251
             
2172 2252
             $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2173
-            $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
2253
+            $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2174 2254
             
2175 2255
             if ($v[3] > 0)//大于0表示需要设置宽度
2176 2256
             {
@@ -2189,8 +2269,8 @@ class Excel extends Common
2189 2269
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . $callCount)->applyFromArray($style_array);
2190 2270
         foreach ($callback as $k => $item) {
2191 2271
             foreach ($field_list as $key => $rule) {
2192
-                $objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2193
-                $objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
2272
+                $objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2273
+                $objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2194 2274
                 $objPHPExcel->getActiveSheet()->setCellValue($cellKey[$key] . ($k + 1 + $topNumber), $item[$rule['field']]);
2195 2275
             }
2196 2276
         }
@@ -2233,25 +2313,28 @@ class Excel extends Common
2233 2313
         $objActSheet = $objPHPExcel->getActiveSheet(0);
2234 2314
         $objPHPExcel->getActiveSheet()->mergeCells('A1:M1');//合并单元格(如果要拆分单元格是需要先合并再拆分的,否则程序会报错)
2235 2315
         $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $title);
2236
-        
2237 2316
         $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(18);//所有单元格(行)默认高度
2238 2317
         $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
2318
+        // 设置字体
2319
+        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
2239 2320
         $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
2240
-        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(16);
2241
-        $objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2242
-        $objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
2321
+        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
2322
+        $objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2323
+        $objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2243 2324
         $objActSheet->getStyle('A1:M1')->getFont()->getColor()->setARGB('FF000000');
2244 2325
         $objActSheet->getStyle('A1:M1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
2245 2326
         
2246 2327
         //处理表头
2247
-        
2248 2328
         $objPHPExcel->getActiveSheet()->freezePane('A2');//冻结窗口
2329
+        // 设置字体为
2330
+        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体');
2249 2331
         $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);//设置是否加粗
2250
-        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
2332
+        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(11);
2333
+        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//垂直居中
2251 2334
         
2252
-        $objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2253
-        $objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
2254
-        $objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//文字居中
2335
+        $objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2336
+        $objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2337
+        $objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//文字居中
2255 2338
         
2256 2339
         $objActSheet->getStyle('A2:M2')->getFont()->getColor()->setARGB('FF000000');
2257 2340
         $objActSheet->getStyle('A2:M2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
@@ -2299,6 +2382,7 @@ class Excel extends Common
2299 2382
         $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel5为xls格式,excel2007为xlsx格式
2300 2383
         $objWriter->save('php://output');
2301 2384
     }
2385
+    
2302 2386
     /**
2303 2387
      * 运行中
2304 2388
      * @param $param
@@ -2319,7 +2403,7 @@ class Excel extends Common
2319 2403
         } elseif ($param == 1) {
2320 2404
             $data = '';
2321 2405
         }
2322
-        
2406
+    
2323 2407
         return $data;
2324 2408
     }
2325 2409
     
@@ -2377,4 +2461,466 @@ class Excel extends Common
2377 2461
         return $data;
2378 2462
     }
2379 2463
     
2464
+    /**
2465
+     * 跟进记录导入
2466
+     * @param $file 文件
2467
+     * @param $param 数据
2468
+     * @param $field_list 导入字段
2469
+     *
2470
+     * @author      alvin guogaobo
2471
+     * @version     1.0 版本号
2472
+     * @since       2021/4/9 0009 16:31
2473
+     */
2474
+    public function ActivityImport($file,$field_list,$param,$controller = null)
2475
+    {
2476
+        // 导入模块
2477
+        $types = $param['types'];
2478
+        if (!in_array($types, $this->types_arr)) {
2479
+            $this->error = '参数错误!';
2480
+            $queue->dequeue();
2481
+            return false;
2482
+        }
2483
+       
2484
+        // 采用伪队列  允许三人同时导入数据
2485
+        $queue = new Queue(self::IMPORT_QUEUE, 30000);
2486
+        $import_queue_index = input('import_queue_index');
2487
+     
2488
+        // 队列任务ID
2489
+        if (!$import_queue_index) {
2490
+            if (!$import_queue_index = $queue->makeTaskId()) {
2491
+                $this->error = $queue->error;
2492
+                $queue->dequeue();
2493
+                return false;
2494
+            }
2495
+        } else {
2496
+            if (!$queue->setTaskId($import_queue_index)) {
2497
+                $this->error = $queue->error;
2498
+                $queue->dequeue();
2499
+                return false;
2500
+            }
2501
+        }
2502
+        // 取消导入
2503
+        if ($param['page'] == -1) {
2504
+           
2505
+            @unlink(UPLOAD_PATH . $param['temp_file']);
2506
+            $this->error = [
2507
+                'msg' => '导入已取消',
2508
+                'page' => -1
2509
+            ];
2510
+           
2511
+            if ($param['error']) {
2512
+                $this->error['error_file_path'] = 'temp/' . $param['error_file'];
2513
+            } else {
2514
+               
2515
+                @unlink(TEMP_DIR . $param['error_file']);
2516
+            }
2517
+            $temp = $queue->cache('last_import_cache');
2518
+           
2519
+            (new ImportRecord())->createData([
2520
+                'type' => $types,
2521
+                'total' => $temp['total'],
2522
+                'done' => $temp['done'],
2523
+                'cover' => $temp['cover'],
2524
+                'error' => $temp['error'],
2525
+                'error_data_file_path' => $temp['error'] ? 'temp/' . $error_data_file_name : ''
2526
+            ]);
2527
+            $queue->dequeue();
2528
+            return true;
2529
+        }
2530
+        if (!empty($file) || $param['temp_file']) {
2531
+            // 导入初始化  上传文件
2532
+            if (!empty($file)) {
2533
+                $save_name = $this->upload($file);
2534
+                if ($save_name === false) {
2535
+                    $queue->dequeue();
2536
+                    return false;
2537
+                }
2538
+            } else {
2539
+                $save_name = $param['temp_file'];
2540
+            }
2541
+            // 文件类型
2542
+            $ext = pathinfo($save_name, PATHINFO_EXTENSION);
2543
+            // 文件路径
2544
+            $save_path = UPLOAD_PATH . $save_name;
2545
+            
2546
+            // 队列-判断是否需要排队
2547
+            if (!$queue->canExec()) {
2548
+                $this->error = [
2549
+                    'temp_file' => $save_name,
2550
+                    'page' => -2,
2551
+                    'import_queue_index' => $import_queue_index,
2552
+                    'info' => $queue->error
2553
+                ];
2554
+                return true;
2555
+            }
2556
+            
2557
+            // 加载类库
2558
+            vendor("phpexcel.PHPExcel");
2559
+            vendor("phpexcel.PHPExcel.Writer.Excel5");
2560
+            vendor("phpexcel.PHPExcel.Writer.Excel2007");
2561
+            vendor("phpexcel.PHPExcel.IOFactory");
2562
+           
2563
+            // 错误数据临时文件路径  错误数据开始行数
2564
+            if ($param['error_file']) {
2565
+                $error_path = TEMP_DIR . $param['error_file'];
2566
+                $error_row = $param['error'] + 3;
2567
+                $cover = $param['cover'] ?: 0;
2568
+            } else {
2569
+                // 生成临时文件名称
2570
+                $error_path = tempFileName($ext);
2571
+                // 将导入模板保存至临时路径
2572
+                $controller->excelDownload($error_path);
2573
+                $error_row = 3;
2574
+                $cover = 0;
2575
+            }
2576
+            // 错误数据临时文件名称 相对于临时目录
2577
+            $error_data_file_name = \substr($error_path, strlen(TEMP_DIR));
2578
+            // 加载错误数据文件
2579
+            
2580
+            $err_PHPExcel = \PHPExcel_IOFactory::load($error_path);
2581
+           
2582
+            $error_sheet = $err_PHPExcel->setActiveSheetIndex(0);
2583
+            /**
2584
+             * 添加错误数据到临时文件
2585
+             *
2586
+             * @param array $data 原数据
2587
+             * @param string $error 错误原因
2588
+             * @return void
2589
+             */
2590
+            $error_data_func = function ($data, $error) use ($error_sheet, &$error_row) {
2591
+                
2592
+                foreach ($data as $key => $val) {
2593
+                    // 第一列为错误原因 所以+1
2594
+                    $error_col = \PHPExcel_Cell::stringFromColumnIndex($key + 1);
2595
+                    $error_sheet->setCellValue($error_col . $error_row, $val);
2596
+                }
2597
+                $error_sheet->setCellValue('A' . $error_row, $error);
2598
+                $error_sheet->getStyle('A' . $error_row)->getFont()->getColor()->setARGB('FF000000');
2599
+                $error_sheet->getStyle('A' . $error_row)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFFF0000');
2600
+                
2601
+                $error_row++;
2602
+            };
2603
+            
2604
+            // 加载导入数据文件
2605
+            $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
2606
+            $objRender->setReadDataOnly(true);
2607
+            $ExcelObj = $objRender->load($save_path);
2608
+          
2609
+            // 指定工作表
2610
+            $sheet = $ExcelObj->getSheet(0);
2611
+            // 总行数
2612
+            $max_row = $sheet->getHighestRow();
2613
+            // 最大列数
2614
+            $max_col_num = count($field_list) - 1;
2615
+            $max_col_num += 3 * array_count_values(array_column($field_list, 'form_type'))['map_address'];
2616
+            $max_col = \PHPExcel_Cell::stringFromColumnIndex($max_col_num);
2617
+            
2618
+            // 每次导入条数
2619
+            $page_size = 100;
2620
+            
2621
+            // 当前页码
2622
+            $page = ((int)$param['page']) ?: 1;
2623
+            
2624
+            // 数据总数
2625
+            $total = $max_row - 2;
2626
+            
2627
+            // 总页数
2628
+            $max_page = ceil($total / $page_size);
2629
+            if ($page > $max_page) {
2630
+                // $this->error = 'page参数错误';
2631
+                // @unlink($save_path);
2632
+                // $queue->dequeue();
2633
+                // return false;
2634
+            }
2635
+            
2636
+            // 开始行  +3 跳过表头
2637
+            $start_row = ($page - 1) * $page_size + 3;
2638
+            // 结束行
2639
+            $end_row = $start_row + $page_size - 1;
2640
+            if ($end_row > $max_row) {
2641
+                $end_row = $max_row;
2642
+            }
2643
+            // 读取数据
2644
+            $dataList = $sheet->rangeToArray("A{$start_row}:{$max_col}{$end_row}");
2645
+            // 默认数据
2646
+            $default_data = [
2647
+            ];
2648
+            switch ($types){
2649
+                case 'crm_business':
2650
+                    $dataModel = new \app\crm\model\Business();
2651
+                    $db = db('crm_business');
2652
+                    $db_id = 'business_id';
2653
+                    $activity_type=5;
2654
+                    break;
2655
+                case 'crm_contract':
2656
+                    $db = db('crm_contract');
2657
+                    $db_id = 'contract_id';
2658
+                    $activity_type=6;
2659
+                    break;
2660
+                case 'crm_leads' :
2661
+                    $dataModel = new \app\crm\model\Leads();
2662
+                    $db = db('crm_leads');
2663
+                    $db_id = 'leads_id';
2664
+                    $activity_type=1;
2665
+                    break;
2666
+                case 'crm_customer' :
2667
+                    $dataModel = new \app\crm\model\Customer();
2668
+                    $db = db('crm_customer');
2669
+                    $db_id = 'customer_id';
2670
+                    $fieldParam['form_type'] = ['not in', ['file', 'form', 'user', 'structure']];
2671
+                    $activity_type=2;
2672
+                    break;
2673
+                case 'crm_contacts' :
2674
+                    $dataModel = new \app\crm\model\Contacts();
2675
+                    $db = db('crm_contacts');
2676
+                    $db_id = 'contacts_id';
2677
+                    $activity_type=3;
2678
+                    break;
2679
+            }
2680
+         
2681
+            // 开始导入数据
2682
+            foreach ($dataList as $val) {
2683
+                $fk = 0;
2684
+                $data = [];
2685
+                foreach ($field_list as $field) {
2686
+                    $temp_value = trim($val[$fk]);
2687
+                    // 特殊字段特殊处理
2688
+//                    $temp_value = $this->handleData($temp_value, $field);
2689
+                    $data[$field['field']] = $temp_value;
2690
+                    if ($temp_value == '') {
2691
+                        if ($field['is_null']) {
2692
+                            $not_null_field[] = $field['name'];
2693
+                        }
2694
+                        $empty_count++;
2695
+                    }
2696
+                    $fk++;
2697
+                }
2698
+                if (!empty($not_null_field)) {
2699
+                    $error_data_func($val, implode(', ', $not_null_field) . '不能为空');
2700
+                    continue;
2701
+                }
2702
+                if ($empty_count == count($field_list)) {
2703
+                    $error_data_func($val, '空行');
2704
+                    continue;
2705
+                }
2706
+                $activityLogic = new \app\crm\logic\ActivityLogic();
2707
+                $userData=db('admin_user')->where(['realname'=>$val[1],'status'=>['neq',0]])->value('id');
2708
+                $customerData=$db->where('name',$val[2])->value($db_id);
2709
+                $classData = db('crm_activity')->where(['content' => $val[0], 'activity_type' => $param['activity_type'],'activity_type_id'=>$customerData])->order('activity_id', 'asc')->select();
2710
+                if (empty($customerData)) {
2711
+                    $error_data_func($val, '所属客户'.$val[2].'不存在');
2712
+                    continue;
2713
+                }
2714
+                if (empty($userData)) {
2715
+                    $error_data_func($val, '管理员'.$val[1].'不存在');
2716
+                    continue;
2717
+                }
2718
+                if($types=='crm_customer' && (!empty($val[5]) || !empty($val[6]))){
2719
+                    $contactsData=db('crm_contacts')->where('name',$val[5])->value($db_id);
2720
+                    $businessData=$db->where('crm_business',$val[6])->value($db_id);
2721
+                    if (empty($contactsData)&&eempty($businessData)) {
2722
+                        $error_data_func($val, '联系人'.$val[5].'不存在或商机'.$val[6].'不存在');
2723
+                        continue;
2724
+                    }
2725
+                }
2726
+                if ($classData[0]['activity_id'] != '') {
2727
+                    
2728
+                    $data['activity_id'] = $classData[0]['activity_id'];
2729
+                    $data = array_merge($data, $default_data);
2730
+                    $data['create_user_id'] = $userData;
2731
+                    $data['activity_type_id'] = $customerData;
2732
+                    $data['activity_type'] = $activity_type;
2733
+                    if (!$resData = $activityLogic->update($data)) {
2734
+                        $error_data_func($val, $dataModel->getError());
2735
+                    }
2736
+                }else{
2737
+                    $data = array_merge($data, $default_data);
2738
+                    $data['user_id']=$userData;
2739
+                    $data['activity_type_id'] = $customerData;
2740
+                    $data['activity_type'] = $activity_type;
2741
+                    unset($data['create_user_id']);
2742
+                    if (!$resData = $activityLogic->save($data)) {
2743
+                        $error_data_func($val, $dataModel->getError());
2744
+                    }
2745
+                }
2746
+            }
2747
+            // 完成数(已导入数)
2748
+            $done = ($page - 1) * $page_size + count($dataList);
2749
+            if ($page == $max_page) {
2750
+                $done = $total;
2751
+            }
2752
+            
2753
+            // 错误数
2754
+            $error = $error_row - 3;
2755
+            // 错误数据文件保存
2756
+            $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
2757
+            $objWriter->save($error_path);
2758
+           
2759
+            $this->error = [
2760
+                // 数据导入文件临时路径
2761
+                'temp_file' => $save_name,
2762
+                // 错误数据文件路径
2763
+                'error_file' => $error_data_file_name,
2764
+                // 文件总计条数
2765
+                'total' => $total,
2766
+                // 已完成条数
2767
+                'done' => $done,
2768
+                // 覆盖
2769
+                'cover' => $cover,
2770
+                // 错误数据写入行号
2771
+                'error' => $error,
2772
+                // 下次页码
2773
+                'page' => $page + 1,
2774
+                // 导入任务ID
2775
+                'import_queue_index' => $import_queue_index
2776
+            ];
2777
+           
2778
+            $queue->cache('last_import_cache', [
2779
+                'total' => $total,
2780
+                'done' => $done,
2781
+                'cover' => $cover,
2782
+                'error' => $error
2783
+            ]);
2784
+            // 执行完成
2785
+            if ($done >= $total) {
2786
+                // 出队
2787
+                $queue->dequeue();
2788
+                // 错误数据文件路径
2789
+                $this->error['error_file_path'] = 'temp/' . $error_data_file_name;
2790
+                // 删除导入文件
2791
+                @unlink($save_path);
2792
+                // 没有错误数据时,删除错误文件
2793
+                if ($error == 0) {
2794
+                    @unlink($error_path);
2795
+                }
2796
+                
2797
+                (new ImportRecord())->createData([
2798
+                    'type' => $types,
2799
+                    'total' => $total,
2800
+                    'done' => $done,
2801
+                    'cover' => $cover,
2802
+                    'error' => $error,
2803
+                    'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
2804
+                ]);
2805
+                Cache::set('item', 1, config('import_cache_time'));
2806
+                Cache::set('excel_item', serialize($this->error), config('import_cache_time'));
2807
+            } else {
2808
+                $excelData['cover'] = $cover;
2809
+                $excelData['page'] = $page + 1;
2810
+                $excelData['types'] = $types;
2811
+                $excelData['temp_file'] = $save_name;
2812
+                $excelData['error_file'] = $error_data_file_name;
2813
+                $excelData['create_user_id'] = $param['create_user_id'];
2814
+                $excelData['import_queue_index'] = $import_queue_index;
2815
+                $excelData['total'] = $total;
2816
+                $excelData['done'] = $done;
2817
+                $excelData['error'] = $error;
2818
+                $excelData['base'] = 'ActivityImport';
2819
+                Cache::set('item', 0, config('import_cache_time'));
2820
+                Cache::set('excel', $excelData, config('import_cache_time'));
2821
+            }
2822
+            return true;
2823
+        } else {
2824
+            $this->error = '请选择导入文件';
2825
+            $queue->dequeue();
2826
+            return false;
2827
+        }
2828
+    }
2829
+    
2830
+    /**
2831
+     * 自定义excel导入样式
2832
+     * @param $field_list
2833
+     * @param $param
2834
+     * @param $types
2835
+     *
2836
+     * @author      alvin guogaobo
2837
+     * @version     1.0 版本号
2838
+     * @since       2021/4/10 0010 09:27
2839
+     */
2840
+    public function importDown($field_list,$types,$save_path='')
2841
+    {
2842
+        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); //创建一个新的工作表
2843
+        //实例化主文件
2844
+        $objPHPExcel = new Spreadsheet();
2845
+        $worksheet = $spreadsheet->getActiveSheet();
2846
+        if ($save_path) {
2847
+            $worksheet->setCellValue('A2', '错误原因(导入时需删除本列)');
2848
+            $worksheet->getColumnDimension('A')->setWidth(40); //设置单元格宽度
2849
+            $k = 1;
2850
+        } else {
2851
+            $k = 0;
2852
+        }
2853
+        $worksheet->getColumnDimension('A1')->setWidth(70); //设置A列宽度为30
2854
+        foreach ($field_list as $v) {
2855
+            for ($j = 3; $j <= 70; $j++) {
2856
+                $worksheet->getStyle($this->stringFromColumnIndex($k).$j)->getNumberFormat()
2857
+                    ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
2858
+               }
2859
+            $worksheet->getColumnDimension($this->stringFromColumnIndex($k))->setWidth(40); //自动设置B列宽度
2860
+            //检查该字段若必填,加上"*"
2861
+            $v['name'] = sign_required($v['is_null'], $v['name']);
2862
+            $worksheet->setCellValue($this->stringFromColumnIndex($k) . '2', $v['name']);
2863
+            $k++;
2864
+        }
2865
+        //加上"*"颜色变红
2866
+        $worksheet -> getStyle('A2:C2') -> getFont()
2867
+            -> getColor() -> setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);
2868
+        $max_row = $this->stringFromColumnIndex($k-1);//列
2869
+        $mark_row = $this->stringFromColumnIndex($k);
2870
+        //样式设置 - 字体
2871
+        $worksheet->getStyle('A1:' . $max_row . '1')->getFont()
2872
+            ->setBold(true)->setName('宋体')
2873
+            ->setSize(11); //设置单元格A7:G10的字体样式
2874
+        $worksheet->getStyle('A2:' . $max_row . '2')->getFont()
2875
+           ->setBold(true)->setName('宋体')
2876
+            ->setSize(11); //设置单元格A7:G10的字体样式; //设置单元格A1的字体颜色
2877
+        //样式设置 - 行高
2878
+        $worksheet->getRowDimension('1')->setRowHeight(200); //设置第10行高度为100
2879
+        //样式设置 - 水平、垂直居中
2880
+        $styleArray = [
2881
+            'alignment' => [
2882
+                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT,
2883
+                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT
2884
+            ],
2885
+        ];
2886
+        $worksheet->getStyle('A1:'.$max_row.'1')->applyFromArray($styleArray);
2887
+        //样式设置 - 边框
2888
+        $styleArray = [
2889
+            'borders' => [
2890
+                'outline' => [
2891
+                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
2892
+                ],
2893
+                'inside' => [
2894
+                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
2895
+                ]
2896
+            ],
2897
+        ];
2898
+        $worksheet->getStyle('A1:'.$max_row.'1')->applyFromArray($styleArray);
2899
+        //样式设置 - 合并和拆分
2900
+        $worksheet->mergeCells('A1:'.$max_row.'1'); //合并单元格
2901
+        //内容设置
2902
+        $worksheet->setCellValue('A1', "
2903
+        注意事项:\n
2904
+        1、表头标“*”的红色字体为必填项\n
2905
+        2、跟进时间:推荐格式为2020-2-1\n
2906
+        3、若相关数据有多条时用“/”区分例如:杭州科技有限公司/卡卡罗特软件科技有限公司\n
2907
+        4、所属客户中的客户需要存在系统中,且填写的所属客户名称与系统中的客户名称必须保持一致否则会导入失败\n
2908
+        5、创建人为系统员工,请填写系统员工“姓名”,若匹配不到系统员工,则会导致导入失败\n
2909
+        6、如果系统中存在多个名称重复的情况,会默认导入到最新的数据中"
2910
+        ); //设置A1单元格内容为
2911
+        $worksheet->getStyle('A1')->getAlignment()->setWrapText(true);//合并单元格换行
2912
+
2913
+        //下载工作表
2914
+        ob_end_clean();
2915
+        if ($save_path) {
2916
+                $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
2917
+                $writer -> save($save_path);
2918
+        } else {
2919
+            header('Content-Type: application/vnd.ms-excel');
2920
+            header('Content-Disposition: attachment;filename="1.xls"');
2921
+            header('Cache-Control: max-age=0');
2922
+            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
2923
+            $writer->save('php://output');
2924
+        }
2925
+    }
2380 2926
 }

+ 264
- 220
application/admin/model/Field.php Zobrazit soubor

@@ -45,13 +45,15 @@ class Field extends Model
45 45
                 'field' => 'last_record',
46 46
                 'name' => '最后跟进记录',
47 47
                 'form_type' => 'text',
48
-                'width' => ''
48
+                'width' => '',
49
+                'is_hidden' => 0,
49 50
             ],
50 51
             [
51 52
                 'field' => 'last_time',
52 53
                 'name' => '最后跟进时间',
53 54
                 'form_type' => 'datetime',
54
-                'width' => ''
55
+                'width' => '',
56
+                'is_hidden' => 0,
55 57
             ],
56 58
         ],
57 59
         'crm_customer' => [
@@ -59,25 +61,29 @@ class Field extends Model
59 61
                 'field' => 'last_record',
60 62
                 'name' => '跟进记录',
61 63
                 'form_type' => 'text',
62
-                'width' => ''
64
+                'width' => '',
65
+                'is_hidden' => 0,
63 66
             ],
64 67
             [
65 68
                 'field' => 'last_time',
66 69
                 'name' => '最后跟进时间',
67 70
                 'form_type' => 'datetime',
68
-                'width' => ''
71
+                'width' => '',
72
+                'is_hidden' => 0,
69 73
             ],
70 74
             [
71 75
                 'field' => 'address',
72 76
                 'name' => '省、市、区/县',
73 77
                 'form_type' => 'customer_address',
74
-                'width' => ''
78
+                'width' => '',
79
+                'is_hidden' => 0,
75 80
             ],
76 81
             [
77 82
                 'field' => 'detail_address',
78 83
                 'name' => '详细地址',
79 84
                 'form_type' => 'text',
80
-                'width' => ''
85
+                'width' => '',
86
+                'is_hidden' => 0,
81 87
             ]
82 88
         ],
83 89
         'crm_contacts' => [
@@ -85,13 +91,15 @@ class Field extends Model
85 91
                 'field' => 'last_record',
86 92
                 'name' => '跟进记录',
87 93
                 'form_type' => 'text',
88
-                'width' => ''
94
+                'width' => '',
95
+                'is_hidden' => 0,
89 96
             ],
90 97
             [
91 98
                 'field' => 'last_time',
92 99
                 'name' => '最后跟进时间',
93 100
                 'form_type' => 'datetime',
94
-                'width' => ''
101
+                'width' => '',
102
+                'is_hidden' => 0,
95 103
             ],
96 104
         ],
97 105
         'crm_business' => [
@@ -99,13 +107,15 @@ class Field extends Model
99 107
                 'field' => 'last_record',
100 108
                 'name' => '跟进记录',
101 109
                 'form_type' => 'text',
102
-                'width' => ''
110
+                'width' => '',
111
+                'is_hidden' => 0,
103 112
             ],
104 113
             [
105 114
                 'field' => 'last_time',
106 115
                 'name' => '最后跟进时间',
107 116
                 'form_type' => 'datetime',
108
-                'width' => ''
117
+                'width' => '',
118
+                'is_hidden' => 0,
109 119
             ],
110 120
         ],
111 121
         'crm_contract' => [
@@ -113,31 +123,36 @@ class Field extends Model
113 123
                 'field' => 'check_status',
114 124
                 'name' => '审核状态',
115 125
                 'form_type' => 'text',
116
-                'width' => ''
126
+                'width' => '',
127
+                'is_hidden' => 0,
117 128
             ],
118 129
             [
119 130
                 'field' => 'last_record',
120 131
                 'name' => '跟进记录',
121 132
                 'form_type' => 'text',
122
-                'width' => ''
133
+                'width' => '',
134
+                'is_hidden' => 0,
123 135
             ],
124 136
             [
125 137
                 'field' => 'last_time',
126 138
                 'name' => '最后跟进时间',
127 139
                 'form_type' => 'datetime',
128
-                'width' => ''
140
+                'width' => '',
141
+                'is_hidden' => 0,
129 142
             ],
130 143
             [
131 144
                 'field' => 'done_money',
132 145
                 'name' => '已回款',
133 146
                 'form_type' => 'floatnumber',
134
-                'width' => ''
147
+                'width' => '',
148
+                'is_hidden' => 0,
135 149
             ],
136 150
             [
137 151
                 'field' => 'un_money',
138 152
                 'name' => '未回款',
139 153
                 'form_type' => 'floatnumber',
140
-                'width' => ''
154
+                'width' => '',
155
+                'is_hidden' => 0,
141 156
             ]
142 157
         ],
143 158
         'crm_receivables' => [
@@ -145,13 +160,15 @@ class Field extends Model
145 160
                 'field' => 'check_status',
146 161
                 'name' => '审核状态',
147 162
                 'form_type' => 'text',
148
-                'width' => ''
163
+                'width' => '',
164
+                'is_hidden' => 0,
149 165
             ],
150 166
             [
151 167
                 'field' => 'contract_money',
152 168
                 'name' => '合同金额',
153 169
                 'form_type' => 'floatnumber',
154
-                'width' => ''
170
+                'width' => '',
171
+                'is_hidden' => 0,
155 172
             ]
156 173
         ]
157 174
 
@@ -211,6 +228,16 @@ class Field extends Model
211 228
             return false;
212 229
         }
213 230
 
231
+        # 公海数据
232
+        $poolList = [];
233
+        $poolData = [];
234
+        if ($types == 'crm_customer') {
235
+            $poolList = db('crm_customer_pool')->column('pool_id');
236
+        }
237
+
238
+        # 用户自定义字段
239
+        $userFields = db('admin_user_field')->field(['id', 'datas'])->where('types', $types)->select();
240
+
214 241
         $error_message = [];
215 242
         $i = 0;
216 243
         foreach ($param as $k => $data) {
@@ -270,9 +297,21 @@ class Field extends Model
270 297
                 } else {
271 298
                     $resField = $this->data($data)->allowField(true)->save();
272 299
                 }
300
+                # 处理公海字段数据
301
+                if ($types == 'crm_customer') {
302
+                    foreach ($poolList AS $k1 => $poolId) {
303
+                        $poolData[] = [
304
+                            'pool_id' => $poolId,
305
+                            'name' => $data['name'],
306
+                            'field_name' => $data['field'],
307
+                            'form_type' => $data['form_type'],
308
+                            'is_hidden' => 1
309
+                        ];
310
+                    }
311
+                }
312
+
273 313
                 if ($types !== 'oa_examine') {
274 314
                     if ($resField) {
275
-                        actionLog($this->field_id, '', '', ''); //操作日志
276 315
                         $this->tableName = $types;
277 316
                         $maxlength = '255';
278 317
                         $defaultvalue = $data['default_value'] ? "DEFAULT '" . $data['default_value'] . "'" : "DEFAULT NULL";
@@ -324,12 +363,30 @@ class Field extends Model
324 363
                             $this->where(['field_id' => $this->field_id])->delete();
325 364
                             $error_message[] = $data['name'] . ',添加失败';
326 365
                         }
366
+                        # 处理用户自定义字段数据
367
+                        if ($resData !== false && !empty($userFields)) {
368
+                            foreach ($userFields AS $key => $value) {
369
+                                $userFields[$key]['datas'] = json_decode($value['datas'], true);
370
+                                $userFields[$key]['datas'][$data['field']] = ['width' => '', 'is_hide' => 0];
371
+                                $userFields[$key]['datas'] = json_encode($userFields[$key]['datas']);
372
+                            }
373
+                        }
327 374
                     } else {
328 375
                         $error_message[] = $data['name'] . ',添加失败';
329 376
                     }
330 377
                 }
331 378
             }
332 379
         }
380
+        # 更新用户自定义字段
381
+        if (!empty($userFields)) {
382
+            foreach ($userFields AS $key => $value) {
383
+                db('admin_user_field')->where('id', $value['id'])->update(['datas' => $value['datas']]);
384
+            }
385
+        }
386
+        # 更新公海字段
387
+        if (!empty($poolData)) {
388
+            db('crm_customer_pool_field_setting')->insertAll($poolData);
389
+        }
333 390
         if ($error_message) {
334 391
             $this->error = implode(';', $error_message);
335 392
             return false;
@@ -374,13 +431,21 @@ class Field extends Model
374 431
      * @return    [array]
375 432
      * @author Michael_xu
376 433
      */
377
-    public function updateDataById($param)
434
+    public function updateDataById($param, $types = '')
378 435
     {
379 436
         $error_message = [];
380 437
         if (!is_array($param)) {
381 438
             $this->error = '参数错误';
382 439
             return false;
383 440
         }
441
+        # 查询老数据
442
+        $oldData = [];
443
+        if (!empty($types) && $types == 'crm_customer') {
444
+            $oldList = db('admin_field')->field(['field', 'name'])->where('types', $types)->select();
445
+            foreach ($oldList AS $key => $value) {
446
+                $oldData[$value['field']] = $value['name'];
447
+            }
448
+        }
384 449
         $i = 0;
385 450
         foreach ($param as $data) {
386 451
             $i++;
@@ -419,7 +484,11 @@ class Field extends Model
419 484
                 $resField = db('admin_field')->where(['field_id' => $field_id])->update($data);
420 485
                 if ($dataInfo['types'] !== 'oa_examine') {
421 486
                     if ($resField) {
422
-                        actionLog($field_id); //操作日志
487
+                        # 更新公海字段
488
+                        if (!empty($oldData[$data['field']]) && $data['name'] != $oldData[$data['field']]['name']) {
489
+                            db('crm_customer_pool_field_setting')->where('field_name', $data['field'])->update(['name' => $data['name']]);
490
+                        }
491
+                        //actionLog($field_id); //操作日志
423 492
                         $this->tableName = $dataInfo['types'];
424 493
                         $maxlength = '255';
425 494
                         $defaultvalue = $data['default_value'] ? "DEFAULT '" . $data['default_value'] . "'" : "DEFAULT NULL";
@@ -486,11 +555,13 @@ class Field extends Model
486 555
      * @param $types 分类
487 556
      * @author Michael_xu
488 557
      */
489
-    public function delDataById($ids)
558
+    public function delDataById($ids, $types = '')
490 559
     {
491 560
         if (!is_array($ids)) {
492 561
             $ids[] = $ids;
493 562
         }
563
+        # 删除公海字段的条件
564
+        $poolWhere = [];
494 565
         $delMessage = [];
495 566
         foreach ($ids as $id) {
496 567
             $dataInfo = [];
@@ -545,12 +616,19 @@ class Field extends Model
545 616
                                 $resScene = $sceneModel->updateData($data, $val['scene_id']);
546 617
                             }
547 618
                         }
619
+                        # 处理删除公海字段的条件
620
+                        if (!empty($types) && $types == 'crm_customer' && !empty($dataInfo['field'])) $poolWhere[] = $dataInfo['field'];
548 621
                     } else {
549 622
                         $delMessage[] = $dataInfo['name'] . ',删除失败';
550 623
                     }
551 624
                 }
552 625
             }
553 626
         }
627
+        # 删除公海字段
628
+        if (!empty($poolWhere)) {
629
+            db('crm_customer_pool_field_setting')->whereIn('field_name', $poolWhere)->delete();
630
+        }
631
+
554 632
         return $delMessage ? implode(';', $delMessage) : '';
555 633
     }
556 634
 
@@ -623,7 +701,7 @@ class Field extends Model
623 701
             $types = 'crm_customer_pool';
624 702
         }
625 703
         if ($param['action'] == 'excel') {
626
-            $map['form_type'] = array('not in', ['file', 'form', 'user', 'structure']);
704
+            $map['form_type'] = array('not in', ['file', 'form','deal_status']);//删除了过滤structure  user字段类型数据 添加deal_status
627 705
         } elseif ($param['action'] == 'index') {
628 706
             $map['form_type'] = array('not in', ['file', 'form']);
629 707
         }
@@ -631,9 +709,7 @@ class Field extends Model
631 709
         $order = 'order_id asc, field_id asc';
632 710
         if ($param['action'] == 'index' || $param['action'] == 'pool') {
633 711
             $field_list = $this->getIndexFieldConfig($types, $param['user_id']);
634
-            // $order = new \think\db\Expression('field(field_id,'..')');
635 712
             foreach ($field_list as $k => $v) {
636
-
637 713
                 # 处理字段授权
638 714
                 $field_list[$k]['writeStatus'] = 1;
639 715
                 if (!$userLevel && $param['module'] == 'crm' && !empty($grantData[$param['types']])) {
@@ -650,8 +726,63 @@ class Field extends Model
650 726
                 }
651 727
             }
652 728
 
729
+            # 客户模块增加锁定状态、距进入公海天数字段
730
+            if (!$userLevel && $param['types'] == 'crm_customer' && !empty($grantData[$param['types']])) {
731
+                $poolDayStatus = getFieldGrantStatus('pool_day', $grantData[$param['types']]);
732
+                if (!empty($poolDayStatus['read'])) {
733
+                    $field_list[] = [
734
+                        'field'       => 'pool_day',
735
+                        'name'        => '距进入公海天数',
736
+                        'form_type'   => 'text',
737
+                        'writeStatus' => 0,
738
+                        'fieldName'   => 'pool_day'
739
+                    ];
740
+                }
741
+
742
+                $isLockStatus = getFieldGrantStatus('is_lock', $grantData[$param['types']]);
743
+                if (!empty($isLockStatus['read'])) {
744
+                    $field_list[] = [
745
+                        'field'       => "is_lock",
746
+                        'fieldName'   => "is_lock",
747
+                        'form_type'   => "text",
748
+                        'name'        => "锁定状态",
749
+                        'writeStatus' => 0
750
+                    ];
751
+                }
752
+            }
753
+
754
+            if ($userLevel) {
755
+                $field_list[] = [
756
+                    'field'       => 'pool_day',
757
+                    'name'        => '距进入公海天数',
758
+                    'form_type'   => 'text',
759
+                    'writeStatus' => 0,
760
+                    'fieldName'   => 'pool_day'
761
+                ];
762
+                $field_list[] = [
763
+                    'field'       => "is_lock",
764
+                    'fieldName'   => "is_lock",
765
+                    'form_type'   => "text",
766
+                    'name'        => "锁定状态",
767
+                    'writeStatus' => 0
768
+                ];
769
+            }
770
+
771
+
653 772
         } else {
654
-            $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();
773
+            $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();
774
+
775
+            # 详情页面增加负责人字段
776
+            if ($param['action'] == 'read' && !in_array($param['types'], ['crm_visit', 'crm_product','oa_examine'])) {
777
+                $field_list[] = [
778
+                    'field'       => 'owner_user_id',
779
+                    'name'        => '负责人',
780
+                    'form_type'   => 'user',
781
+                    'writeStatus' => 0,
782
+                    'fieldName'   => 'owner_user_name',
783
+                    'value'       => $dataInfo['owner_user_name'],
784
+                ];
785
+            }
655 786
 
656 787
             //客户
657 788
             if (in_array($param['types'], ['crm_customer'])) {
@@ -693,17 +824,17 @@ class Field extends Model
693 824
                     $status = getFieldGrantStatus($v['field'], $grantData[$param['types']]);
694 825
 
695 826
                     # 查看权限
696
-                    if ($status['read'] == 0) {
827
+                    if (empty($status['read'])) {
697 828
                         unset($field_list[(int)$k]);
698 829
                         continue;
699 830
                     }
700 831
 
701 832
                     # 编辑权限
702
-                    $field_list[$k]['writeStatus'] = $status['write'];
833
+                    if ($param['action'] != 'save') $field_list[$k]['writeStatus'] = $status['write'];
703 834
                 }
704 835
 
705 836
                 # (联系人,商机,合同,回款,回访)关联其他模块的字段在详情页面不允许修改;创建人、负责人不允许修改
706
-                if ($param['action'] == 'read' && in_array($v['field'], ['customer_id', 'business_id', 'contacts_id', 'contract_id', 'create_user_id', 'owner_user_id'])) {
837
+                if ($param['action'] == 'read' && in_array($v['field'], ['customer_id', 'business_id', 'contacts_id', 'contract_id', 'create_user_id', 'owner_user_id', 'plan_id'])) {
707 838
                     $field_list[$k]['writeStatus'] = 0;
708 839
                 }
709 840
 
@@ -978,18 +1109,32 @@ class Field extends Model
978 1109
     }
979 1110
 
980 1111
     /**
981
-     * [validateField 自定义字段验证规则]
982
-     * @param
983
-     * @author Michael_xu
1112
+     * 自定义字段验证规则
1113
+     * @param string $types 类型:crm_customer crm_business ...
1114
+     * @param int $types_id 自定义表types_id
1115
+     * @param string $action 操作:save update
1116
+     * @return array
984 1117
      */
985
-    public function validateField($types, $types_id = 0)
1118
+    public function validateField($types, $types_id = 0, $action = 'save')
986 1119
     {
1120
+        $apiCommon = new ApiCommon();
1121
+        $userId = $apiCommon->userInfo['id'];
1122
+        $grantData = getFieldGrantData($userId);
1123
+        $userLevel = isSuperAdministrators($userId);
987 1124
         $unField = ['update_time', 'create_time', 'create_user_id', 'owner_user_id'];
988 1125
         $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();
989 1126
         $validateArr = [];
990 1127
         $rule = [];
991 1128
         $message = [];
992 1129
         foreach ($fieldList as $field) {
1130
+            # 字段授权
1131
+            if (!$userLevel && !empty($grantData[$types])) {
1132
+                $status = getFieldGrantStatus($field['field'], $grantData[$types]);
1133
+
1134
+                # 没有字段查看权限或者编辑时没有字段修改权限就跳过验证
1135
+                if (empty($status['read']) || ($action != 'save' && empty($status['write']))) continue;
1136
+            }
1137
+
993 1138
             $rule_value = '';
994 1139
             $scene_value = '';
995 1140
 
@@ -1532,25 +1677,33 @@ class Field extends Model
1532 1677
     }
1533 1678
 
1534 1679
     /**
1535
-     * 获取发票高级搜索字段
1680
+     * 处理字段别名、权限
1536 1681
      *
1537
-     * @return array[]
1682
+     * @param int $userId 用户ID
1683
+     * @param string $types 模块类型
1684
+     * @param string $action 行为
1685
+     * @param array $data 字段数据
1686
+     * @author fanqi
1687
+     * @since 2021-04-06
1688
+     * @return array
1538 1689
      */
1539
-    private function getInvoiceSearch()
1690
+    public function resetField($userId, $types, $action, $data)
1540 1691
     {
1541
-        return [
1542
-            ['field' => 'invoice_number', 'form_type' => 'text', 'setting' => [], 'name' => '发票号码'],
1543
-            ['field' => 'real_invoice_date', 'form_type' => 'datetime', 'setting' => [], 'name' => '实际开票日期'],
1544
-            ['field' => 'logistics_number', 'form_type' => 'text', 'setting' => [], 'name' => '物流单号'],
1545
-            ['field' => 'invoice_status', 'form_type' => 'select', 'setting' => ['未开票', '已开票'], 'name' => '开票状态'],
1546
-            ['field' => 'check_status', 'form_type' => 'select', 'setting' => ['待审核', '审核中', '审核通过', '审核未通过', '撤回'], 'name' => '审核状态'],
1547
-            ['field' => 'owner_user_id', 'form_type' => 'user', 'setting' => [], 'name' => '负责人']
1548
-        ];
1549
-    }
1692
+        $grantData = getFieldGrantData($userId);
1693
+        $userLevel = isSuperAdministrators($userId);
1550 1694
 
1551
-    public function resetField($types, $data)
1552
-    {
1553 1695
         foreach ($data AS $key => $value) {
1696
+            # 处理字段授权
1697
+            if (!$userLevel && !empty($grantData[$types])) {
1698
+                $status = getFieldGrantStatus($value['field'], $grantData[$types]);
1699
+
1700
+                # 查看权限
1701
+                if ($status['read'] == 0) {
1702
+                    unset($data[(int)$key]);
1703
+                    continue;
1704
+                }
1705
+            }
1706
+
1554 1707
             switch ($value['field']) {
1555 1708
                 case 'create_user_id' :
1556 1709
                     $data[$key]['fieldName'] = 'create_user_name';
@@ -1592,185 +1745,76 @@ class Field extends Model
1592 1745
             if (in_array($value['form_type'], ['user', 'structure']) && !in_array($value['field'], ['create_user_id', 'owner_user_id'])) {
1593 1746
                 $data[$key]['fieldName'] = $value['field'] . '_name';
1594 1747
             }
1595
-        }
1596 1748
 
1597
-        # 线索
1598
-//        if ($types == 'crm_leads') {
1599
-//            foreach ($data as $key => $value) {
1600
-//                switch ($value['field']) {
1601
-//                    case 'create_user_id' :
1602
-//                        $data[$key]['fieldName'] = 'create_user_name';
1603
-//                        break;
1604
-//                    case 'owner_user_id' :
1605
-//                        $data[$key]['fieldName'] = 'owner_user_name';
1606
-//                        break;
1607
-//                    default :
1608
-//                        $data[$key]['fieldName'] = $value['field'];
1609
-//                }
1610
-//            }
1611
-//        }
1612
-
1613
-        # 客户
1614
-//        if ($types == 'crm_customer') {
1615
-//            foreach ($data as $key => $value) {
1616
-//                switch ($value['field']) {
1617
-//                    case 'create_user_id' :
1618
-//                        $data[$key]['fieldName'] = 'create_user_name';
1619
-//                        break;
1620
-//                    case 'owner_user_id' :
1621
-//                        $data[$key]['fieldName'] = 'owner_user_name';
1622
-//                        break;
1623
-//                    default :
1624
-//                        $data[$key]['fieldName'] = $value['field'];
1625
-//                }
1626
-//            }
1627
-//        }
1628
-
1629
-        # 联系人
1630
-//        if ($types == 'crm_contacts') {
1631
-//            foreach ($data as $key => $value) {
1632
-//                switch ($value['field']) {
1633
-//                    case 'customer_id' :
1634
-//                        $data[$key]['fieldName'] = 'customer_name';
1635
-//                        break;
1636
-//                    case 'create_user_id' :
1637
-//                        $data[$key]['fieldName'] = 'create_user_name';
1638
-//                        break;
1639
-//                    case 'owner_user_id' :
1640
-//                        $data[$key]['fieldName'] = 'owner_user_name';
1641
-//                        break;
1642
-//                    default :
1643
-//                        $data[$key]['fieldName'] = $value['field'];
1644
-//                }
1645
-//            }
1646
-//        }
1647
-
1648
-        # 商机
1649
-//        if ($types == 'crm_business') {
1650
-//            foreach ($data as $key => $value) {
1651
-//                switch ($value['field']) {
1652
-//                    case 'customer_id' :
1653
-//                        $data[$key]['fieldName'] = 'customer_name';
1654
-//                        break;
1655
-//                    case 'type_id' :
1656
-//                        $data[$key]['fieldName'] = 'type_id_info';
1657
-//                        break;
1658
-//                    case 'status_id' :
1659
-//                        $data[$key]['fieldName'] = 'status_id_info';
1660
-//                        break;
1661
-//                    case 'create_user_id' :
1662
-//                        $data[$key]['fieldName'] = 'create_user_name';
1663
-//                        break;
1664
-//                    case 'owner_user_id' :
1665
-//                        $data[$key]['fieldName'] = 'owner_user_name';
1666
-//                        break;
1667
-//                    default :
1668
-//                        $data[$key]['fieldName'] = $value['field'];
1669
-//                }
1670
-//            }
1671
-//        }
1672
-
1673
-        # 合同
1674
-//        if ($types == 'crm_contract') {
1675
-//            foreach ($data as $key => $value) {
1676
-//                switch ($value['field']) {
1677
-//                    case 'customer_id' :
1678
-//                        $data[$key]['fieldName'] = 'customer_name';
1679
-//                        break;
1680
-//                    case 'business_id' :
1681
-//                        $data[$key]['fieldName'] = 'business_name';
1682
-//                        break;
1683
-//                    case 'contacts_id' :
1684
-//                        $data[$key]['fieldName'] = 'contacts_name';
1685
-//                        break;
1686
-//                    case 'order_user_id' :
1687
-//                        $data[$key]['fieldName'] = 'order_user_name';
1688
-//                        break;
1689
-//                    case 'create_user_id' :
1690
-//                        $data[$key]['fieldName'] = 'create_user_name';
1691
-//                        break;
1692
-//                    case 'owner_user_id' :
1693
-//                        $data[$key]['fieldName'] = 'owner_user_name';
1694
-//                        break;
1695
-//                    default :
1696
-//                        $data[$key]['fieldName'] = $value['field'];
1697
-//                }
1698
-//            }
1699
-//        }
1700
-
1701
-        # 回款
1702
-//        if ($types == 'crm_receivables') {
1703
-//            foreach ($data as $key => $value) {
1704
-//                switch ($value['field']) {
1705
-//                    case 'customer_id' :
1706
-//                        $data[$key]['fieldName'] = 'customer_name';
1707
-//                        break;
1708
-//                    case 'contract_id' :
1709
-//                        $data[$key]['fieldName'] = 'contract_num';
1710
-//                        break;
1711
-//                    case 'create_user_id' :
1712
-//                        $data[$key]['fieldName'] = 'create_user_name';
1713
-//                        break;
1714
-//                    case 'owner_user_id' :
1715
-//                        $data[$key]['fieldName'] = 'owner_user_name';
1716
-//                        break;
1717
-//                    case 'plan_id' :
1718
-//                        $data[$key]['fieldName'] = 'plan_id_info';
1719
-//                        break;
1720
-//                    default :
1721
-//                        $data[$key]['fieldName'] = $value['field'];
1722
-//                }
1723
-//            }
1724
-//        }
1725
-
1726
-        # 回访
1727
-//        if ($types == 'crm_visit') {
1728
-//            foreach ($data as $key => $value) {
1729
-//                switch ($value['field']) {
1730
-//                    case 'customer_id' :
1731
-//                        $data[$key]['fieldName'] = 'customer_name';
1732
-//                        break;
1733
-//                    case 'owner_user_id' :
1734
-//                        $data[$key]['fieldName'] = 'owner_user_name';
1735
-//                        $data[$key]['name'] = '回访人';
1736
-//                        break;
1737
-//                    case 'contacts_id' :
1738
-//                        $data[$key]['fieldName'] = 'contacts_name';
1739
-//                        break;
1740
-//                    case 'contract_id' :
1741
-//                        $data[$key]['fieldName'] = 'contract_number';
1742
-//                        break;
1743
-//                    case 'create_user_id' :
1744
-//                        $data[$key]['fieldName'] = 'create_user_name';
1745
-//                        break;
1746
-//                    default :
1747
-//                        $data[$key]['fieldName'] = $value['field'];
1748
-//                }
1749
-//            }
1750
-//        }
1751
-
1752
-        # 产品
1753
-//        if ($types == 'crm_product') {
1754
-//            foreach ($data as $key => $value) {
1755
-//                switch ($value['field']) {
1756
-//                    case 'category_id' :
1757
-//                        $data[$key]['fieldName'] = 'category_name';
1758
-//                        break;
1759
-//                    case 'create_user_id' :
1760
-//                        $data[$key]['fieldName'] = 'create_user_name';
1761
-//                        break;
1762
-//                    case 'owner_user_id' :
1763
-//                        $data[$key]['fieldName'] = 'owner_user_name';
1764
-//                        break;
1765
-//                    default :
1766
-//                        $data[$key]['fieldName'] = $value['field'];
1767
-//                }
1768
-//            }
1769
-//        }
1749
+            # 详情中不显示产品类别、回款期数
1750
+            if ($action == 'read' && in_array($value['field'], ['category_id'])) {
1751
+                unset($data[(int)$key]);
1752
+            }
1753
+        }
1770 1754
 
1771 1755
         return $data;
1772 1756
     }
1773 1757
 
1758
+    /**
1759
+     * 获取公海自定义字段数据
1760
+     *
1761
+     * @param $poolId
1762
+     * @param $dataInfo
1763
+     * @return bool|\PDOStatement|string|\think\Collection
1764
+     */
1765
+    public function getPoolFieldData($poolId, $dataInfo)
1766
+    {
1767
+        $poolFields = db('crm_customer_pool_field_setting')->field(['field_name AS field', 'form_type', 'name'])->where(['pool_id' => $poolId, 'is_hidden' => 0])->select();
1768
+
1769
+        foreach ($poolFields AS $key => $value) {
1770
+            # 字段值
1771
+            $poolFields[$key]['value'] = !empty($dataInfo[$value['field']]) ? $dataInfo[$value['field']] : '';
1772
+
1773
+            # 处理别名
1774
+            switch ($value['field']) {
1775
+                case 'create_user_id' :
1776
+                    $poolFields[$key]['fieldName'] = 'create_user_name';
1777
+                    $poolFields[$key]['value'] = !empty($dataInfo['create_user_id_info']) ? [$dataInfo['create_user_id_info']] : '';
1778
+                    break;
1779
+                case 'before_owner_user_id' :
1780
+                    $poolFields[$key]['fieldName'] = 'before_owner_user_name';
1781
+                    $poolFields[$key]['value'] = !empty($dataInfo['before_owner_user_id_info']) ? [$dataInfo['before_owner_user_id_info']] : '';
1782
+                    break;
1783
+                default :
1784
+                    $poolFields[$key]['fieldName'] = $value['field'];
1785
+            }
1786
+            if (in_array($value['form_type'], ['user', 'structure']) && !in_array($value['field'], ['create_user_id', 'owner_user_id', 'before_owner_user_id'])) {
1787
+                $poolFields[$key]['fieldName'] = $value['field_name'] . '_name';
1788
+            }
1789
+
1790
+            # 系统字段
1791
+            if (in_array($value['field'], ['last_record', 'create_user_id', 'create_time', 'update_time', 'last_time', 'before_owner_user_id'])) {
1792
+                $poolFields[$key]['system'] = 1;
1793
+            } else {
1794
+                $poolFields[$key]['system'] = 0;
1795
+            }
1796
+        }
1797
+
1798
+        return $poolFields;
1799
+    }
1800
+
1801
+    /**
1802
+     * 获取发票高级搜索字段
1803
+     *
1804
+     * @return array[]
1805
+     */
1806
+    private function getInvoiceSearch()
1807
+    {
1808
+        return [
1809
+            ['field' => 'invoice_number', 'form_type' => 'text', 'setting' => [], 'name' => '发票号码'],
1810
+            ['field' => 'real_invoice_date', 'form_type' => 'datetime', 'setting' => [], 'name' => '实际开票日期'],
1811
+            ['field' => 'logistics_number', 'form_type' => 'text', 'setting' => [], 'name' => '物流单号'],
1812
+            ['field' => 'invoice_status', 'form_type' => 'select', 'setting' => ['未开票', '已开票'], 'name' => '开票状态'],
1813
+            ['field' => 'check_status', 'form_type' => 'select', 'setting' => ['待审核', '审核中', '审核通过', '审核未通过', '撤回'], 'name' => '审核状态'],
1814
+            ['field' => 'owner_user_id', 'form_type' => 'user', 'setting' => [], 'name' => '负责人']
1815
+        ];
1816
+    }
1817
+
1774 1818
     /**
1775 1819
      * 获取产品父类层级(不包含自身)
1776 1820
      *

+ 13
- 3
application/admin/model/Group.php Zobrazit soubor

@@ -7,6 +7,7 @@
7 7
 
8 8
 namespace app\admin\model;
9 9
 
10
+use app\admin\controller\ApiCommon;
10 11
 use app\admin\model\Common;
11 12
 
12 13
 class Group extends Common 
@@ -85,9 +86,11 @@ class Group extends Common
85 86
 			//项目模块下角色
86 87
 			$param['type'] = 0;
87 88
 		}
89
+		$userInfo=new ApiCommon();
90
+		$user_id=$userInfo->userInfo;
88 91
 		$flag = $this->insertGetId($param);
89 92
 		if ($flag) {
90
-			return $flag;
93
+          return $flag;
91 94
 		} else {
92 95
 			$this->error = '操作失败';
93 96
 			return false;
@@ -122,7 +125,10 @@ class Group extends Common
122 125
         }
123 126
 		$flag = $this->where('id = '.$group_id)->update($param);
124 127
 		if ($flag) {
125
-			return true;
128
+		    $user=new ApiCommon();
129
+		    $user_id=$user->userInfo;
130
+            SystemActionLog($user_id['id'], 'admin_group','role', $group_id,  'update', $dataInfo['title'], '', '','编辑了:'.$dataInfo['title']);
131
+            return true;
126 132
 		} else {
127 133
 			$this->error = '操作失败';
128 134
 			return false;
@@ -143,7 +149,11 @@ class Group extends Common
143 149
 		}
144 150
 		$flag = $this->where('id = '.$group_id)->delete();
145 151
 		if ($flag) {
146
-			return true;
152
+		    # 系统操作记录
153
+            $user=new ApiCommon();
154
+            $user_id=$user->userInfo;
155
+            SystemActionLog($user_id['id'], 'admin_group','role', $group_id,  'update', $dataInfo['title'], '', '','删除了角色:'.$dataInfo['title']);
156
+            return true;
147 157
 		} else {
148 158
 			$this->error = '删除失败';
149 159
 			return false;

+ 10
- 3
application/admin/model/LoginRecord.php Zobrazit soubor

@@ -50,10 +50,11 @@ class LoginRecord extends Common
50 50
 
51 51
     /**
52 52
      * 添加登录记录
53
-     *
53
+     * todo 登录设备暂时不加 数据表字段未加。
54 54
      * @param int $type
55
+     * @param int $platform 登录设备
55 56
      */
56
-    public function createRecord($type = 0)
57
+    public function createRecord($platform='',$type = 0)
57 58
     {
58 59
         $data = [];
59 60
         $data['type'] = $type;
@@ -62,7 +63,13 @@ class LoginRecord extends Common
62 63
         $data['ip'] = (new Scan())->get_client_ip();
63 64
         $data['os'] = getOS();
64 65
         $data['browser'] = getBrowser();
65
-
66
+        # todo登录设备暂时不加 数据表字段未加
67
+//        $platform=['_mobile'=>'手机','_ding'=>'钉钉','_wechat'=>'微信','_wxwork'=>'企业微信'];
68
+//        if(empty($platform)){
69
+//            $data['device']='网页';
70
+//        }else{
71
+//            $data['device']=$platform[$platform];
72
+//        }
66 73
         $ip_address = getAddressById($data['ip']);
67 74
         $data['address'] = $ip_address['country'];
68 75
 

+ 1
- 0
application/admin/model/Market.php Zobrazit soubor

@@ -0,0 +1 @@
1
+<?php

+ 7
- 0
application/admin/model/Message.php Zobrazit soubor

@@ -161,6 +161,10 @@ class Message extends Common
161 161
      * 退出合同团队
162 162
      */
163 163
     const CONTRACT_END = 30;
164
+    /**
165
+     * 移除团队成员
166
+     */
167
+    const TEAM_END = 31;
164 168
 
165 169
     /**
166 170
      * 消息类型
@@ -266,6 +270,9 @@ class Message extends Common
266 270
         30 => [
267 271
             'template' => '{from_user} 退出了您合同 {title} 的团队。',
268 272
         ],
273
+        31 => [
274
+            'template' => '将{from_user} 移除了您 {title} 的团队。',
275
+        ],
269 276
     ];
270 277
 
271 278
     /**

+ 7
- 3
application/admin/model/Scene.php Zobrazit soubor

@@ -58,6 +58,8 @@ class Scene extends Common
58 58
                     'name'      => $v['name'],
59 59
                     'type'      => $v['type']
60 60
                 ];
61
+                if (!empty($v['start'])) $sceneData[$k]['start'] = $v['start'];
62
+                if (!empty($v['end'])) $sceneData[$k]['end'] = $v['end'];
61 63
             }
62 64
         }
63 65
         if (!empty($sceneData)) $param['data'] = $sceneData;
@@ -122,8 +124,8 @@ class Scene extends Common
122 124
 				foreach ($data as $key=>$val) {
123 125
 					$setting = $newFieldList[$key]['setting'];
124 126
 	    			$data[$key]['setting'] = $setting;
125
-	    			if ($val['form_type'] == 'user' && $val['value']) {
126
-	    				$userInfo = $userModel->getUserById($val['value']);
127
+	    			if ($val['form_type'] == 'user' && !empty($val['value'][0])) {
128
+	    				$userInfo = $userModel->getUserById($val['value'][0]);
127 129
 	    				$data[$key]['setting']['realname'] = $userInfo['realname'];
128 130
 	    				$data[$key]['setting']['id'] = $userInfo['id'];
129 131
 	    			} 
@@ -192,7 +194,7 @@ class Scene extends Common
192 194
 			$this->error = '场景名称必填';
193 195
 			return false;
194 196
 		}
195
-		if ($this->where(['scene_id'=>['neq',$id],'types'=>$types,'user_id'=>$user_id,'name'=>$param['name']])->find()) {
197
+		if ($this->where(['scene_id' => ['neq', $id], 'types' => $param['types'], 'user_id' => $user_id,'name' => $param['name']])->find()) {
196 198
 			$this->error = '场景名称已存在';
197 199
 			return false;
198 200
 		}
@@ -207,6 +209,8 @@ class Scene extends Common
207 209
                     'name'      => $v['name'],
208 210
                     'type'      => $v['type']
209 211
                 ];
212
+                if (!empty($v['start'])) $sceneData[$k]['start'] = $v['start'];
213
+                if (!empty($v['end'])) $sceneData[$k]['end'] = $v['end'];
210 214
             }
211 215
         }
212 216
         if (!empty($sceneData)) $param['data'] = $sceneData;

+ 12
- 2
application/admin/model/Structure.php Zobrazit soubor

@@ -7,6 +7,7 @@
7 7
 
8 8
 namespace app\admin\model;
9 9
 
10
+use app\admin\controller\ApiCommon;
10 11
 use app\admin\model\Common;
11 12
 use think\Db;
12 13
 
@@ -31,7 +32,11 @@ class Structure extends Common
31 32
 		if ($type == 'tree') {
32 33
 			$tree = new \com\Tree();
33 34
 			$data = $tree->list_to_tree($data, 'id', 'pid', 'child', 0, true, array(''));
34
-		}		
35
+		}
36
+		
37
+		foreach ($data as $k=>$v){
38
+		    $data[$k]['owner_user_name']=foreachData('admin_structure',$v['owner_user_id'])?:null;
39
+        }
35 40
 		return $data;
36 41
 	}
37 42
 	
@@ -85,7 +90,12 @@ class Structure extends Common
85 90
 			$this->error = '删除失败';
86 91
 			return false;
87 92
 		} else {
88
-			return true;
93
+            $apiCommon = new ApiCommon();
94
+            $userInfo = $apiCommon->userInfo;
95
+		    $content='删除了部门:'.$dataInfo['name'];
96
+            # 添加记录
97
+            SystemActionLog($userInfo['id'], 'admin_structure','structures', $id,'delete', $dataInfo['name'], '', '', $content);
98
+            return true;
89 99
 		}	
90 100
 	}
91 101
 

+ 167
- 52
application/admin/model/User.php Zobrazit soubor

@@ -7,6 +7,7 @@
7 7
 
8 8
 namespace app\admin\model;
9 9
 
10
+use app\admin\controller\ApiCommon;
10 11
 use think\Db;
11 12
 use app\admin\model\Common;
12 13
 use com\verify\HonrayVerify;
@@ -107,6 +108,8 @@ class User extends Common
107 108
      */	    
108 109
 	public function getDataList($request)
109 110
 	{
111
+	    $structure_status=$request['isNeedChild'];
112
+        unset($request['isNeedChild']);
110 113
 		$request = $this->fmtRequest( $request );
111 114
 		$fieldarray = ['search','group_id','structure_id','status','type','page','limit','pageType'];
112 115
 		$map = $request['map'] ? : [];
@@ -127,10 +130,15 @@ class User extends Common
127 130
 		// $map['user.id'] = array('neq', 1);
128 131
 		if($map['structure_id']){
129 132
 			//获取部门下员工列表
130
-			$str_ids = structureList($map['structure_id'],'');
131
-			$new_str_ids = rtrim($str_ids,',');
132
-			$map['user.structure_id'] = ['in',$new_str_ids]; //$map['structure_id'];
133
+            if($structure_status==1){
134
+                $str_ids = structureList($map['structure_id'],'');
135
+                $new_str_ids = rtrim($str_ids,',');
136
+                $map['user.structure_id'] = ['in',$new_str_ids]; //$map['structure_id'];
137
+            }else{
138
+                $map['user.structure_id']=['in',$map['structure_id']];
139
+            }
133 140
 		}
141
+        $structureData=db('admin_structure')->where('id',$map['structure_id'])->value('owner_user_id');
134 142
 		unset($map['structure_id']);
135 143
 		if ($map['status'] || $map['group_id']) {
136 144
 		    if ($map['status'] != 3) {
@@ -187,11 +195,20 @@ class User extends Common
187 195
 			$list[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
188 196
 			$list[$k]['s_name'] = !empty($v['s_name']) ? $v['s_name'] : '';
189 197
 			$list[$k]['structure_id'] = !empty($v['structure_id']) ? $v['structure_id'] : '';
190
-		}															
198
+			if($v['id']==1){
199
+                $list[$k]['userIdentity']=0;
200
+            }elseif($v['id']==$structureData){
201
+                $list[$k]['userIdentity']=1;
202
+            }else{
203
+                $list[$k]['userIdentity']=2;
204
+            }
205
+		}
206
+		//二位数组排序
207
+        $last_names = array_column($list,'userIdentity');
208
+        array_multisort($last_names,SORT_ASC,$list);
191 209
 		$data = [];			
192 210
 		$data['list'] = $list;				
193 211
 		$data['dataCount'] = $dataCount;
194
-					
195 212
 		return $data;
196 213
 	}
197 214
 
@@ -261,6 +278,10 @@ class User extends Common
261 278
             if(db('admin_user')->where('username',$param['username'])->find()){
262 279
                 $this->error = '手机号已存在';
263 280
                 return false;
281
+            }
282
+            if(db('admin_user')->where('realname',$param['realname'])->find()){
283
+                $this->error = '姓名已存在';
284
+                return false;
264 285
             }
265 286
 		} else {
266 287
 			if (empty($param['group_id']) || !is_array($param['group_id'])) {
@@ -268,6 +289,20 @@ class User extends Common
268 289
 				return false;
269 290
 			}		
270 291
 		}
292
+		$nameData=db('admin_user')->where('realname','like','%'.$param['realname'].'%')->column('realname');
293
+        if(in_array($param['realname'],$nameData)){
294
+            for($j=1;$j<100;$j++){
295
+                $name=$param['realname'].$j;
296
+                if(in_array($name,$nameData)){
297
+                }else{
298
+                    $name= $param['realname'].$j;
299
+                    break ;
300
+                }
301
+            }
302
+            $param['realname']= $name;
303
+        }else{
304
+            $param['realname']= $param['realname'];
305
+        }
271 306
 		// 验证
272 307
 		$validate = validate($this->name);
273 308
 		if (!$validate->check($param)) {
@@ -311,8 +346,12 @@ class User extends Common
311 346
 		
312 347
 			$this->commit();
313 348
 			$param['user_id'] = $data['user_id'];
314
-			$resSync = $syncModel->syncData($param);			
315
-			return true;
349
+			$resSync = $syncModel->syncData($param);
350
+            # 添加记录
351
+            $user=new ApiCommon();
352
+            $userInfo=$user->userInfo;
353
+            SystemActionLog($userInfo['id'], 'admin_user','employee', $user_id,  'save', $param['realname'], '', '','新增用户:'.$param['realname']);
354
+            return true;
316 355
 		} catch(\Exception $e) {
317 356
 			$this->rollback();
318 357
 			$this->error = '添加失败';
@@ -355,13 +394,15 @@ class User extends Common
355 394
 	 */
356 395
 	public function updateDataById($param, $id)
357 396
 	{
358
-	 
397
+        $user=new ApiCommon();
398
+        $user_id=$user->userInfo;
359 399
 		if ($param['user_id']) {
360 400
 			//修改个人信息
361 401
 			$data['email'] = $param['email'];
362 402
 			$data['sex'] = $param['sex'];
363 403
 			// $data['mobile'] = $param['username'];
364
-			if (db('admin_user')->where(['username' => $param['username'],'id' => ['neq',$param['user_id']]])->find()) {
404
+            $userInfo=db('admin_user')->where(['username' => $param['username'],'id' => ['neq',$param['user_id']]])->find();
405
+			if ($userInfo) {
365 406
 				$this->error = '手机号已存在';
366 407
 				return false;				
367 408
 			}
@@ -370,7 +411,8 @@ class User extends Common
370 411
 			 $data['post'] = $param['post'];
371 412
 			$flag = $this->where(['id' => $param['user_id']])->update($data);
372 413
 			if ($flag==0 || $flag==1) {
373
-				return true;
414
+                SystemActionLog($user_id['id'],'admin_user', 'employee', $param['user_id'], 'update', $param['realname'], '', '','编辑了:'.$param['realname']);
415
+                return true;
374 416
 			} else {
375 417
 				$this->error = '保存失败';
376 418
 				return false;
@@ -421,8 +463,8 @@ class User extends Common
421 463
 				$this->allowField(true)->save($param, ['id' => $id]);
422 464
 				$this->commit();
423 465
 				Cache::rm('user_info' . $id);
424
-				
425
-				// $data['mobile'] = $param['username'];	 	
466
+                SystemActionLog($user_id['id'], 'admin_user','employee', $id, 'update', $userInfo['realname'], '', '','编辑了:'.$userInfo['realname']);
467
+                // $data['mobile'] = $param['username'];
426 468
 				$data['email'] = $param['email'];	
427 469
 				$data['sex'] = $param['sex'];				
428 470
 				$data['update_time'] = time();
@@ -504,8 +546,8 @@ class User extends Common
504 546
 			$login_record->createRecord(LoginRecord::TYPE_USER_BANNED);
505 547
 			return false;
506 548
 		}
507
-		
508
-		$login_record->createRecord(LoginRecord::TYPE_SUCCESS);
549
+        $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
550
+		$login_record->createRecord($platform,LoginRecord::TYPE_SUCCESS);
509 551
 
510 552
         // 获取菜单和权限
511 553
         $dataList = $this->getMenuAndRule($userInfo['id']);
@@ -528,7 +570,6 @@ class User extends Common
528 570
         // $info['_AUTH_LIST_'] = $dataList['rulesList'];
529 571
         $info['authKey'] = $authKey;
530 572
         
531
-    	$platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
532 573
 		//删除旧缓存
533 574
         if (Cache::get('Auth_'.$userInfo['authkey'].$platform)) {
534 575
             Cache::rm('Auth_'.$userInfo['authkey'].$platform);
@@ -596,12 +637,17 @@ class User extends Common
596 637
 	        $resSync = $syncModel->syncData($syncData);        	
597 638
 
598 639
             $userInfo = $this->where('id', $userInfo['id'])->find();
640
+            # 添加记录
641
+            $user=new ApiCommon();
642
+            $user_id=$user->userInfo;
643
+            SystemActionLog($user_id['id'], 'admin_user','employee', $userInfo['id'], 'update', $userInfo['realname'], '', '','重置了密码:'.$userInfo['realname']);
599 644
             // 重新设置缓存
600 645
             session_start();
601 646
             $cache['userInfo'] = $userInfo;
602 647
             $cache['authKey'] = user_md5($userInfo['username'].$userInfo['password'].session_id(), $userInfo['salt']);
603 648
             cache('Auth_'.$cache['authKey'], null);
604 649
             cache('Auth_'.$cache['authKey'], $cache, $loginExpire);
650
+            
605 651
             return $cache['authKey'];//把auth_key传回给前端
606 652
         }
607 653
         $this->error = '修改失败';
@@ -613,21 +659,29 @@ class User extends Common
613 659
 	{
614 660
 		$syncModel = new \app\admin\model\Sync();
615 661
 		$flag = true;
662
+		$userInfo = new ApiCommon();
663
+		$user_id=$userInfo->userInfo;
616 664
 		foreach ($param['id'] as $value) {
617 665
 			$password = '';
618
-			$userInfo = db('admin_user')->where(['id' => $value])->find();;
666
+			$userInfo = db('admin_user')->where(['id' => $value])->find();
619 667
 			$salt = substr(md5(time()),0,4);
620 668
 			$temp['salt'] = $salt;
621 669
 			$temp['password']= $password = user_md5($param['password'], $salt, $userInfo['username']);
622 670
 			$flag = $flag && Db::name('AdminUser')->where('id ='.$value)->update($temp);
623
-
624
-			$syncData = [];
671
+            $syncData = [];
625 672
 	        $syncData['user_id'] = $value;
626 673
 	        $syncData['salt'] = $salt;
627 674
 	        $syncData['password'] = $password;
628 675
 	        $resSync = $syncModel->syncData($syncData);			
629 676
 		}
630 677
 		if ($flag) {
678
+		    foreach ($param['id'] as $v){
679
+                $userInfo = db('admin_user')->where(['id' => $v])->find();
680
+                # 添加记录
681
+                $user=new ApiCommon();
682
+                $user_id=$user->userInfo;
683
+                SystemActionLog($user_id['id'], 'admin_user','employee', $v,  'update',$userInfo['realname'],'', '', '重置了密码:'.$userInfo['realname']);
684
+            }
631 685
 			return $flag;
632 686
 		} else {
633 687
 			$this->error ='修改失败,请稍后重试';
@@ -733,9 +787,16 @@ class User extends Common
733 787
         if (in_array('calendar', $adminConfig)) {
734 788
             $authList['oa']['calendar'] = (Object)[];
735 789
         }
790
+        # 公海权限
791
+        $structureId = db('admin_user')->where('id', $u_id)->value('structure_id');
792
+        $poolStatus = db('crm_customer_pool')->whereLike('admin_user_ids', '%,' . $u_id . ',%')
793
+            ->whereOr('user_ids', 'like', '%,' . $u_id . ',%')
794
+            ->whereOr('department_ids', 'like', '%,' . $structureId . ',%')
795
+            ->value('pool_id');
796
+        if (!empty($poolStatus)) $authList['crm']['pool'] = ['index' => true];
736 797
 
737 798
 	    $ret['authList'] = $this->resetAuthorityFiled($authList);
738
-		$res['manage']=$rules;
799
+		$res['manage'] = $rules;
739 800
         return $ret;
740 801
     }
741 802
 
@@ -756,24 +817,10 @@ class User extends Common
756 817
             $authList['crm']['customer']['nearbyCustomer'] = $authList['crm']['customer']['nearby'];
757 818
             unset($authList['crm']['customer']['nearby']);
758 819
         }
820
+        # 公海权限
821
+        $authList['crm']['customer']['pool'] = !empty($authList['crm']['pool']['index']);;
759 822
         # 跟进记录
760 823
         $authList['crm']['followRecord'] = $authList['crm']['activity'];
761
-        # 公海
762
-        if (isset($authList['crm']['customer']['pool'])) {
763
-            $authList['crm']['pool']['index'] = $authList['crm']['customer']['pool'] ? true : false;
764
-        }
765
-        if (isset($authList['crm']['customer']['distribute'])) {
766
-            $authList['crm']['pool']['distribute'] = $authList['crm']['customer']['distribute'] ? true : false;
767
-        }
768
-        if (isset($authList['crm']['customer']['receive'])) {
769
-            $authList['crm']['pool']['receive'] = $authList['crm']['customer']['receive'] ? true : false;
770
-        }
771
-        if (isset($authList['crm']['customer']['poolexcelexport'])) {
772
-            $authList['crm']['pool']['excelexport'] = $authList['crm']['customer']['poolexcelexport'] ? true : false;
773
-        }
774
-        if (isset($authList['crm']['customer']['pooldelete'])) {
775
-            $authList['crm']['pool']['delete'] = $authList['crm']['customer']['pooldelete'] ? true : false;
776
-        }
777 824
         # 合同
778 825
         if (isset($authList['crm']['contract']['discard'])) {
779 826
             $authList['crm']['contract']['discard'] = false;
@@ -789,14 +836,6 @@ class User extends Common
789 836
         unset($authList['work']['work']);
790 837
         unset($authList['work']['task']);
791 838
         unset($authList['work']['taskclass']);
792
-        # 跟进记录
793
-        if (!empty($authList['crm']['record']['index'])) {
794
-            $authList['crm']['followRecord']['delete'] = true;
795
-            $authList['crm']['followRecord']['read'] = true;
796
-            $authList['crm']['followRecord']['save'] = true;
797
-            $authList['crm']['followRecord']['update'] = true;
798
-        }
799
-        unset($authList['crm']['record']);
800 839
         # admin:system
801 840
         if (!empty($authList['admin']['system']['index'])) {
802 841
             $authList['admin']['system']['read'] = $authList['admin']['system']['index'];
@@ -853,9 +892,9 @@ class User extends Common
853 892
             unset($authList['admin']['examine_flow']);
854 893
         }
855 894
         # admin:printing
856
-        if (!empty($authList['admin']['printing'])) {
857
-            $authList['admin']['print'] = $authList['admin']['printing'];
858
-            unset($authList['admin']['printing']);
895
+        if (!empty($authList['admin']['crm']['printing'])) {
896
+            $authList['admin']['crm']['print'] = $authList['admin']['crm']['printing'];
897
+            unset($authList['admin']['crm']['printing']);
859 898
         }
860 899
         # admin:work
861 900
         if (!empty($authList['admin']['work']['work'])) {
@@ -863,8 +902,19 @@ class User extends Common
863 902
             unset($authList['admin']['work']['work']);
864 903
         }
865 904
         # admin:log
866
-        unset($authList['admin']['loginrecord']);
867
-        unset($authList['admin']['log']);
905
+        if (isset($authList['admin']['adminlog']['loginlog'])) {
906
+            $authList['admin']['adminLog']['loginLog'] = $authList['admin']['adminlog']['loginlog'];
907
+            unset($authList['admin']['adminlog']['loginlog']);
908
+        }
909
+        if (isset($authList['admin']['adminlog']['actionrecord'])) {
910
+            $authList['admin']['adminLog']['actionRecord'] = $authList['admin']['adminlog']['actionrecord'];
911
+            unset($authList['admin']['adminlog']['actionrecord']);
912
+        }
913
+        if (isset($authList['admin']['adminlog']['systemlog'])) {
914
+            $authList['admin']['adminLog']['systemLog'] = $authList['admin']['adminlog']['systemlog'];
915
+            unset($authList['admin']['adminlog']['systemlog']);
916
+        }
917
+        unset($authList['admin']['adminlog']);
868 918
         # admin:initialize
869 919
         if (!empty($authList['admin']['initialize'])) {
870 920
             $authList['admin']['init']['initData'] = $authList['admin']['initialize']['update'];
@@ -1032,7 +1082,7 @@ class User extends Common
1032 1082
 					'structure.name' => 'structure_name',
1033 1083
 					'structure.id' => 'structure_id'
1034 1084
 				])
1035
-				->cache('user_info' . $id, null, 'user_info')
1085
+//				->cache('user_info' . $id, null, 'user_info')
1036 1086
 				->find();
1037 1087
 		$data['img'] = $data['img'] ? getFullPath($data['img']) : '';
1038 1088
 		$data['thumb_img'] = $data['thumb_img'] ? getFullPath($data['thumb_img']) : '';
@@ -1088,7 +1138,7 @@ class User extends Common
1088 1138
 		$list = $this
1089 1139
 				->alias('user')
1090 1140
 				->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
1091
-				->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();
1141
+				->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();
1092 1142
 		return $list ? : [];
1093 1143
 	}
1094 1144
 
@@ -1241,7 +1291,7 @@ class User extends Common
1241 1291
 	{
1242 1292
 		$user_id = $user_id ?: self::userInfo('id');
1243 1293
 		if (empty($group_list))
1244
-		return !!Access::where(['user_id' => $user_id, 'group_id' => ['IN', $group]])->value('user_id');
1294
+		return !!Access::where(['user_id' => $user_id, 'group_id' => ['IN', $group_list]])->value('user_id');
1245 1295
 	}
1246 1296
 
1247 1297
     /**
@@ -1311,7 +1361,12 @@ class User extends Common
1311 1361
             if (!empty($userGroup)) Db::name('admin_access')->insertAll($userGroup);
1312 1362
 
1313 1363
             Db::commit();
1314
-
1364
+            $user= new ApiCommon();
1365
+            $user_id=$user->userInfo;
1366
+            foreach ($userIds AS $key => $value) {
1367
+                $userInfo=Db::name('admin_user')->where('id', $value)->find();
1368
+                SystemActionLog($user_id['id'], 'admin_user','employee', $value,  'update', $userInfo['realname'], '', '','编辑员工角色:'.$userInfo['realname']);
1369
+            }
1315 1370
             return true;
1316 1371
         } catch (\Exception $e) {
1317 1372
             Db::rollback();
@@ -1319,4 +1374,64 @@ class User extends Common
1319 1374
             return false;
1320 1375
         }
1321 1376
     }
1377
+    
1378
+    /**
1379
+     * 重设部门
1380
+     * @param array $ids 用户id
1381
+     * @param $param 部门id
1382
+     *
1383
+     * @author      alvin guogaobo
1384
+     * @version     1.0 版本号
1385
+     * @since       2021/4/24 0024 14:05
1386
+     *
1387
+     */
1388
+    public function setUserDept($ids = [],$param)
1389
+    {
1390
+        if (empty($ids)) {
1391
+            $this->error = '参数错误';
1392
+            return false;
1393
+        }
1394
+        foreach ($ids as $v){
1395
+            $data['id']=$v;
1396
+            $data['structure_id']=$param['structure_id'];
1397
+            $flag=foreachData('',$data);
1398
+        }
1399
+        if ($flag) {
1400
+            return $flag;
1401
+        } else {
1402
+            $this->error ='修改失败,请稍后重试';
1403
+            return false;
1404
+        }
1405
+    }
1406
+    
1407
+    /**
1408
+     * 员工分类总数
1409
+     * @author      alvin guogaobo
1410
+     * @version     1.0 版本号
1411
+     * @since       2021/4/24 0024 14:42
1412
+     */
1413
+    public function countNumOfUser(){
1414
+        //全部
1415
+//        $data['allUserCount']=$this->count();
1416
+//        //未激活
1417
+//        $data['inactiveCount']=$this->where('status',2)->count();
1418
+//        //激活
1419
+//        $data['activateCount']=$this->where('status',1)->count();
1420
+//        //停用
1421
+//        $data['disableCount']=$this->where('status',0)->count();
1422
+//        //新增
1423
+//        $data['addNewlyCount']=$this->where('create_time','gt',strtotime('-1 week'))->count();
1424
+        $time=strtotime('-1 week');
1425
+        $list=db('admin_user')->field([
1426
+            'count(id) as allUserCount,
1427
+            count(case status when 2 then id else null end) as inactiveCount,
1428
+            count(case status when 1 then id else null end) as activateCount,
1429
+            count(case status when 0 then id else null end) as disableCount,
1430
+            count(case when create_time >' .$time.' then id else null end) as addNewlyCount
1431
+            '
1432
+        ])->select();
1433
+        $data=[];
1434
+        $data['list']=$list;
1435
+        return $data;
1436
+    }
1322 1437
 }

+ 30
- 6
application/admin/model/UserField.php Zobrazit soubor

@@ -139,6 +139,8 @@ class UserField extends Model
139 139
      */
140 140
     public function getDataList($types, $user_id)
141 141
     {
142
+        $grantData = getFieldGrantData($user_id);
143
+        $userLevel = isSuperAdministrators($user_id);
142 144
         $fieldArr = (new Field)->getFieldList($types);
143 145
         $fieldList = [];
144 146
         $field_list = [];
@@ -166,14 +168,14 @@ class UserField extends Model
166 168
 
167 169
                 if (empty($v['is_hide'])) {
168 170
                     $valueList[] = $k;
169
-                    $value_list[$a]['field'] = $k; 
170
-                    $value_list[$a]['width'] = $v['width']; 
171
-                    $value_list[$a]['name'] = $field_list[$k]['name']; 
171
+                    $value_list[$a]['field'] = $k;
172
+                    $value_list[$a]['width'] = $v['width'];
173
+                    $value_list[$a]['name'] = $field_list[$k]['name'];
172 174
                     $a++;
173 175
                 } else {
174 176
                     $hideList[] = $k;
175 177
                     $hide_list[$b]['field'] = $k;
176
-                    $hide_list[$b]['width'] = $v['width'];  
178
+                    $hide_list[$b]['width'] = $v['width'];
177 179
                     $hide_list[$b]['name'] = $field_list[$k]['name'];
178 180
                     $b++;
179 181
                 }
@@ -192,9 +194,31 @@ class UserField extends Model
192 194
             $hide_list = [];
193 195
         }
194 196
 
197
+        # 处理显示列的字段授权
198
+        foreach ($value_list AS $key => $value) {
199
+            if (!$userLevel && !empty($grantData[$types])) {
200
+                foreach ($grantData[$types] AS $k => $v) {
201
+                    $status = getFieldGrantStatus($value['field'], $grantData[$types]);
202
+
203
+                    if (empty($status['read'])) unset($value_list[(int)$key]);
204
+                }
205
+            }
206
+        }
207
+
208
+        # 处理隐藏列的字段授权
209
+        foreach ($hide_list AS $key => $value) {
210
+            if (!$userLevel && !empty($grantData[$types])) {
211
+                foreach ($grantData[$types] AS $k => $v) {
212
+                    $status = getFieldGrantStatus($value['field'], $grantData[$types]);
213
+
214
+                    if (empty($status['read'])) unset($hide_list[(int)$key]);
215
+                }
216
+            }
217
+        }
218
+
195 219
         $data = [];
196
-        $data['value_list'] = $value_list ? : []; //展示列
197
-        $data['hide_list'] = $hide_list ? : []; //隐藏列
220
+        $data['value_list'] = array_values($value_list) ? : []; //展示列
221
+        $data['hide_list'] = array_values($hide_list) ? : []; //隐藏列
198 222
 
199 223
         if ($types == 'crm_visit') {
200 224
             foreach ($data['value_list'] AS $key => $value) {

+ 101
- 88
application/bi/controller/Customer.php Zobrazit soubor

@@ -84,8 +84,8 @@ class Customer extends ApiCommon
84 84
 
85 85
         if ($param['type']) {
86 86
             $timeArr = getTimeByType($param['type']);
87
-            $param['start_time'] = $timeArr[0];
88
-            $param['end_time'] = $timeArr[1];
87
+            $param['start_time'] = date('y-m-d 00:00:00',$timeArr[0]);
88
+            $param['end_time'] = date('y-m-d 23:59:59',$timeArr[1]);
89 89
         } else {
90 90
             if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
91 91
             if (!empty($param['end_time']))   $param['end_time']   =$param['end_time'] . ' 23:59:59';
@@ -482,7 +482,6 @@ class Customer extends ApiCommon
482 482
      */
483 483
     public function pool()
484 484
     {
485
-        $actionRecordModel = new \app\bi\model\ActionRecord();
486 485
         $userModel         = new \app\admin\model\User();
487 486
         $adminModel        = new \app\admin\model\Admin();
488 487
         $param             = $this->param;
@@ -497,29 +496,45 @@ class Customer extends ApiCommon
497 496
         if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
498 497
         if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
499 498
         $time = getTimeArray($param['start_time'], $param['end_time']);
500
-        $sql = $actionRecordModel
501
-            ->field([
502
-                "FROM_UNIXTIME(`create_time`, '{$time['time_format']}')" => 'type',
503
-                'SUM(CASE WHEN `content` = "将客户放入公海" THEN 1 ELSE 0 END)' => 'put_in',
504
-                'SUM(CASE WHEN `content` = "领取了客户" THEN 1 ELSE 0 END)' => 'receive'
505
-            ])
506
-            ->where([
507
-                'user_id' => ['IN', !empty($userIds) ? $userIds : '9999999999'],
508
-                'create_time' => ['BETWEEN', $time['between']],
509
-                'content' => ['IN', ['将客户放入公海', '领取了客户']]
510
-            ])
511
-            ->group('type')
512
-            ->fetchSql()
513
-            ->select();
499
+//        $sql = db('crm_customer_pool_record')
500
+//                ->field([
501
+//                    "FROM_UNIXTIME(`create_time`, '{$time['time_format']}')" => 'time',
502
+//                    'SUM(CASE WHEN `type` = 2 THEN 1 ELSE 0 END)' => 'put_in',
503
+//                    'SUM(CASE WHEN `type` = 1 THEN 1 ELSE 0 END)' => 'receive'
504
+//                ])
505
+//                ->where([
506
+//                    'user_id' => ['IN', !empty($userIds) ? $userIds : 0],
507
+//                    'create_time' => ['BETWEEN', $time['between']],
508
+//                ])
509
+//                ->group('time')
510
+//                ->fetchSql()
511
+//                ->select();
512
+        $prefix = config('database.prefix');
513
+        $ids = !empty($userIds) ? implode(',', $userIds) : 0;
514
+        $sql = "SELECT 
515
+	                FROM_UNIXTIME( `create_time`, '%Y-%m' ) AS `time`, 
516
+	                SUM( CASE WHEN `type` = 2 THEN 1 ELSE 0 END ) AS `put_in`, 
517
+	                SUM( CASE WHEN `type` = 1 THEN 1 ELSE 0 END ) AS `receive` 
518
+                FROM 
519
+                    (SELECT * FROM `".$prefix."crm_customer_pool_record` GROUP BY `customer_id`, `type`) AS `record` 
520
+                WHERE 
521
+	                `user_id` IN ( ".$ids." ) AND `create_time` BETWEEN ".$time['between'][0]." AND ".$time['between'][1]." 
522
+                GROUP BY `time`";
514 523
         $res = queryCache($sql);
515
-        $res = array_column($res, null, 'type');
516
-
517
-        foreach ($time['list'] as &$val) {
518
-            $val['put_in'] = (int)$res[$val['type']]['put_in'];
519
-            $val['receive'] = (int)$res[$val['type']]['receive'];
524
+        $res = array_column($res, null, 'time');
525
+
526
+        $result = [];
527
+        foreach ($time['list'] AS $key => $value) {
528
+            $result[] = [
529
+                'type'       => $value['type'],
530
+                'start_time' => $value['start_time'],
531
+                'end_time'   => $value['end_time'],
532
+                'put_in'     => !empty($res[$value['type']]['put_in'])  ? (int)$res[$value['type']]['put_in']  : 0,
533
+                'receive'    => !empty($res[$value['type']]['receive']) ? (int)$res[$value['type']]['receive'] : 0
534
+            ];
520 535
         }
521 536
 
522
-        return resultArray(['data' => $time['list']]);
537
+        return resultArray(['data' => $result]);
523 538
     }
524 539
 
525 540
     /**
@@ -554,81 +569,79 @@ class Customer extends ApiCommon
554 569
         $whereArr = $adminModel->getWhere($param, '', $perUserIds); //统计条件
555 570
         $userIds = $whereArr['userIds'];
556 571
         $between_time = $whereArr['between_time'];
557
-        $sql = CustomerModel::field([
558
-            'COUNT(*)' => 'customer_num',
559
-            'owner_user_id'
560
-        ])
561
-            ->where([
562
-                'create_time' => ['BETWEEN', $between_time],
563
-                'owner_user_id' => ['IN', !empty($userIds) ? $userIds : '9999999999']
564
-            ])
565
-            ->group('owner_user_id')
566
-            ->fetchSql()
567
-            ->select();
568
-        $customer_num_list = queryCache($sql);
569
-        $customer_num_list = array_column($customer_num_list, null, 'owner_user_id');
570 572
 
571
-        $configModel = new \app\crm\model\ConfigData();
572
-        $configInfo = $configModel->getData();
573
-        $paramPool = [];
574
-        $paramPool['config'] = $configInfo['config'] ? : 0;
575
-        $paramPool['follow_day'] = $configInfo['follow_day'] ? : 0;
576
-        $paramPool['deal_day'] = $configInfo['deal_day'] ? : 0;
577
-        $paramPool['remind_config'] = $configInfo['remind_config'] ? : 0;
578
-        $customer_list='';
579
-        $action_record_list='';
580
-        if($paramPool['config']==1){
581
-            $sql = $CustomerModel
582
-                ->alias('customer')
583
-                ->field([
584
-                    'customer.create_user_id as user_id' ,
585
-                    'COUNT(customer.customer_id) as put_in'
586
-                ])
587
-                ->group('user_id')
588
-                ->where($CustomerModel->getWhereByPool())
589
-                ->where([
590
-                    'create_time' => ['BETWEEN', $between_time],
591
-                    'create_user_id' => ['IN', $userIds],
592
-                ])
593
-                ->fetchSql()
594
-                ->select();
595
-            $customer_list = queryCache($sql);
596
-            $customer_list = array_column($customer_list, null, 'user_id');
573
+//        $sql = db('crm_customer_pool_record')
574
+//            ->field([
575
+//                'user_id',
576
+//                'SUM(CASE WHEN `type` = 2 THEN 1 ELSE 0 END)' => 'put_in',
577
+//                'SUM(CASE WHEN `type` = 1 THEN 1 ELSE 0 END)' => 'receive'
578
+//            ])
579
+//            ->group('user_id')
580
+//            ->where([
581
+//                'create_time' => ['BETWEEN', $between_time],
582
+//                'user_id' => ['IN', !empty($userIds) ? $userIds : 0]
583
+//            ])
584
+//            ->fetchSql()
585
+//            ->select();
586
+        $prefix = config('database.prefix');
587
+        $ids = !empty($userIds) ? implode(',', $userIds) : 0;
588
+        $sql = "SELECT 
589
+	                `user_id`, 
590
+	                SUM( CASE WHEN `type` = 2 THEN 1 ELSE 0 END ) AS `put_in`, 
591
+	                SUM( CASE WHEN `type` = 1 THEN 1 ELSE 0 END ) AS `receive` 
592
+                FROM 
593
+	                (SELECT * FROM `".$prefix."crm_customer_pool_record` GROUP BY `customer_id`, `type`) AS `record` 
594
+                WHERE 
595
+	                `create_time` BETWEEN ".$between_time[0]." AND ".$between_time[1]." AND `user_id` IN ( ".$ids." ) 
596
+                GROUP BY `user_id`";
597
+        $poolRecord = queryCache($sql);
598
+        $recordData = [];
599
+        foreach ($poolRecord AS $key => $value) {
600
+            $recordData[$value['user_id']] = [
601
+                'put_in' => $value['put_in'],
602
+                'receive' => $value['receive']
603
+            ];
597 604
         }
598
-        $sql = $actionRecordModel
599
-            ->field([
600
-                'user_id',
601
-                'SUM(CASE WHEN `content` = "将客户放入公海" THEN 1 ELSE 0 END)' => 'put_in',
602
-                'SUM(CASE WHEN `content` = "领取了客户" THEN 1 ELSE 0 END)' => 'receive'
603
-            ])
604
-            ->group('user_id')
605
-            ->where([
606
-                'create_time' => ['BETWEEN', $between_time],
607
-                'user_id' => ['IN', $userIds],
608
-                'content' => ['IN', ['将客户放入公海', '领取了客户']],
609
-                'types' => 'crm_customer',
610
-            ])
611
-            ->fetchSql()
612
-            ->select();
613
-        $action_record_list = queryCache($sql);
614
-        $action_record_list = array_column($action_record_list, null, 'user_id');
615
-    
605
+//        $action_record_list = array_column($action_record_list, null, 'user_id');
606
+
607
+        # 部门列表
608
+        $structureData = [];
609
+        $structureList = db('admin_structure')->select();
610
+        foreach ($structureList AS $key => $value) {
611
+            $structureData[$value['id']] = $value['name'];
612
+        }
613
+
614
+        # 员工列表
615
+        $userList = db('admin_user')->field(['id', 'realname', 'structure_id'])->whereIn('id', $userIds)->select();
616
+
616 617
         $res = [];
617 618
         $receiveCount = 0; # 领取公海客户总数
618 619
         $putInCount = 0; # 进入公海客户总数
619
-        foreach ($userIds as $val) {
620
-            $item['put'] = !empty($customer_list[$val]['put_in'])?(int)$customer_list[$val]['put_in']:0;
621
-            $item['put_in'] = !empty($customer_list[$val]['put_in']) ?  $item['put'] : (int)$action_record_list[$val]['put_in'] + $item['put'];
622
-            $item['receive'] = !empty($action_record_list[$val]['receive']) ? (int)$action_record_list[$val]['receive'] : 0;
623
-            $item['customer_num'] = !empty($customer_num_list[$val]['customer_num']) ? (int)$customer_num_list[$val]['customer_num'] : 0;
624
-            $user_info = $userModel->getUserById($val);
625
-            $item['realname'] = $user_info['realname'];
626
-            $item['username'] = $user_info['structure_name'];
620
+        foreach ($userList as $val) {
621
+            $item['put'] = !empty($recordData[$val['id']]['put_in']) ? (int)$recordData[$val['id']]['put_in'] : 0;
622
+            $item['put_in'] = !empty($recordData[$val['id']]['put_in']) ? (int)$recordData[$val['id']]['put_in'] : 0;
623
+            $item['receive'] = !empty($recordData[$val['id']]['receive']) ? (int)$recordData[$val['id']]['receive'] : 0;
624
+            $item['customer_num'] = 0;
625
+            $item['realname'] = $val['realname'];
626
+            $item['username'] = !empty($structureData[$val['structure_id']]) ? $structureData[$val['structure_id']] : '';
627 627
             $res[] = $item;
628 628
 
629 629
             $receiveCount += $item['receive'];
630 630
             $putInCount += $item['put_in'];
631 631
         }
632
+//        foreach ($userIds as $val) {
633
+//            $item['put'] = !empty($customer_list[$val]['put_in'])?(int)$customer_list[$val]['put_in']:0;
634
+//            $item['put_in'] = !empty($customer_list[$val]['put_in']) ?  $item['put'] : (int)$action_record_list[$val]['put_in'] + $item['put'];
635
+//            $item['receive'] = !empty($action_record_list[$val]['receive']) ? (int)$action_record_list[$val]['receive'] : 0;
636
+//            $item['customer_num'] = !empty($customer_num_list[$val]['customer_num']) ? (int)$customer_num_list[$val]['customer_num'] : 0;
637
+//            $user_info = $userModel->getUserById($val);
638
+//            $item['realname'] = $user_info['realname'];
639
+//            $item['username'] = $user_info['structure_name'];
640
+//            $res[] = $item;
641
+//
642
+//            $receiveCount += $item['receive'];
643
+//            $putInCount += $item['put_in'];
644
+//        }
632 645
 
633 646
         $result = ['list' => $res, 'total' => ['realname' => '总计', 'receive' => $receiveCount, 'put_in' => $putInCount]];
634 647
 

+ 2
- 2
application/bi/controller/Examine.php Zobrazit soubor

@@ -89,7 +89,7 @@ class Examine extends ApiCommon
89 89
 
90 90
         $where = [];
91 91
         $where['create_user_id'] = $user_id;
92
-        $where['check_status'] = 2;
92
+        $where['check_status'] = ['neq',4];
93 93
         $where['create_time'] = $create_time;
94 94
         $where['category_id'] = $category_id;
95 95
         $sumData = 0;
@@ -122,7 +122,7 @@ class Examine extends ApiCommon
122 122
         unset($where['create_time']);
123 123
         unset($where['create_user_id']);
124 124
         unset($where['create_user_id']);
125
-//        $where['check_status'] = 'all';
125
+        $where['check_status'] = 'all';
126 126
         $where['page'] = $param['page'];
127 127
         $where['limit'] = $param['limit'];
128 128
         $where['user_id'] = $user_id;

+ 18
- 45
application/bi/controller/Product.php Zobrazit soubor

@@ -25,7 +25,7 @@ class Product extends ApiCommon
25 25
     {
26 26
         $action = [
27 27
             'permission' => [''],
28
-            'allow' => ['statistics', 'productcategory', 'excelexport']
28
+            'allow' => ['statistics', 'productcategory', 'excelexport','listproduct']
29 29
         ];
30 30
         Hook::listen('check_auth', $action);
31 31
         $request = Request::instance();
@@ -65,7 +65,7 @@ class Product extends ApiCommon
65 65
         }
66 66
         return resultArray(['data' => $list]);
67 67
     }
68
-
68
+    
69 69
     /**
70 70
      * 产品分类销量分析
71 71
      *
@@ -99,50 +99,23 @@ class Product extends ApiCommon
99 99
     {
100 100
         $param = $this->param;
101 101
         $list = $this->statistics($param);
102
-        $data = [];
103
-        $subtotalCount = [];
104
-        $sumCount = [];
105
-        $item = [];
106
-        $res = [];
107
-        foreach ($list as &$val) {
108
-            $res[] = $val['product_id'];
109
-            $data[$val['product_id']][] = $val;
110
-        }
111
-        $res = array_unique($res);
112
-        foreach ($res as $e) {
113
-            $unm = 0;
114
-            $subtotal = 0;
115
-            foreach ($list as $v) {
116
-                if ($e == $v['product_id']) {
117
-                    $unm += $v['num'];
118
-                    $subtotal += $v['subtotal'];
119
-                    $sumCount[$e] = $unm;
120
-                    $subtotalCount[$e] = (float)$subtotal;
121
-                }
122
-            }
123
-            $item[$e][] = [
124
-                'type' => '',
125
-                'category_id_info' => '',
126
-                'product_name' => '',
127
-                'contract_num' => '',
128
-                'realname' => '',
129
-                'name' => '',
130
-                'price' => '合计',
131
-                'num' => $sumCount[$e],
132
-                'subtotal' => $subtotalCount[$e],
133
-            ];
134
-        }
135
-        $items = [];
136
-        foreach ($data as $key => $value) {
137
-            $items[] = array_merge($data[$key], $item[$key]);
138
-        }
139
-        foreach ($items as $u) {
140
-            foreach ($u as $d) {
141
-                $field[] = $d;
142
-            }
143
-        }
144 102
         $excelLogic = new ExcelLogic();
145
-        $data = $excelLogic->productExcel($param, $field);
103
+        $data = $excelLogic->productExcel($param, $list['list']);
146 104
         return $data;
147 105
     }
106
+    /**
107
+     * 产品销量列表
108
+     * @author      alvin guogaobo
109
+     * @version     1.0 版本号
110
+     * @since       2021/4/20 0020 16:16
111
+     */
112
+    public function listProduct(){
113
+        $param = $this->param;
114
+        $productModel = new \app\crm\model\Product();
115
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
116
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
117
+        $list = $productModel->listProduct($param);
118
+        return resultArray(['data' => $list]);
119
+    }
120
+    
148 121
 }

+ 1
- 1
application/bi/controller/Ranking.php Zobrazit soubor

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

+ 3
- 6
application/bi/logic/ExcelLogic.php Zobrazit soubor

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

+ 1
- 0
application/command.php Zobrazit soubor

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

+ 267
- 117
application/common.php Zobrazit soubor

@@ -15,6 +15,7 @@ use think\Lang;
15 15
 use think\helper\Time;
16 16
 use com\IpLocation;
17 17
 use app\crm\traits\DataTime;
18
+
18 19
 /**
19 20
  * 对象 转 数组
20 21
  *
@@ -56,7 +57,7 @@ function array_to_object($arr)
56 57
 
57 58
 /**
58 59
  * 返回对象
59
- * @param $array 响应数据
60
+ * @param array $array 响应数据
60 61
  */
61 62
 function resultArray($array)
62 63
 {
@@ -135,7 +136,7 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
135 136
     //查询自定义字段模块多选字段类型
136 137
     $check_field_arr = [];
137 138
     //特殊字段
138
-
139
+    
139 140
     //过滤系统参数
140 141
     $unset_arr = ['page', 'limit', 'order_type', 'order_field'];
141 142
     if (!is_array($array)) {
@@ -163,7 +164,7 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
163 164
             }
164 165
             if ($v['form_type'] == 'date') {
165 166
                 if (!empty($v['start'])) $v['start'] = date('Y-m-d', $v['start']);
166
-                if (!empty($v['end']))   $v['end']   = date('Y-m-d', $v['end']);
167
+                if (!empty($v['end'])) $v['end'] = date('Y-m-d', $v['end']);
167 168
             }
168 169
             # 创建人、负责人、回访人(非自定义字段)
169 170
 //            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 = '')
173 174
             if (($v['form_type'] == 'user' && !in_array($k, ['create_user_id', 'owner_user_id'])) || $v['form_type'] == 'structure') {
174 175
                 if ($v['condition'] == 'is') $v['condition'] = 'contains';
175 176
                 if ($v['condition'] == 'isNot') {
176
-                    return "(".$c.$k." not like ',%".$v['value'][0]."%,' OR ".$c.$k." is null)";
177
+                    return "(" . $c . $k . " not like ',%" . $v['value'][0] . "%,' OR " . $c . $k . " is null)";
177 178
                 }
178 179
             }
179 180
             # 处理多选字段的精确搜索
@@ -181,10 +182,10 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
181 182
                 if ($v['condition'] == 'is' && count($v['value']) == 1) $v['value'][0] = ',' . $v['value'][0] . ',';
182 183
                 if ($v['condition'] == 'is' && count($v['value']) > 1) {
183 184
                     $checkboxLike = '';
184
-                    foreach ($v['value'] AS $kk => $vv) {
185
-                        $checkboxLike .= $c.$k." like "."',%".$vv."%,' AND ";
185
+                    foreach ($v['value'] as $kk => $vv) {
186
+                        $checkboxLike .= $c . $k . " like " . "',%" . $vv . "%,' AND ";
186 187
                     }
187
-                    return "(".$checkboxLike."LENGTH(".$c.$k.") = LENGTH('".arrayToString($v['value'])."'))";
188
+                    return "(" . $checkboxLike . "LENGTH(" . $c . $k . ") = LENGTH('" . arrayToString($v['value']) . "'))";
188 189
                 }
189 190
             }
190 191
             if ($types == 'contract' && !empty($v['value'])) {
@@ -195,9 +196,9 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
195 196
                         break;
196 197
                     case 'contacts_id' :
197 198
                         $contactsIds = [];
198
-                        foreach ($v['value'] AS $kk => $vv) {
199
+                        foreach ($v['value'] as $kk => $vv) {
199 200
                             $contactsIdArray = db('crm_contacts')->whereLike('name', '%' . $vv . '%')->column('contacts_id');
200
-                            foreach ($contactsIdArray AS $kkk => $vvv) {
201
+                            foreach ($contactsIdArray as $kkk => $vvv) {
201 202
                                 $contactsIds[] = $vvv;
202 203
                             }
203 204
                         }
@@ -211,16 +212,16 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
211 212
             }
212 213
             if ($types == 'receivables' && $k == 'plan_id' && !empty($v['value'])) {
213 214
                 $planIds = [];
214
-                foreach ($v['value'] AS $kk => $vv) {
215
+                foreach ($v['value'] as $kk => $vv) {
215 216
                     $planIdArray = db('crm_receivables_plan')->whereLike('num', '%' . $vv . '%')->column('plan_id');
216
-                    foreach ($planIdArray AS $kkk => $vvv) {
217
+                    foreach ($planIdArray as $kkk => $vvv) {
217 218
                         $planIds[] = $vvv;
218 219
                     }
219 220
                 }
220 221
                 $v['value'] = array_unique($planIds);
221 222
             }
222 223
             if ($types == 'invoice' && $v['type'] == 'invoice_status' && !empty($v['value'])) {
223
-                foreach ($v['value'] AS $kk => $vv) {
224
+                foreach ($v['value'] as $kk => $vv) {
224 225
                     if ($vv == '已开票') $v['value'][$kk] = 1;
225 226
                     if ($vv == '未开票') $v['value'][$kk] = 0;
226 227
                 }
@@ -279,7 +280,11 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
279 280
                     if (in_array($k, $check_field_arr)) {
280 281
                         $where[$c . $k] = field($v['value'], 'contains');
281 282
                     } else {
282
-                        $where[$c . $k] = field($v['value'], $v['condition'], $k);
283
+                        if ($v['condition'] == 'isNot' || $v['condition'] == 'notContains') {
284
+                            $where[$c . $k] = [field($v['value'], $v['condition'], $k), ['null'], 'or'];
285
+                        } else {
286
+                            $where[$c . $k] = field($v['value'], $v['condition'], $k);
287
+                        }
283 288
                     }
284 289
                 } elseif (in_array($v['condition'], ['isNull', 'isNotNull', 'in'])) {
285 290
                     $where[$c . $k] = field($v['value'], $v['condition']);
@@ -293,13 +298,13 @@ function where_arr($array = [], $m = '', $c = '', $a = '')
293 298
             }
294 299
         }
295 300
     }
296
-
301
+    
297 302
     # 商机阶段为赢单、输单、无效的值保存在is_end中,将status_id改为is_end;
298
-    if (!empty($where['business.status_id']) && in_array($where['business.status_id'][1], [1,2,3])) {
303
+    if (!empty($where['business.status_id']) && in_array($where['business.status_id'][1], [1, 2, 3])) {
299 304
         $where['business.is_end'] = $where['business.status_id'];
300 305
         unset($where['business.status_id']);
301 306
     }
302
-
307
+    
303 308
     return $where ?: [];
304 309
 }
305 310
 
@@ -322,22 +327,22 @@ function field($search, $condition = '', $k = '')
322 327
             break;
323 328
         case "contains" :
324 329
             $containsWhere = [];
325
-            foreach ((array)$search AS $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
330
+            foreach ((array)$search as $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
326 331
             $where = ['like', $containsWhere, 'OR'];
327 332
             break;
328 333
         case "notContains" :
329 334
             $containsWhere = [];
330
-            foreach ((array)$search AS $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
335
+            foreach ((array)$search as $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
331 336
             $where = ['notlike', $containsWhere, 'AND'];
332 337
             break;
333 338
         case "startWith" :
334 339
             $startWithWhere = [];
335
-            foreach ((array)$search AS $key1 => $value1) $startWithWhere[] = $value1 . '%';
340
+            foreach ((array)$search as $key1 => $value1) $startWithWhere[] = $value1 . '%';
336 341
             $where = ['like', $startWithWhere, 'OR'];
337 342
             break;
338 343
         case "endWith" :
339 344
             $endWithWhere = [];
340
-            foreach ((array)$search AS $key1 => $value1) $endWithWhere[] = '%' . $value1;
345
+            foreach ((array)$search as $key1 => $value1) $endWithWhere[] = '%' . $value1;
341 346
             $where = ['like', $endWithWhere, 'OR'];
342 347
             break;
343 348
         case "isNull" :
@@ -348,42 +353,42 @@ function field($search, $condition = '', $k = '')
348 353
             break;
349 354
         case "eq" :
350 355
             $where = function ($query) use ($search, $k) {
351
-                foreach ((array)$search AS $key1 => $value1) {
356
+                foreach ((array)$search as $key1 => $value1) {
352 357
                     $query->whereOr($k, $value1);
353 358
                 }
354 359
             };
355 360
             break;
356 361
         case "neq" :
357 362
             $where = function ($query) use ($search, $k) {
358
-                foreach ((array)$search AS $key1 => $value1) {
363
+                foreach ((array)$search as $key1 => $value1) {
359 364
                     $query->whereOr($k, '<>', $value1);
360 365
                 }
361 366
             };
362 367
             break;
363 368
         case "gt" :
364 369
             $where = function ($query) use ($search, $k) {
365
-                foreach ((array)$search AS $key1 => $value1) {
370
+                foreach ((array)$search as $key1 => $value1) {
366 371
                     $query->whereOr($k, '>', $value1);
367 372
                 }
368 373
             };
369 374
             break;
370 375
         case "egt" :
371 376
             $where = function ($query) use ($search, $k) {
372
-                foreach ((array)$search AS $key1 => $value1) {
377
+                foreach ((array)$search as $key1 => $value1) {
373 378
                     $query->whereOr($k, '>=', $value1);
374 379
                 }
375 380
             };
376 381
             break;
377 382
         case "lt" :
378 383
             $where = function ($query) use ($search, $k) {
379
-                foreach ((array)$search AS $key1 => $value1) {
384
+                foreach ((array)$search as $key1 => $value1) {
380 385
                     $query->whereOr($k, '<', $value1);
381 386
                 }
382 387
             };
383 388
             break;
384 389
         case "elt" :
385 390
             $where = function ($query) use ($search, $k) {
386
-                foreach ((array)$search AS $key1 => $value1) {
391
+                foreach ((array)$search as $key1 => $value1) {
387 392
                     $query->whereOr($k, '<=', $value1);
388 393
                 }
389 394
             };
@@ -408,12 +413,12 @@ function field($search, $condition = '', $k = '')
408 413
 function field_arr($value, $condition = '')
409 414
 {
410 415
     if (is_array($value)) {
411
-
416
+    
412 417
     } else {
413 418
         $condition = $condition ?: 'eq';
414 419
         $where_arr = ['value' => $value, 'condition' => $condition];
415 420
     }
416
-
421
+    
417 422
     return $where_arr;
418 423
 }
419 424
 
@@ -432,18 +437,18 @@ function actionLog($id, $join_user_ids = '', $structure_ids = '', $content = '')
432 437
     }
433 438
     $header = Request::instance()->header();
434 439
     $authKey = $header['authkey'];
435
-    $cache = cache('Auth_'.$authKey);
440
+    $cache = cache('Auth_' . $authKey);
436 441
     if (!$cache) {
437 442
         return false;
438 443
     }
439 444
     $userInfo = $cache['userInfo'];
440 445
     $category = $userInfo['id'] == 1 ? '管理员' : '员工';
441
-
446
+    
442 447
     $request = request();
443 448
     $m = strtolower($request->module());
444 449
     $c = strtolower($request->controller());
445 450
     $a = strtolower($request->action());
446
-
451
+    
447 452
     $res_action = true;
448 453
     foreach ($idArr as $v) {
449 454
         $data = [];
@@ -454,27 +459,27 @@ function actionLog($id, $join_user_ids = '', $structure_ids = '', $content = '')
454 459
         $data['action_id'] = $v;
455 460
         $data['create_time'] = time();
456 461
         $data['client_ip'] = request()->ip();
457
-        $data['content'] = $content ? : lang('ACTIONLOG', [$category, $userInfo['realname'], date('Y-m-d H:i:s'), lang($action_name), $v, lang($controller_name)]);
458
-        $data['join_user_ids'] = $join_user_ids ? : ''; //抄送人
459
-        $data['structure_ids'] = $structure_ids ? : ''; //抄送部门
462
+        $data['content'] = $content ?: lang('ACTIONLOG', [$category, $userInfo['realname'], date('Y-m-d H:i:s'), lang($action_name), $v, lang($controller_name)]);
463
+        $data['join_user_ids'] = $join_user_ids ?: ''; //抄送人
464
+        $data['structure_ids'] = $structure_ids ?: ''; //抄送部门
460 465
         if ($action_name == 'delete' || $action_name == 'commentdel') {
461 466
             $data['action_delete'] = 1;
462 467
         }
463 468
         if (!db('admin_action_log')->insert($data)) {
464 469
             $res_action = false;
465 470
         }
466
-
471
+        
467 472
         # 数据操作日志
468 473
         db('admin_operation_log')->insert([
469
-            'user_id'     => $userInfo['id'],
470
-            'client_ip'   => request()->ip(),
471
-            'module'      => $m . '_' . $c,
472
-            'action_id'   => $v,
473
-            'content'     => $content,
474
+            'user_id' => $userInfo['id'],
475
+            'client_ip' => request()->ip(),
476
+            'module' => $m . '_' . $c,
477
+            'action_id' => $v,
478
+            'content' => $content,
474 479
             'create_time' => time()
475 480
         ]);
476 481
     }
477
-
482
+    
478 483
     if ($res_action) {
479 484
         return true;
480 485
     } else {
@@ -598,14 +603,14 @@ function getSubUserId($self = true, $type = 0, $user_id = '')
598 603
         $userInfo = $cache['userInfo'];
599 604
         $user_id = $userInfo['id'];
600 605
         $adminTypes = adminGroupTypes($user_id);
601
-
606
+        
602 607
         if (in_array(1, $adminTypes)) {
603 608
             $type = 1;
604 609
         }
605 610
     }
606 611
     $belowIds = [];
607 612
     if (empty($type)) {
608
-
613
+        
609 614
         if ($user_id) {
610 615
             $belowIds = getSubUser($user_id);
611 616
         }
@@ -629,7 +634,7 @@ function getSubUser($userId, $queried = [], $allUserList = [])
629 634
     if (empty($allUserList)) {
630 635
         $allUserList = db('admin_user')->field('id,parent_id')->select();
631 636
     }
632
-    foreach ($allUserList as $k=>$v) {
637
+    foreach ($allUserList as $k => $v) {
633 638
         if ($v['parent_id'] == $userId) {
634 639
             $sub_user[] = $v['id'];
635 640
         }
@@ -725,7 +730,7 @@ function sendMessage($user_id, $content, $action_id, $sysMessage = 0)
725 730
     $m = strtolower($request->module());
726 731
     $c = strtolower($request->controller());
727 732
     $a = strtolower($request->action());
728
-
733
+    
729 734
     $userInfo = [];
730 735
     if ($sysMessage == 0) {
731 736
         $header = $request->header();
@@ -739,7 +744,7 @@ function sendMessage($user_id, $content, $action_id, $sysMessage = 0)
739 744
     foreach ($user_ids as $v) {
740 745
         $data = [];
741 746
         $data['content'] = $content;
742
-        $data['from_user_id'] = $userInfo['id'] ? : 0;
747
+        $data['from_user_id'] = $userInfo['id'] ?: 0;
743 748
         $data['to_user_id'] = $v;
744 749
         $data['read_time'] = 0;
745 750
         $data['send_time'] = time();
@@ -777,6 +782,11 @@ function format_bytes($size, $delimiter = '')
777 782
  */
778 783
 function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData = [], $content = '')
779 784
 {
785
+    # 转格式
786
+    if (!empty($oldData['next_time']) && $oldData['next_time'] != strtotime($oldData['next_time'])) {
787
+        $oldData['next_time'] = strtotime($oldData['next_time']);
788
+    }
789
+
780 790
     if (is_array($oldData) && is_array($newData) && $user_id) {
781 791
         $differentData = array_diff_assoc($newData, $oldData);
782 792
         $fieldModel = new FieldModel();
@@ -787,19 +797,18 @@ function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData =
787 797
         foreach ($field_arr as $k => $v) {
788 798
             $newFieldArr[$v['field']] = $v;
789 799
         }
790
-        $unField = ['update_time','create_time']; //定义过滤字段
800
+        $unField = ['update_time', 'create_time']; //定义过滤字段
791 801
         $message = [];
792 802
         $un_form_type = ['file', 'form'];
793
-        
794 803
         foreach ($differentData as $k => $v) {
795 804
             if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
796 805
                 $field_name = '';
797 806
                 $field_name = $newFieldArr[$k]['name'];
798
-                $new_value = $v;
807
+                $new_value = $v ?: '空';
799 808
                 $old_value = $oldData[$k] ?: '空';
800 809
                 if ($newFieldArr[$k]['form_type'] == 'datetime') {
801
-                    $new_value = $v ? date('Y-m-d', $v) : '';
802
-                    $old_value = date('Y-m-d', $oldData[$k]);
810
+                    $new_value = $v ? date('Y-m-d', $v) : '';
811
+                    $old_value = !empty($oldData[$k]) ? date('Y-m-d', $oldData[$k]) : '空';
803 812
                     if (empty($v) && empty($oldData[$k])) continue;
804 813
                 } elseif ($newFieldArr[$k]['form_type'] == 'user') {
805 814
                     $new_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($v))) : '';
@@ -829,13 +838,15 @@ function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData =
829 838
                 } elseif ($newFieldArr[$k]['form_type'] == 'visit') {
830 839
                     $new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
831 840
                     $old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
832
-                } elseif ($newFieldArr[$k]['form_type'] == 'single_user'){
841
+                } elseif ($newFieldArr[$k]['form_type'] == 'single_user') {
833 842
                     $new_value = $v ? db('admin_user')->where(['id' => $v])->value('realname') : '';
834 843
                     $old_value = $v ? db('admin_user')->where(['id' => $oldData['owner_user_id']])->value('realname') : '';
835
-                }elseif($newFieldArr[$k]['form_type'] == 'floatnumber'){
836
-                    $new_value = $v ? number_format($v,2) : '';
844
+                } elseif ($newFieldArr[$k]['form_type'] == 'floatnumber') {
845
+                    $new_value = $v ? number_format($v, 2) : '';
846
+                }
847
+                if ($old_value != $new_value) {
848
+                    $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
837 849
                 }
838
-                $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
839 850
             }
840 851
         }
841 852
         if ($message) {
@@ -846,15 +857,6 @@ function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData =
846 857
             $data['action_id'] = $action_id;
847 858
             $data['content'] = implode('.|.', $message);
848 859
             db('admin_action_record')->insert($data);
849
-            # 数据操作日志
850
-            db('admin_operation_log')->insert([
851
-                'user_id'     => $user_id,
852
-                'client_ip'   => request()->ip(),
853
-                'module'      => $types,
854
-                'action_id'   => $action_id,
855
-                'content'     => implode('.|.', $message),
856
-                'create_time' => time()
857
-            ]);
858 860
         }
859 861
     } elseif ($content) {
860 862
         $data = [];
@@ -864,15 +866,6 @@ function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData =
864 866
         $data['action_id'] = $action_id;
865 867
         $data['content'] = $content;
866 868
         db('admin_action_record')->insert($data);
867
-        # 数据操作日志
868
-        db('admin_operation_log')->insert([
869
-            'user_id'     => $user_id,
870
-            'client_ip'   => request()->ip(),
871
-            'module'      => $types,
872
-            'action_id'   => $action_id,
873
-            'content'     => $content,
874
-            'create_time' => time()
875
-        ]);
876 869
     }
877 870
 }
878 871
 
@@ -923,7 +916,7 @@ function checkVerify($saftCode = '5kcrm@')
923 916
     $parmList['sessionId'] = $header['sessionId'];
924 917
     $authkey = $header['authKey'];
925 918
     $clientSign = $parmList['client_sign'];
926
-
919
+    
927 920
     if ($clientSign) {
928 921
         unset($parmList['client_sign']);
929 922
         if (count($parmList) > 0) {
@@ -1348,7 +1341,7 @@ function getTimeByType($type = 'today', $is_last = false)
1348 1341
                 $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
1349 1342
                 $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
1350 1343
             }
1351
-
1344
+            
1352 1345
             //上季度
1353 1346
             $month = date('m');
1354 1347
             if ($month == 1 || $month == 2 || $month == 3) {
@@ -1609,12 +1602,12 @@ function nextCheckData($user_id, $flow_id, $types, $types_id, $order_id, $check_
1609 1602
     $new_order_id = $order_id;
1610 1603
     $max_order_id = db('admin_examine_step')->where(['flow_id' => $flow_id])->max('order_id'); //审批流最大排序ID
1611 1604
     $examineStepModel = new \app\admin\model\ExamineStep();
1612
-
1605
+    
1613 1606
     $stepInfo = $examineStepModel->getStepByOrder($flow_id, $new_order_id); //审批步骤
1614 1607
     $next_user_ids = [];
1615 1608
     $is_end = 0; //审批结束
1616 1609
     //固定流程(status 1负责人主管,2指定用户(任意一人),3指定用户(多人会签),4上一级审批人主管)
1617
-
1610
+    
1618 1611
     //当前步骤审批人user_id
1619 1612
     $step_user_ids = $examineStepModel->getUserByStep($stepInfo['step_id'], $user_id);
1620 1613
     if ($step_user_ids) {
@@ -1771,7 +1764,7 @@ function getWhereUserByParam(&$where, $field = 'owner_user_id', $m = '', $c = ''
1771 1764
 {
1772 1765
     $param = request()->param();
1773 1766
     $userModel = new UserModel();
1774
-
1767
+    
1775 1768
     $map_user_ids = [];
1776 1769
     if ($param['user_id']) {
1777 1770
         $map_user_ids = array($param['user_id']);
@@ -1782,7 +1775,7 @@ function getWhereUserByParam(&$where, $field = 'owner_user_id', $m = '', $c = ''
1782 1775
         $where[$field] = array('in', $map_user_ids);
1783 1776
         return;
1784 1777
     }
1785
-
1778
+    
1786 1779
     $perUserIds = $userModel->getUserByPer($m, $c, $a); //权限范围内userIds
1787 1780
     $userIds = array_intersect($map_user_ids, $perUserIds); //数组交集
1788 1781
     $where[$field] = array('in', $userIds);
@@ -1877,10 +1870,10 @@ function download($file, $name = '', $del = false)
1877 1870
             'error' => '文件路径错误',
1878 1871
         ]);
1879 1872
     }
1880
-
1873
+    
1881 1874
     $fp = fopen($file, 'r');
1882 1875
     $size = filesize($file);
1883
-
1876
+    
1884 1877
     //下载文件需要的头
1885 1878
     header("Content-type: application/octet-stream");
1886 1879
     header("Accept-Ranges: bytes");
@@ -1889,12 +1882,12 @@ function download($file, $name = '', $del = false)
1889 1882
     $file_name = $name != '' ? $name : pathinfo($file, PATHINFO_BASENAME);
1890 1883
     // urlencode 处理中文乱码
1891 1884
     header("Content-Disposition:attachment; filename=" . urlencode($file_name));
1892
-
1885
+    
1893 1886
     // 导出数据时  csv office Excel 需要添加bom头
1894 1887
     if (pathinfo($file, PATHINFO_EXTENSION) == 'csv') {
1895 1888
         echo "\xEF\xBB\xBF";    // UTF-8 BOM
1896 1889
     }
1897
-
1890
+    
1898 1891
     $fileCount = 0;
1899 1892
     $fileUnit = 1024;
1900 1893
     while (!feof($fp) && $size - $fileCount > 0) {
@@ -1903,7 +1896,7 @@ function download($file, $name = '', $del = false)
1903 1896
         $fileCount += $fileUnit;
1904 1897
     }
1905 1898
     fclose($fp);
1906
-
1899
+    
1907 1900
     // 删除
1908 1901
     if ($del) @unlink($file);
1909 1902
     die();
@@ -1924,7 +1917,7 @@ function tempFileName($ext = '')
1924 1917
     if (!file_exists($path)) {
1925 1918
         mkdir($path, 0777, true);
1926 1919
     }
1927
-
1920
+    
1928 1921
     $ext = trim($ext, '.');
1929 1922
     do {
1930 1923
         $temp_file = md5(time() . rand(1000, 9999));
@@ -1953,7 +1946,7 @@ function delDir($dir)
1953 1946
             }
1954 1947
         }
1955 1948
     }
1956
-
1949
+    
1957 1950
     closedir($dh);
1958 1951
     //删除当前文件夹:
1959 1952
     @rmdir($dir);
@@ -2065,7 +2058,7 @@ function getTimeArray($start = null, $end = null)
2065 2058
                 break;
2066 2059
         }
2067 2060
     }
2068
-
2061
+    
2069 2062
     $between = [$start, $end];
2070 2063
     $list = [];
2071 2064
     $len = ($end - $start) / 86400;
@@ -2094,7 +2087,7 @@ function getTimeArray($start = null, $end = null)
2094 2087
             $start = $item['end_time'] + 1;
2095 2088
         }
2096 2089
     }
2097
-
2090
+    
2098 2091
     return [
2099 2092
         'list' => $list,        // 时间段列表
2100 2093
         'time_format' => $time_format,      // 时间格式 mysql 格式化时间戳
@@ -2127,8 +2120,8 @@ function DBBackup($file = '', $path = '')
2127 2120
     $username = config('database.username');
2128 2121
     $password = config('database.password');
2129 2122
     $dsn = "{$type}:host={$host};dbname={$dbname};port={$port}";
2130
-
2131
-
2123
+    
2124
+    
2132 2125
     if ($file == '') {
2133 2126
         $save_path = dirname(APP_PATH) . DS . 'data' . DS . date('Ym') . DS;
2134 2127
         if (!file_exists($save_path) && !mkdir($save_path, '0777', true)) {
@@ -2136,11 +2129,11 @@ function DBBackup($file = '', $path = '')
2136 2129
         }
2137 2130
         $file = $save_path . date('d_H_i') . '_db_backup' . '.sql';
2138 2131
     }
2139
-
2132
+    
2140 2133
     if (file_exists($file)) {
2141 2134
         return '数据库备份文件已存在(自动备份时间间隔需大于1分钟)。';
2142 2135
     }
2143
-
2136
+    
2144 2137
     try {
2145 2138
         $backup = new \com\Mysqldump($dsn, $username, $password);
2146 2139
         $backup->start($file);
@@ -2148,7 +2141,7 @@ function DBBackup($file = '', $path = '')
2148 2141
     } catch (\Exception $e) {
2149 2142
         return '备份失败,请手动备份。错误原因:' . $e->getMessage();
2150 2143
     }
2151
-
2144
+    
2152 2145
 }
2153 2146
 
2154 2147
 /**
@@ -2171,17 +2164,17 @@ if (!function_exists('isSuperAdministrators')) {
2171 2164
     function isSuperAdministrators($userId)
2172 2165
     {
2173 2166
         $status = false;
2174
-
2167
+        
2175 2168
         $apiCommon = new \app\admin\controller\ApiCommon();
2176
-
2169
+        
2177 2170
         $userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
2178
-
2171
+        
2179 2172
         $data = db('admin_access')->where('user_id', $userId)->column('group_id');
2180
-
2173
+        
2181 2174
         if ($userId == 1 || in_array(1, $data)) {
2182 2175
             $status = true;
2183 2176
         }
2184
-
2177
+        
2185 2178
         return $status;
2186 2179
     }
2187 2180
 }
@@ -2195,11 +2188,11 @@ if (!function_exists('getFieldGrantData')) {
2195 2188
     function getFieldGrantData($userId)
2196 2189
     {
2197 2190
         $result = [];
2198
-
2191
+        
2199 2192
         $apiCommon = new \app\admin\controller\ApiCommon();
2200
-
2193
+        
2201 2194
         $userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
2202
-
2195
+        
2203 2196
         $grantData = Db::query("
2204 2197
             SELECT 
2205 2198
                 `grant`.`module`, `grant`.`column`, `grant`.`content` 
@@ -2212,12 +2205,14 @@ if (!function_exists('getFieldGrantData')) {
2212 2205
             WHERE 
2213 2206
                 `access`.`user_id` = 
2214 2207
         " . $userId);
2215
-
2208
+        
2216 2209
         # 存在多角色多授权的情况
2217
-        foreach ($grantData AS $key => $value) {
2210
+        foreach ($grantData as $key => $value) {
2211
+            if (empty($value['module']) || empty($value['column'])) continue;
2212
+            
2218 2213
             $result[$value['module'] . '_' . $value['column']][] = !empty($value['content']) ? unserialize($value['content']) : [];
2219 2214
         }
2220
-
2215
+        
2221 2216
         return $result;
2222 2217
     }
2223 2218
 }
@@ -2234,27 +2229,34 @@ if (!function_exists('getFieldGrantStatus')) {
2234 2229
     {
2235 2230
         # 默认状态都是不能查看、不能编辑,通过配置来取最大权限。
2236 2231
         $result = ['read' => 0, 'write' => 0];
2237
-
2238
-        foreach ($grantData AS $key => $value) {
2239
-            # 对于不在权限控制之内的字段,将状态都改为1。
2232
+        
2233
+        foreach ($grantData as $key => $value) {
2240 2234
             $fieldBool = false;
2241
-
2242
-            foreach ($value AS $ke => $va) {
2243
-                if ($va['field'] == $field) {
2244
-                    $result['read']  = $va['read']  > $result['read']  ? $va['read']  : $result['read'];
2235
+            
2236
+            foreach ($value as $ke => $va) {
2237
+                # 多个字段授权,只取最高的读权限
2238
+                if ($va['field'] == $field && $result['read'] == 0) {
2239
+                    $result['read'] = $va['read'] > $result['read'] ? $va['read'] : $result['read'];
2240
+                }
2241
+                
2242
+                # 多个字段授权,只取最高的写权限
2243
+                if ($va['field'] == $field && $result['write'] == 0) {
2245 2244
                     $result['write'] = $va['write'] > $result['write'] ? $va['write'] : $result['write'];
2246
-                    $fieldBool       = true;
2247 2245
                 }
2246
+                
2247
+                if ($va['field'] == $field) $fieldBool = true;
2248 2248
             }
2249
-
2249
+            
2250
+            # 对于不在权限控制之内的字段,将状态都改为1。
2250 2251
             if (!$fieldBool) {
2251
-                $result['read']  = 1;
2252
+                $result['read'] = 1;
2252 2253
                 $result['write'] = 1;
2253 2254
             }
2254 2255
         }
2255
-
2256
+        
2256 2257
         return $result;
2257 2258
     }
2259
+    
2258 2260
     /**
2259 2261
      * 仪表盘日志使用
2260 2262
      * 根据类型获取开始结束时间戳数组
@@ -2299,7 +2301,7 @@ if (!function_exists('getFieldGrantStatus')) {
2299 2301
                     $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
2300 2302
                     $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
2301 2303
                 }
2302
-
2304
+                
2303 2305
                 //上季度
2304 2306
                 $month = date('m');
2305 2307
                 if ($month == 1 || $month == 2 || $month == 3) {
@@ -2317,7 +2319,7 @@ if (!function_exists('getFieldGrantStatus')) {
2317 2319
                     $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
2318 2320
                 }
2319 2321
                 $timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
2320
-
2322
+                
2321 2323
                 $timeArr = array($daterange_start_time, $daterange_end_time);
2322 2324
                 break;
2323 2325
             case 'lastQuarter' :
@@ -2377,4 +2379,152 @@ if (!function_exists('getFieldGrantStatus')) {
2377 2379
         }
2378 2380
         return $timeArr;
2379 2381
     }
2382
+    
2383
+    /**
2384
+     * 系统操作日志
2385
+     * @param int $user_id 用户
2386
+     * @param string $types 方法所属模块
2387
+     * @param int $action_id 操作
2388
+     * @param string $module_name 模块
2389
+     * @param string $action_name 修改添加删除新建
2390
+     * @param array $oldData 旧数据
2391
+     * @param array $newData 新数据
2392
+     * @param string $target_name 被操作对象
2393
+     * @param string $content 添加时创建使用
2394
+     * @author      alvin guogaobo
2395
+     * @version     1.0 版本号
2396
+     * @since       2021/3/26 0026 15:10
2397
+     */
2398
+    function SystemActionLog($user_id, $types, $module_name, $action_id, $action_name, $target_name, $oldData = [], $newData = [], $content = '')
2399
+    {
2400
+        //action_name 修改添加删除新建 action_id 操作id client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module_name 模块 系统管理 固定  user_id 用户
2401
+        $data = [];
2402
+        $data['user_id'] = $user_id;
2403
+        $data['create_time'] = time();
2404
+        $data['client_ip'] = request()->ip();
2405
+        $data['action_id'] = $action_id;
2406
+        $data['action_name'] = $action_name;
2407
+        $data['target_name'] = $target_name;
2408
+        $data['module_name'] = $module_name;
2409
+        $data['controller_name'] = $types;
2410
+        $data['content'] = $content;
2411
+        db('admin_system_log')->insert($data);
2412
+    }
2413
+    
2414
+    /**
2415
+     * 系统操作日志
2416
+     * @param int $user_id 用户
2417
+     * @param string $types 方法所属模块
2418
+     * @param string $action_name 修改添加删除新建
2419
+     * @param string $target_name 被操作对象
2420
+     * @param array $oldData 旧数据
2421
+     * @param array $newData 新数据
2422
+     * @param string $content 添加时创建使用
2423
+     * @author      alvin guogaobo
2424
+     * @version     1.0 版本号
2425
+     * @since       2021/4/2 0026 15:10
2426
+     */
2427
+    function RecordActionLog($user_id, $types, $action_name, $target_name, $oldData = [], $newData = [], $content = '')
2428
+    {
2429
+        //action_name 修改 添加 删除  client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module 模块  user_id 用户
2430
+        if (is_array($oldData) && is_array($newData) && $user_id) {
2431
+            $differentData = array_diff_assoc($newData, $oldData);
2432
+            $fieldModel = new FieldModel();
2433
+            $userModel = new UserModel();
2434
+            $structureModel = new \app\admin\model\Structure();
2435
+            $field_arr = $fieldModel->getField(['types' => $types, 'unFormType' => ['file', 'form']]); //获取字段属性
2436
+            $newFieldArr = array();
2437
+            foreach ($field_arr as $k => $v) {
2438
+                $newFieldArr[$v['field']] = $v;
2439
+            }
2440
+            $unField = ['update_time', 'create_time']; //定义过滤字段
2441
+            $message = [];
2442
+            $un_form_type = ['file', 'form'];
2443
+            foreach ($differentData as $k => $v) {
2444
+                if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
2445
+                    $field_name = '';
2446
+                    $field_name = $newFieldArr[$k]['name'];
2447
+                    $new_value = $v ?: '空';
2448
+                    $old_value = $oldData[$k] ?: '空';
2449
+                    switch ($newFieldArr[$k]['form_type']) {
2450
+                        case 'datetime' :
2451
+                            $new_value = $v ? date('Y-m-d', $v) : '';
2452
+                            $old_value = date('Y-m-d', $oldData[$k]);
2453
+                            if (!empty($v) && !empty($oldData[$k]))
2454
+                            break;
2455
+                        case 'user' :
2456
+                            $new_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($v))) : '';
2457
+                            $old_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($oldData[$k]))) : '';
2458
+                            break;
2459
+                        case 'structure' :
2460
+                            $new_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($v))) : '';
2461
+                            $old_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($oldData[$k]))) : '';
2462
+                            break;
2463
+                        case 'business_status' :
2464
+                            $new_value = $v ? db('crm_business_status')->where(['status_id' => $v])->value('name') : '';
2465
+                            $old_value = $v ? db('crm_business_status')->where(['status_id' => $oldData[$k]])->value('name') : '';
2466
+                            break;
2467
+                        case 'business_type' :
2468
+                            $new_value = $v ? db('crm_business_type')->where(['type_id' => $v])->value('name') : '';
2469
+                            $old_value = $v ? db('crm_business_type')->where(['type_id' => $oldData[$k]])->value('name') : '';
2470
+                            break;
2471
+                        case 'customer' :
2472
+                            $new_value = $v ? db('crm_customer')->where(['customer_id' => $v])->value('name') : '';
2473
+                            $old_value = $v ? db('crm_customer')->where(['customer_id' => $oldData[$k]])->value('name') : '';
2474
+                            break;
2475
+                        case 'category' :
2476
+                            $new_value = $v ? db('crm_product_category')->where(['category_id' => $v])->value('name') : '';
2477
+                            $old_value = $v ? db('crm_product_category')->where(['category_id' => $oldData[$k]])->value('name') : '';
2478
+                            break;
2479
+                        case 'business' :
2480
+                            $new_value = $v ? db('crm_business')->where(['business_id' => $v])->value('name') : '';
2481
+                            $old_value = $v ? db('crm_business')->where(['business_id' => $oldData[$k]])->value('name') : '';
2482
+                            break;
2483
+                        case 'visit' :
2484
+                            $new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
2485
+                            $old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
2486
+                            break;
2487
+                        case 'single_user' :
2488
+                            $new_value = $v ? db('admin_user')->where(['id' => $v])->value('realname') : '';
2489
+                            $old_value = $v ? db('admin_user')->where(['id' => $oldData['owner_user_id']])->value('realname') : '';
2490
+                            break;
2491
+                        case 'floatnumber' :
2492
+                            $new_value = $v ? number_format($v, 2) : '';
2493
+                            break;
2494
+                    }
2495
+                    if ($newFieldArr[$k]['field'] == 'check_status') {
2496
+                        $statusArr = ['0' => '待审核', '1' => '审核中', '2' => '审核通过', '3' => '已拒绝', '4' => '已撤回', '5' => '未提交'];
2497
+                        $new_value = $statusArr[$v];
2498
+                        $old_value = $statusArr[$oldData[$k]];
2499
+                    }
2500
+                    if ($old_value != $new_value) {
2501
+                        $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
2502
+                    }
2503
+                }
2504
+            }
2505
+            if ($message) {
2506
+                $data = [];
2507
+                $data['user_id'] = $user_id;
2508
+                $data['create_time'] = time();
2509
+                $data['client_ip'] = request()->ip();
2510
+                $data['action_name'] = $action_name;
2511
+                $data['action_id'] = 1;
2512
+                $data['target_name'] = $target_name;
2513
+                $data['module'] = $types;  //子模块 客户线索
2514
+                $data['content'] = implode(',', $message);
2515
+                db('admin_operation_log')->insert($data);
2516
+            }
2517
+        } elseif ($content) {
2518
+            $data = [];
2519
+            $data['user_id'] = $user_id;
2520
+            $data['create_time'] = time();
2521
+            $data['client_ip'] = request()->ip();
2522
+            $data['action_name'] = $action_name;
2523
+            $data['target_name'] = $target_name;
2524
+            $data['action_id'] = 1;
2525
+            $data['module'] = $types;  //子模块 客户线索
2526
+            $data['content'] = $content;
2527
+            db('admin_operation_log')->insert($data);
2528
+        }
2529
+    }
2380 2530
 }

+ 411
- 0
application/common/command/PoolCommand.php Zobrazit soubor

@@ -0,0 +1,411 @@
1
+<?php
2
+/**
3
+ * 使用定时器将符合条件的用户回收到公海池
4
+ *
5
+ * @author fanqi
6
+ * @since 2021-03-31
7
+ */
8
+
9
+namespace app\common\command;
10
+
11
+use think\Config;
12
+use think\console\Command;
13
+use think\console\Input;
14
+use think\console\input\Argument;
15
+use think\console\input\Option;
16
+use think\console\Output;
17
+use think\Db;
18
+use think\response\Json;
19
+use Workerman\Lib\Timer;
20
+use Workerman\Worker;
21
+
22
+class PoolCommand extends Command
23
+{
24
+    protected $timer;
25
+    protected $interval = 10;
26
+
27
+    protected function configure()
28
+    {
29
+        $this->setName('pool')
30
+            ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
31
+            ->addOption('d', null, Option::VALUE_NONE, 'daemon(守护进程)方式启动')
32
+            ->setDescription('公海回收定时器');
33
+
34
+        // 读取数据库配置文件
35
+        $filename = ROOT_PATH . 'config'.DS.'database.php';
36
+        // 重新加载数据库配置文件
37
+        Config::load($filename, 'database');
38
+    }
39
+
40
+    /**
41
+     * 初始化
42
+     *
43
+     * @param Input $input
44
+     * @param Output $output
45
+     */
46
+    protected function init(Input $input, Output $output)
47
+    {
48
+        global $argv;
49
+
50
+        $argv[1] = $input->getArgument('status') ? : 'start';
51
+
52
+        if ($input->hasOption('d')) {
53
+            $argv[2] = '-d';
54
+        } else {
55
+            unset($argv[2]);
56
+        }
57
+    }
58
+
59
+    /**
60
+     * 停止定时器
61
+     */
62
+    public function stop()
63
+    {
64
+        Timer::del($this->timer);
65
+    }
66
+
67
+    /**
68
+     * 启动定时器
69
+     */
70
+    public function start()
71
+    {
72
+        $this->timer = Timer::add($this->interval, function () {
73
+            # 只在凌晨12点至6点间执行
74
+            if ((int)date('H') >= 0 && (int)date('H') < 6) {
75
+                # 公海规则
76
+                $ruleList = db('crm_customer_pool_rule')->alias('rule')->field('rule.*')
77
+                    ->join('__CRM_CUSTOMER_POOL__ pool', 'pool.pool_id = rule.pool_id', 'LEFT')->where('pool.status', 1)->select();
78
+
79
+                if (!empty($ruleList)) {
80
+                    # 符合公海条件的客户IDS
81
+                    $customerIds = $this->getQueryCondition($ruleList);
82
+
83
+                    # 整理客户公海关联数据
84
+                    $poolRelationData = $this->getCustomerPoolRelationData($customerIds);
85
+
86
+                    # 整理修改客户数据的条件(进入公海时间,前负责人...)
87
+                    $customerWhere = $this->getCustomerQueryCondition($customerIds);
88
+
89
+                    Db::startTrans();
90
+                    try {
91
+                        # 将客户退回公海
92
+                        if (!empty($poolRelationData)) Db::name('crm_customer_pool_relation')->insertAll($poolRelationData);
93
+
94
+                        # 修改客户数据
95
+                        if (!empty($customerWhere)) {
96
+                            Db::name('crm_customer')->whereIn('customer_id', $customerWhere)->exp('before_owner_user_id', 'owner_user_id')->update([
97
+                                'ro_user_id' => '',
98
+                                'rw_user_id' => '',
99
+                                'owner_user_id' => 0,
100
+                                'into_pool_time' => time()
101
+                            ]);
102
+                        }
103
+
104
+                        # 删除联系人的负责人
105
+                        Db::name('crm_contacts')->whereIn('customer_id', $customerWhere)->update(['owner_user_id' => '']);
106
+
107
+                        Db::commit();
108
+                    } catch (\Exception $e) {
109
+                        Db::rollback();
110
+                    }
111
+                }
112
+            }
113
+        });
114
+    }
115
+
116
+    protected function execute(Input $input, Output $output)
117
+    {
118
+        # 动态修改运行时参数
119
+        set_time_limit(0);
120
+        ini_set('memory_limit', '512M');
121
+
122
+        $this->init($input, $output);
123
+
124
+        # 创建定时器任务
125
+        $task = new Worker();
126
+        $task->name = 'pool';
127
+        $task->count = 1;
128
+        $task->onWorkerStart = [$this, 'start'];
129
+        $task->runAll();
130
+    }
131
+
132
+    /**
133
+     * 整理修改客户数据的条件
134
+     *
135
+     * @param array $customerIds 客户ID
136
+     * @author fanqi
137
+     * @since 2021-04-01
138
+     * @return array
139
+     */
140
+    private function getCustomerQueryCondition($customerIds)
141
+    {
142
+        $result = [];
143
+
144
+        foreach ($customerIds AS $k1 => $v1) {
145
+            foreach ($v1 AS $k2 => $v2) {
146
+                $result[] = $v2;
147
+            }
148
+        }
149
+
150
+        return array_unique($result);
151
+    }
152
+
153
+    /**
154
+     * 客户公海关联数据
155
+     *
156
+     * @param array $customerIds 客户ID
157
+     * @author fanqi
158
+     * @since 2021-04-01
159
+     * @return array
160
+     */
161
+    private function getCustomerPoolRelationData($customerIds)
162
+    {
163
+        $result = [];
164
+
165
+        # 用于排重
166
+        $repeat = [];
167
+
168
+        foreach ($customerIds AS $k1 => $v1) {
169
+            $customerArray = array_unique($v1);
170
+            foreach ($customerArray AS $k2 => $v2) {
171
+                if (!empty($repeat[$k1][$v2])) continue;
172
+
173
+                $result[] = [
174
+                    'pool_id' => $k1,
175
+                    'customer_id' => $v2
176
+                ];
177
+
178
+                $repeat[$k1][$v2] = $v2;
179
+            }
180
+        }
181
+
182
+        return $result;
183
+    }
184
+
185
+    /**
186
+     * 获取符合公海条件的客户
187
+     *
188
+     * @param array $rules 公海规则数据
189
+     * @author fanqi
190
+     * @since 2021-04-01
191
+     * @return array
192
+     */
193
+    private function getQueryCondition($rules)
194
+    {
195
+        $result = [];
196
+
197
+        foreach ($rules AS $k => $v) {
198
+            if (!isset($result[$v['pool_id']])) $result[$v['pool_id']] = [];
199
+
200
+            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']));
201
+            if ($v['type'] == 2) $result[$v['pool_id']] = array_merge($result[$v['pool_id']], $this->getBusinessQueryResult($v['level_conf'], $v['level'], $v['deal_handle']));
202
+            if ($v['type'] == 3) $result[$v['pool_id']] = array_merge($result[$v['pool_id']], $this->getDealQueryResult($v['level_conf'], $v['level'], $v['business_handle']));
203
+        }
204
+
205
+        return $result;
206
+    }
207
+
208
+    /**
209
+     * N天内无新建跟进记录的客户
210
+     *
211
+     * @param int $type 类型:1 所有用户,不分级别,2 根据用户级别区分
212
+     * @param Json $levels 级别数据
213
+     * @param int $dealStatus 是否排除成交用户:1 排除,0 不排除
214
+     * @param int $businessStatus 是否排除有商机用户:1 排除,0 不排除
215
+     * @author fanqi
216
+     * @since 2021-04-01
217
+     * @return array
218
+     */
219
+    private function getFollowUpQueryResult($type, $levels, $dealStatus, $businessStatus)
220
+    {
221
+        # 转换格式
222
+        $levels = json_decode($levels, true);
223
+
224
+        # 默认条件
225
+        $where = "`customer`.`owner_user_id` > 0";
226
+
227
+        # 所有用户,不区分级别
228
+        if ($type == 1) {
229
+            foreach ($levels AS $k1 => $v1) {
230
+                if (!empty($v1['limit_day'])) {
231
+                    $time = time() - 24 * 60 * 60 * $v1['limit_day'];
232
+                    $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`)))";
233
+                }
234
+            }
235
+        }
236
+
237
+        # 根据用户级别设置条件
238
+        if ($type == 2) {
239
+            foreach ($levels AS $k1 => $v1) {
240
+                if (!empty($v1['level']) && !empty($v1['limit_day'])) {
241
+                    $time = (time() - 24 * 60 * 60 * $v1['limit_day']);
242
+                    if ($k1 == 0) {
243
+                        $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`)))";
244
+                    } else {
245
+                        $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`)))";
246
+                    }
247
+                }
248
+            }
249
+
250
+            # 获取最小天数,对于没有设置级别的客户数据使用
251
+            $minLimit = $this->getMinDay($levels);
252
+            $minTime = (time() - 24 * 60 * 60 * $minLimit);
253
+
254
+            $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`))) )";
255
+        }
256
+
257
+        # 选择不进入公海的客户(已成交客户)
258
+        if (!empty($dealStatus)) $where .= " AND (`customer`.`deal_status` <> '已成交' OR ISNULL(`customer`.`deal_status`))";
259
+
260
+        # 选择不进入公海的客户(有商机客户)
261
+        if (!empty($businessStatus)) $where .= " AND ISNULL(`business`.`customer_id`)";
262
+
263
+        # 锁定的客户不提醒
264
+        $where .= " AND `customer`.`is_lock` = 0";
265
+
266
+        # 查询符合条件的客户
267
+        return db('crm_customer')
268
+            ->alias('customer')->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
269
+            ->where($where)->column('customer.customer_id');
270
+    }
271
+
272
+    /**
273
+     * N天内无新建商机的客户
274
+     *
275
+     * @param int $type 类型:1 所有用户,不分级别,2 根据用户级别区分
276
+     * @param Json $levels 级别数据
277
+     * @param int $dealStatus 是否排除成交用户:1 排除,0 不排除
278
+     * @author fanqi
279
+     * @since 2021-04-01
280
+     * @return array|false|string
281
+     */
282
+    private function getBusinessQueryResult($type, $levels, $dealStatus)
283
+    {
284
+        # 转换格式
285
+        $levels = json_decode($levels, true);
286
+
287
+        # 默认条件
288
+        $where = "`customer`.`owner_user_id` > 0";
289
+
290
+        # 所有用户,不区分级别
291
+        if ($type == 1) {
292
+            foreach ($levels AS $k1 => $v1) {
293
+                if (!empty($v1['limit_day'])) {
294
+                    $time = time() - 24 * 60 * 60 * $v1['limit_day'];
295
+                    $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`) )";
296
+                }
297
+            }
298
+        }
299
+
300
+        # 根据用户级别设置条件
301
+        if ($type == 2) {
302
+            foreach ($levels AS $k1 => $v1) {
303
+                if (!empty($v1['level']) && !empty($v1['limit_day'])) {
304
+                    $time = time() - 24 * 60 * 60 * $v1['limit_day'];
305
+                    if ($k1 == 0) {
306
+                        $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']."'))";
307
+                    } else {
308
+                        $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']."'))";
309
+                    }
310
+                }
311
+            }
312
+
313
+            # 获取最小天数,对于没有设置级别的客户数据使用
314
+            $minLimit = $this->getMinDay($levels);
315
+            $minTime = (time() - 24 * 60 * 60 * $minLimit);
316
+
317
+            $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`)) )";
318
+        }
319
+
320
+        # 选择不进入公海的客户(已成交客户)
321
+        if (!empty($dealStatus)) $where .= " AND (`customer`.`deal_status` <> '已成交' OR ISNULL(`customer`.`deal_status`))";
322
+
323
+        # 锁定的客户不提醒
324
+        $where .= " AND `customer`.`is_lock` = 0";
325
+
326
+        # 查询匹配条件的客户
327
+        return db('crm_customer')->alias('customer')
328
+            ->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
329
+            ->where($where)->column('customer.customer_id');
330
+    }
331
+
332
+    /**
333
+     * N天内没有成交的客户
334
+     *
335
+     * @param int $type 类型:1 所有用户,不分级别,2 根据用户级别区分
336
+     * @param Json $levels 级别数据
337
+     * @param int $businessStatus 是否排除有商机用户:1 排除,0 不排除
338
+     * @author fanqi
339
+     * @since 2021-04-01
340
+     * @return array|false|string
341
+     */
342
+    private function getDealQueryResult($type, $levels, $businessStatus)
343
+    {
344
+        # 转换格式
345
+        $levels = json_decode($levels, true);
346
+
347
+        # 默认条件
348
+        $where = "`customer`.`owner_user_id` > 0";
349
+
350
+        # 所有用户,不区分级别
351
+        if ($type == 1) {
352
+            foreach ($levels AS $k1 => $v1) {
353
+                if (!empty($v1['limit_day'])) {
354
+                    $time = time() - 24 * 60 * 60 * $v1['limit_day'];
355
+                    $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`) )";
356
+                }
357
+            }
358
+        }
359
+
360
+        # 根据用户级别设置条件
361
+        if ($type == 2) {
362
+            foreach ($levels AS $k1 => $v1) {
363
+                if (!empty($v1['level']) && !empty($v1['limit_day'])) {
364
+                    $time = time() - 24 * 60 * 60 * $v1['limit_day'];
365
+                    if ($k1 == 0) {
366
+                        $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']."'))";
367
+                    } else {
368
+                        $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']."'))";
369
+                    }
370
+                }
371
+            }
372
+
373
+            # 获取最小天数,对于没有设置级别的客户数据使用
374
+            $minLimit = $this->getMinDay($levels);
375
+            $minTime = (time() - 24 * 60 * 60 * $minLimit);
376
+
377
+            $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`)) )";
378
+        }
379
+
380
+        # 选择不进入公海的客户(有商机客户)
381
+        if (!empty($businessStatus)) $where .= " AND ISNULL(`business`.`customer_id`)";
382
+
383
+        # 锁定的客户不提醒
384
+        $where .= " AND `customer`.`is_lock` = 0";
385
+
386
+        # 查询符合条件的客户
387
+        return db('crm_customer')->alias('customer')
388
+            ->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
389
+            ->join('__CRM_CONTRACT__ contract', 'contract.customer_id = customer.customer_id', 'LEFT')
390
+            ->where($where)->column('customer.customer_id');
391
+    }
392
+
393
+    /**
394
+     * 获取公海规则最小数字(最快进入公海天数)
395
+     *
396
+     * @param $data
397
+     * @author fanqi
398
+     * @since 2021-04-19
399
+     * @return int
400
+     */
401
+    private function getMinDay($data)
402
+    {
403
+        $number = 1;
404
+
405
+        foreach ($data AS $k1 => $v1) {
406
+            if (empty($number) || $v1['limit_day'] < $number) $number = $v1['limit_day'];
407
+        }
408
+
409
+        return $number;
410
+    }
411
+}

+ 8
- 3
application/crm/controller/Achievement.php Zobrazit soubor

@@ -96,6 +96,8 @@ class Achievement extends ApiCommon
96 96
         $param = $this->param;
97 97
         $userInfo = $this->userInfo;
98 98
         if ($model->createData($param)) {
99
+            # 系统操作日志
100
+            SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1,  'save','业绩目标设置' , '', '','添加了业绩目标');
99 101
             return resultArray(['data' => '添加成功']);
100 102
         } else {
101 103
             return resultArray(['error' => $model->getError()]);
@@ -129,9 +131,11 @@ class Achievement extends ApiCommon
129 131
     public function update()
130 132
     {    
131 133
         $model = model('Achievement');
132
-      
134
+        $userInfo = $this->userInfo;
133 135
         $param = $this->param;
134 136
         if ($model->updateData($param)) {
137
+            # 系统操作日志
138
+            SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1, 'update','业绩目标设置' , '', '','设置了业绩目标');
135 139
             return resultArray(['data' => '编辑成功']);
136 140
         } else {
137 141
             return resultArray(['error' => $model->getError()]);
@@ -150,9 +154,10 @@ class Achievement extends ApiCommon
150 154
         if (empty($this->param['achievement_id'])) return resultArray(['error' => '参数错误!']);
151 155
 
152 156
         $model = new \app\crm\model\Achievement();
153
-
157
+        $userInfo = $this->userInfo;
154 158
         if (!$model->delete($this->param['achievement_id'])) return resultArray(['error' => '操作失败!']);
155
-
159
+        # 系统操作日志
160
+        SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1, 'update','业绩目标设置' , '', '','删除了业绩目标');
156 161
         return resultArray(['data' => '操作成功!']);
157 162
     }
158 163
 }

+ 236
- 3
application/crm/controller/Activity.php Zobrazit soubor

@@ -24,7 +24,7 @@ class Activity extends ApiCommon
24 24
     {
25 25
         $action = [
26 26
             'permission'=>[],
27
-            'allow'=>['index', 'save', 'read', 'update', 'delete', 'getphrase', 'setphrase', 'getrecordauth']
27
+            'allow'=>['index', 'save', 'read', 'update', 'delete', 'getphrase', 'setphrase', 'getrecordauth','excelimport','excelexport','exceldownload']
28 28
         ];
29 29
         Hook::listen('check_auth',$action);
30 30
         $request = Request::instance();
@@ -77,7 +77,6 @@ class Activity extends ApiCommon
77 77
         $param['user_id'] = $this->userInfo['id'];
78 78
 
79 79
         if (!$activityLogic->save($param)) return resultArray(['error' => '操作失败!']);
80
-
81 80
         return resultArray(['data' => '操作成功!']);
82 81
     }
83 82
 
@@ -144,7 +143,6 @@ class Activity extends ApiCommon
144 143
         if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']);
145 144
 
146 145
         if (!$activityLogic->delete($this->param['activity_id'])) return resultArray(['error' => '操作失败!']);
147
-
148 146
         return resultArray(['data' => '操作成功!']);
149 147
     }
150 148
 
@@ -196,4 +194,239 @@ class Activity extends ApiCommon
196 194
 
197 195
         return resultArray(['data' => $data]);
198 196
     }
197
+    /**
198
+     * 导入模板下载
199
+     * @author      alvin guogaobo
200
+     * @version     1.0 版本号
201
+     * @since       2021/4/10 0010 16:01
202
+     */
203
+    public function excelDownload($save_path = ''){
204
+        $param = $this->param;
205
+        $excelModel = new \app\admin\model\Excel();
206
+        $field_list=$this->importData($param);
207
+        $types='crm_activity';
208
+        $excelModel->importDown($field_list,$types,$save_path);
209
+    }
210
+    
211
+    /**
212
+     * 导入导出模板标题
213
+     * @param $param
214
+     *
215
+     * @author      alvin guogaobo
216
+     * @version     1.0 版本号
217
+     * @since       2021/4/13 0013 11:15
218
+     */
219
+    public function importData($param){
220
+        switch ($param['label']){
221
+            case 1 :
222
+                $field = [
223
+                    '2' => [
224
+                        'name' => '所属线索',
225
+                        'field' => 'activity_type_id',
226
+                        'types' => 'log',
227
+                        'form_type' => 'datetime',
228
+                        'is_null' => 1,
229
+                    ]
230
+                ];
231
+                break;
232
+            case 3:
233
+                $field = [
234
+                    '2' => [
235
+                        'name' => '所属联系人',
236
+                        'field' => 'activity_type_id',
237
+                        'types' => 'log',
238
+                        'form_type' => 'datetime',
239
+                        'is_null' => 1,
240
+                    ],
241
+                ];
242
+                break;
243
+            case 5:
244
+                $field = [
245
+                    '2' => [
246
+                        'name' => '所属商机',
247
+                        'field' => 'activity_type_id',
248
+                        'types' => 'log',
249
+                        'form_type' => 'text',
250
+                        'is_null' => 1,
251
+                    ]
252
+                ];
253
+                break;
254
+            case 6:
255
+                $field = [
256
+                    '2' => [
257
+                        'name' => '所属合同',
258
+                        'field' => 'activity_type_id',
259
+                        'types' => 'log',
260
+                        'form_type' => 'text',
261
+                        'is_null' => 1,
262
+                    ],
263
+                ];
264
+                break;
265
+            case 2:
266
+                $field_list = [
267
+                    '0' => [
268
+                        'name' => '跟进内容',
269
+                        'field' => 'content',
270
+                        'types' => 'log',
271
+                        'form_type' => 'text',
272
+                        'is_null' => 1,
273
+                    ],
274
+                    '1' => [
275
+                        'name' => '创建人',
276
+                        'field' => 'create_user_id',
277
+                        'types' => 'log',
278
+                        'form_type' => 'user',
279
+                        'is_null' => 1,
280
+                    ],
281
+                    '2' => [
282
+                        'name' => '所属客户',
283
+                        'field' => 'activity_type_id',
284
+                        'types' => 'log',
285
+                        'form_type' => 'text',
286
+                        'is_null' => 1,
287
+                    ],
288
+                    '3' => [
289
+                        'name' => '跟进时间-例:2020-2-1',
290
+                        'field' => 'next_time',
291
+                        'types' => 'log',
292
+                        'form_type' => 'datetime',
293
+                    ],
294
+                    '4' => [
295
+                        'name' => '跟进方式',
296
+                        'field' => 'category',
297
+                        'types' => 'log',
298
+                        'form_type' => 'text',
299
+                    ],
300
+                    '5' => [
301
+                        'name' => '相关联系人',
302
+                        'field' => 'contacts_ids',
303
+                        'types' => 'log',
304
+                        'form_type' => 'text',
305
+                    ],
306
+                    '6' => [
307
+                        'name' => '相关商机',
308
+                        'field' => 'business_ids',
309
+                        'types' => 'log',
310
+                        'form_type' => 'text',
311
+                    ]
312
+                ];
313
+                break;
314
+        }
315
+        $fields = [
316
+            '0' => [
317
+                'name' => '跟进内容',
318
+                'field' => 'content',
319
+                'types' => 'log',
320
+                'form_type' => 'text',
321
+                'is_null' => 1,
322
+            ],
323
+            '1' => [
324
+                'name' => '创建人',
325
+                'field' => 'create_user_id',
326
+                'types' => 'log',
327
+                'form_type' => 'user',
328
+                'is_null' => 1,
329
+            ],
330
+            '2' => [
331
+                'name' => '所属111',
332
+                'field' => 'activity_type_id',
333
+                'types' => 'log',
334
+                'form_type' => 'text',
335
+                'is_null' => 1,
336
+            ],
337
+            '3' => [
338
+                'name' => '跟进时间-例:2020-2-1',
339
+                'field' => 'next_time',
340
+                'types' => 'log',
341
+                'form_type' => 'datetime',
342
+            ],
343
+            '4' => [
344
+                'name' => '跟进方式',
345
+                'field' => 'category',
346
+                'types' => 'log',
347
+                'form_type' => 'text',
348
+            ],
349
+        ];
350
+        // 导入的字段列表
351
+        if(!empty($param['down'])){
352
+            $field_list = [
353
+                '0' => ['name' => '所属客户', 'field' => 'activity_type_name'],
354
+                '1' => ['name' => '跟进内容', 'field' => 'content'],
355
+                '2' => ['name' => '创建人', 'field' => 'create_user_name'],
356
+                '3' => ['name' => '跟进时间', 'field' => 'create_time'],
357
+                '4' => ['name' => '跟进方式','field' => 'category'],
358
+                '5' => ['name' => '下次联系时间', 'field' => 'next_time'],
359
+                '6' => ['name' => '相关联系人', 'field' => 'contacts_ids'],
360
+                '7' => ['name' => '相关商机', 'field' => 'business_ids'],
361
+               
362
+            ];
363
+        }else{
364
+            if(empty($field_list)){
365
+                $field_list=array_merge($fields,$field);
366
+            }
367
+        }
368
+        return $field_list;
369
+    }
370
+    /**
371
+     * 导入数据
372
+     *
373
+     * @author      alvin guogaobo
374
+     * @version     1.0 版本号
375
+     * @since       2021/4/10 0010 16:27
376
+     */
377
+    public function excelImport(){
378
+        $param = $this->param;
379
+        $field_list=$this->importData($param['label']);
380
+        $excelModel = new \app\admin\model\Excel();
381
+        $file = request()->file('file');
382
+        switch ($param['label']){
383
+            case 1 :
384
+                $param['types']='crm_leads';
385
+                $param['activity_type']=1;
386
+                break;
387
+            case 3:
388
+                $param['types']='crm_contacts';
389
+                $param['activity_type']=3;
390
+                break;
391
+            case 5:
392
+                $param['types']='crm_business';
393
+                $param['activity_type']=5;
394
+                break;
395
+            case 6:
396
+                $param['types']='crm_contract';
397
+                $param['activity_type']=6;
398
+                break;
399
+            case 2:
400
+                $param['types']='crm_customer';
401
+                $param['activity_type']=2;
402
+                break;
403
+        }
404
+        $res = $excelModel->ActivityImport($file,$field_list, $param,$this);
405
+        if (!$res) {
406
+            return resultArray(['error' => $excelModel->getError()]);
407
+        }
408
+        return resultArray(['data' => $excelModel->getError()]);
409
+    }
410
+    
411
+    /**
412
+     * 导出跟进记录
413
+     * action 列表分辨是否导出
414
+     * label 导出类型 合同 客户 联系人
415
+     *
416
+     * @author      alvin guogaobo
417
+     * @version     1.0 版本号
418
+     * @since       2021/4/13 0013 11:32
419
+     */
420
+    public function excelExport(){
421
+       
422
+        $activityLogic=new ActivityLogic();
423
+        $indexLogic=new \app\crm\logic\IndexLogic();
424
+        $param = $this->param;
425
+        $param['action']='crm_activity';
426
+        $list=$indexLogic->activityList($param);
427
+//        $param['down']=1;
428
+        $field_list=$this->importData($param);
429
+        $data=$activityLogic->excelExport($field_list,$list);
430
+        return $data;
431
+    }
199 432
 }

+ 172
- 163
application/crm/controller/Business.php Zobrazit soubor

@@ -17,47 +17,47 @@ use think\Db;
17 17
 class Business extends ApiCommon
18 18
 {
19 19
     use StarTrait, SearchConditionTrait;
20
-
20
+    
21 21
     /**
22 22
      * 用于判断权限
23 23
      * @permission 无限制
24 24
      * @allow 登录用户可访问
25 25
      * @other 其他根据系统设置
26
-    **/    
26
+     **/
27 27
     public function _initialize()
28 28
     {
29 29
         $action = [
30
-            'permission'=>[''],
31
-            'allow'=>['statuslist','advance','product','system','count','setprimary']
30
+            'permission' => [''],
31
+            'allow' => ['statuslist', 'advance', 'product', 'system', 'count', 'setprimary']
32 32
         ];
33
-        Hook::listen('check_auth',$action);
33
+        Hook::listen('check_auth', $action);
34 34
         $request = Request::instance();
35
-        $a = strtolower($request->action());        
35
+        $a = strtolower($request->action());
36 36
         if (!in_array($a, $action['permission'])) {
37 37
             parent::_initialize();
38 38
         }
39
-    } 
40
-
39
+    }
40
+    
41 41
     /**
42 42
      * 商机列表
43
-     * @author Michael_xu
44 43
      * @return
44
+     * @author Michael_xu
45 45
      */
46 46
     public function index()
47 47
     {
48 48
         $businessModel = model('Business');
49 49
         $param = $this->param;
50 50
         $userInfo = $this->userInfo;
51
-        $param['user_id'] = $userInfo['id']; 
52
-        $data = $businessModel->getDataList($param);       
51
+        $param['user_id'] = $userInfo['id'];
52
+        $data = $businessModel->getDataList($param);
53 53
         return resultArray(['data' => $data]);
54 54
     }
55
-
55
+    
56 56
     /**
57 57
      * 添加商机
58
+     * @param
59
+     * @return
58 60
      * @author Michael_xu
59
-     * @param 
60
-     * @return 
61 61
      */
62 62
     public function save()
63 63
     {
@@ -66,19 +66,19 @@ class Business extends ApiCommon
66 66
         $userInfo = $this->userInfo;
67 67
         $param['create_user_id'] = $userInfo['id'];
68 68
         $param['owner_user_id'] = $userInfo['id'];
69
-
69
+        
70 70
         if ($businessModel->createData($param)) {
71 71
             return resultArray(['data' => '添加成功']);
72 72
         } else {
73 73
             return resultArray(['error' => $businessModel->getError()]);
74 74
         }
75 75
     }
76
-
76
+    
77 77
     /**
78 78
      * 商机详情
79
-     * @author Michael_xu
80
-     * @param  
79
+     * @param
81 80
      * @return
81
+     * @author Michael_xu
82 82
      */
83 83
     public function read()
84 84
     {
@@ -92,11 +92,11 @@ class Business extends ApiCommon
92 92
         $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'read');
93 93
         //读权限
94 94
         $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
95
-        $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');        
96
-        if (!in_array($data['owner_user_id'],$auth_user_ids) && !$rwPre && !$roPre) {
95
+        $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
96
+        if (!in_array($data['owner_user_id'], $auth_user_ids) && !$rwPre && !$roPre) {
97 97
             $authData['dataAuth'] = (int)0;
98 98
             return resultArray(['data' => $authData]);
99
-        }        
99
+        }
100 100
         //商机状态组
101 101
         $data['status_list'] = $businessStatusModel->getDataById($data['type_id']);
102 102
         $data['lose_reason'] = Db::name('CrmBusinessLog')
@@ -108,15 +108,15 @@ class Business extends ApiCommon
108 108
         }
109 109
         return resultArray(['data' => $data]);
110 110
     }
111
-
111
+    
112 112
     /**
113 113
      * 编辑商机
114
-     * @author Michael_xu
115
-     * @param 
114
+     * @param
116 115
      * @return
116
+     * @author Michael_xu
117 117
      */
118 118
     public function update()
119
-    {    
119
+    {
120 120
         $businessModel = model('Business');
121 121
         $userModel = new \app\admin\model\User();
122 122
         $param = $this->param;
@@ -126,31 +126,32 @@ class Business extends ApiCommon
126 126
         $data = $businessModel->getDataById($param['id']);
127 127
         $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'update');
128 128
         //读写权限
129
-        $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');        
130
-        if (!in_array($data['owner_user_id'],$auth_user_ids) && !$rwPre) {
129
+        $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
130
+        if (!in_array($data['owner_user_id'], $auth_user_ids) && !$rwPre) {
131 131
             header('Content-Type:application/json; charset=utf-8');
132
-            exit(json_encode(['code'=>102,'error'=>'无权操作']));
133
-        }        
132
+            exit(json_encode(['code' => 102, 'error' => '无权操作']));
133
+        }
134 134
         if ($businessModel->updateDataById($param, $param['id'])) {
135 135
             return resultArray(['data' => '编辑成功']);
136 136
         } else {
137 137
             return resultArray(['error' => $businessModel->getError()]);
138
-        }       
138
+        }
139 139
     }
140
-
140
+    
141 141
     /**
142 142
      * 删除商机(逻辑删)
143
-     * @author Michael_xu
144
-     * @param 
143
+     * @param
145 144
      * @return
145
+     * @author Michael_xu
146 146
      */
147 147
     public function delete()
148 148
     {
149
-        $param = $this->param; 
149
+        $param = $this->param;
150
+        $userInfo = $this->userInfo;
150 151
         $businessModel = model('Business');
151 152
         $recordModel = new \app\admin\model\Record();
152 153
         $fileModel = new \app\admin\model\File();
153
-        $actionRecordModel = new \app\admin\model\ActionRecord();    
154
+        $actionRecordModel = new \app\admin\model\ActionRecord();
154 155
         if (!is_array($param['id'])) {
155 156
             $business_id[] = $param['id'];
156 157
         } else {
@@ -158,57 +159,60 @@ class Business extends ApiCommon
158 159
         }
159 160
         $delIds = [];
160 161
         $errorMessage = [];
161
-
162
+        
162 163
         //数据权限判断
163 164
         $userModel = new \app\admin\model\User();
164 165
         $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'delete');
165
-        foreach ($business_id as $k=>$v) {
166
+        foreach ($business_id as $k => $v) {
166 167
             $isDel = true;
167 168
             //数据详情
168 169
             $data = $businessModel->getDataById($v);
169 170
             if (!$data) {
170 171
                 $isDel = false;
171
-                $errorMessage[] = 'id为'.$v.'的商机删除失败,错误原因:'.$businessModel->getError();
172
+                $errorMessage[] = 'id为' . $v . '的商机删除失败,错误原因:' . $businessModel->getError();
172 173
             }
173
-            if (!in_array($data['owner_user_id'],$auth_user_ids)) {
174
+            if (!in_array($data['owner_user_id'], $auth_user_ids)) {
174 175
                 $isDel = false;
175
-                $errorMessage[] = '名称为'.$data['name'].'的商机删除失败,错误原因:无权操作';
176
+                $errorMessage[] = '名称为' . $data['name'] . '的商机删除失败,错误原因:无权操作';
176 177
             }
177 178
             if ($isDel) {
178
-                if (db('crm_contract')->where(['business_id'=> $v, 'check_status' => ['in', '0,1,2']])->value('contract_id')) {
179
+                if (db('crm_contract')->where(['business_id' => $v, 'check_status' => ['in', '0,1,2']])->value('contract_id')) {
179 180
                     $isDel = false;
180
-                    $errorMessage[] = '名称为'.$data['name'].'的商机删除失败,错误原因:商机下关联的有合同,无法删除!';
181
-                }                
181
+                    $errorMessage[] = '名称为' . $data['name'] . '的商机删除失败,错误原因:商机下关联的有合同,无法删除!';
182
+                }
182 183
             }
183 184
             if ($isDel) {
184 185
                 $delIds[] = $v;
185
-            }         
186
+            }
186 187
         }
188
+        $dataInfo = $businessModel->where('visit_id',['in',$delIds])->select();
187 189
         if ($delIds) {
188 190
             $data = $businessModel->delDatas($delIds);
189 191
             if (!$data) {
190 192
                 return resultArray(['error' => $businessModel->getError()]);
191 193
             }
192 194
             //删除跟进记录
193
-            $recordModel->delDataByTypes(5,$delIds);
195
+            $recordModel->delDataByTypes(5, $delIds);
194 196
             //删除关联附件
195
-            $fileModel->delRFileByModule('crm_business',$delIds);
197
+            $fileModel->delRFileByModule('crm_business', $delIds);
196 198
             //删除关联操作记录
197
-            $actionRecordModel->delDataById(['types'=>'crm_business','action_id'=>$delIds]);           
198
-            actionLog($delIds,'','','');         
199
+            $actionRecordModel->delDataById(['types' => 'crm_business', 'action_id' => $delIds]);
200
+            foreach ($dataInfo as $k => $v) {
201
+                RecordActionLog($userInfo['id'], 'crm_business', 'delete', $v['name'], '', '', '删除了商机:' . $v['name']);
202
+            }
199 203
         }
200 204
         if ($errorMessage) {
201 205
             return resultArray(['error' => $errorMessage]);
202 206
         } else {
203 207
             return resultArray(['data' => '删除成功']);
204
-        }        
208
+        }
205 209
     }
206
-
210
+    
207 211
     /**
208 212
      * 符合条件的商机状态组
209
-     * @author Michael_xu
210
-     * @param 
213
+     * @param
211 214
      * @return
215
+     * @author Michael_xu
212 216
      */
213 217
     public function statusList()
214 218
     {
@@ -218,28 +222,28 @@ class Business extends ApiCommon
218 222
         if (!$list) {
219 223
             $userInfo = $this->userInfo;
220 224
             $list = db('crm_business_type')
221
-                    ->field(['name', 'status', 'structure_id', 'type_id'])
222
-                    ->where(['structure_id' => ['like','%,'.$userInfo['structure_id'].',%'],'status' => 1])
223
-                    ->where('is_display', 1)
224
-                    ->whereOr('structure_id','')
225
-                    ->select();
226
-            foreach ($list as $k=>$v) {
225
+                ->field(['name', 'status', 'structure_id', 'type_id'])
226
+                ->where(['structure_id' => ['like', '%,' . $userInfo['structure_id'] . ',%'], 'status' => 1])
227
+                ->where('is_display', 1)
228
+                ->whereOr('structure_id', '')
229
+                ->select();
230
+            foreach ($list as $k => $v) {
227 231
                 $list[$k]['statusList'] = $businessStatusModel->getDataList($v['type_id']);
228 232
             }
229 233
             cache($key, $list, config('business_status_cache_time'));
230 234
         }
231
-
235
+        
232 236
         return resultArray(['data' => $list]);
233
-    }          
237
+    }
234 238
     
235 239
     /**
236 240
      * 商机转移
237
-     * @author Michael_xu
238 241
      * @param owner_user_id 变更负责人
239 242
      * @param is_remove 1移出,2转为团队成员
240 243
      * @param type 权限 1只读2读写
241 244
      * @return
242
-     */ 
245
+     * @author Michael_xu
246
+     */
243 247
     public function transfer()
244 248
     {
245 249
         $param = $this->param;
@@ -248,12 +252,12 @@ class Business extends ApiCommon
248 252
         $settingModel = model('Setting');
249 253
         $userModel = new \app\admin\model\User();
250 254
         $authIds = $userModel->getUserByPer(); //权限范围的user_id
251
-
255
+        
252 256
         if (!$param['owner_user_id']) {
253 257
             return resultArray(['error' => '变更负责人不能为空']);
254 258
         }
255 259
         if (!$param['business_id'] || !is_array($param['business_id'])) {
256
-            return resultArray(['error' => '请选择需要转移的商机']); 
260
+            return resultArray(['error' => '请选择需要转移的商机']);
257 261
         }
258 262
         
259 263
         $is_remove = $param['is_remove'] == 2 ? 2 : 1;
@@ -262,22 +266,22 @@ class Business extends ApiCommon
262 266
         $data = [];
263 267
         $data['owner_user_id'] = $param['owner_user_id'];
264 268
         $data['update_time'] = time();
265
-
269
+        
266 270
         $ownerUserName = $userModel->getUserNameById($param['owner_user_id']);
267 271
         $errorMessage = [];
268 272
         foreach ($param['business_id'] as $business_id) {
269 273
             $businessInfo = $businessModel->getDataById($business_id);
270
-
274
+            
271 275
             if (!$businessInfo) {
272
-                $errorMessage[] = '名称:为《'.$businessInfo['name'].'》的商机转移失败,错误原因:数据不存在;';
276
+                $errorMessage[] = '名称:为《' . $businessInfo['name'] . '》的商机转移失败,错误原因:数据不存在;';
273 277
                 continue;
274 278
             }
275 279
             //权限判断
276
-            if (!in_array($businessInfo['owner_user_id'],$authIds)) {
277
-                $errorMessage[] = $businessInfo['name'].'"转移失败,错误原因:无权限;';
280
+            if (!in_array($businessInfo['owner_user_id'], $authIds)) {
281
+                $errorMessage[] = $businessInfo['name'] . '"转移失败,错误原因:无权限;';
278 282
                 continue;
279 283
             }
280
-
284
+            
281 285
             //团队成员
282 286
             teamUserId(
283 287
                 'crm_business',
@@ -287,10 +291,10 @@ class Business extends ApiCommon
287 291
                 $is_remove,
288 292
                 0
289 293
             );
290
-
294
+            
291 295
             $resBusiness = db('crm_business')->where(['business_id' => $business_id])->update($data);
292 296
             if (!$resBusiness) {
293
-                $errorMessage[] = $businessInfo['name'].'"转移失败,错误原因:数据出错;';
297
+                $errorMessage[] = $businessInfo['name'] . '"转移失败,错误原因:数据出错;';
294 298
                 continue;
295 299
             } else {
296 300
                 $businessArray = [];
@@ -305,23 +309,25 @@ class Business extends ApiCommon
305 309
                 }
306 310
                 db('crm_business')->where('business_id', $business_id)->update($businessArray);
307 311
             }
308
-
312
+            
309 313
             //修改记录
310
-            updateActionLog($userInfo['id'], 'crm_business', $business_id, '', '', '将商机转移给:'.$ownerUserName);       
314
+            updateActionLog($userInfo['id'], 'crm_business', $business_id, '', '', '将商机转移给:' . $ownerUserName);
315
+            RecordActionLog($userInfo['id'], 'crm_business', 'transfer', $businessInfo['name'], '', '', '将商机:' . $businessInfo['name'] . '转移给:' . $ownerUserName);
316
+            
311 317
         }
312 318
         if (!$errorMessage) {
313 319
             return resultArray(['data' => '转移成功']);
314 320
         } else {
315 321
             return resultArray(['error' => $errorMessage]);
316 322
         }
317
-    } 
318
-
323
+    }
324
+    
319 325
     /**
320 326
      * 相关产品
321
-     * @author Michael_xu
322
-     * @param 
327
+     * @param
323 328
      * @return
324
-     */ 
329
+     * @author Michael_xu
330
+     */
325 331
     public function product()
326 332
     {
327 333
         $productModel = model('Product');
@@ -331,44 +337,44 @@ class Business extends ApiCommon
331 337
         if (!$param['business_id']) {
332 338
             return resultArray(['error' => '参数错误']);
333 339
         }
334
-        $businessInfo = db('crm_business')->where(['business_id' => $param['business_id']])->find();     
340
+        $businessInfo = db('crm_business')->where(['business_id' => $param['business_id']])->find();
335 341
         //判断权限
336 342
         $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'read');
337 343
         //读写权限
338 344
         $roPre = $userModel->rwPre($userInfo['id'], $businessInfo['ro_user_id'], $businessInfo['rw_user_id'], 'read');
339 345
         $rwPre = $userModel->rwPre($userInfo['id'], $businessInfo['ro_user_id'], $businessInfo['rw_user_id'], 'update');
340
-        if (!in_array($businessInfo['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
346
+        if (!in_array($businessInfo['owner_user_id'], $auth_user_ids) && !$roPre && !$rwPre) {
341 347
             header('Content-Type:application/json; charset=utf-8');
342
-            exit(json_encode(['code'=>102,'error'=>'无权操作']));
348
+            exit(json_encode(['code' => 102, 'error' => '无权操作']));
343 349
         }
344 350
         $dataList = db('crm_business_product')->where(['business_id' => $param['business_id']])->select();
345
-        foreach ($dataList as $k=>$v) {
351
+        foreach ($dataList as $k => $v) {
346 352
             $where = [];
347 353
             $where['product_id'] = $v['product_id'];
348 354
             $productInfo = db('crm_product')->where($where)->field('name,category_id')->find();
349 355
             $category_name = db('crm_product_category')->where(['category_id' => $productInfo['category_id']])->value('name');
350
-            $dataList[$k]['name'] = $productInfo['name'] ? : '';
351
-            $dataList[$k]['category_id_info'] = $category_name ? : '';
356
+            $dataList[$k]['name'] = $productInfo['name'] ?: '';
357
+            $dataList[$k]['category_id_info'] = $category_name ?: '';
352 358
         }
353
-        $list['list'] = $dataList ? : [];
354
-        $list['total_price'] = $businessInfo['total_price'] ? : '0.00';
355
-        $list['discount_rate'] = $businessInfo['discount_rate'] ? : '0.00';        
359
+        $list['list'] = $dataList ?: [];
360
+        $list['total_price'] = $businessInfo['total_price'] ?: '0.00';
361
+        $list['discount_rate'] = $businessInfo['discount_rate'] ?: '0.00';
356 362
         return resultArray(['data' => $list]);
357
-    }  
358
-
363
+    }
364
+    
359 365
     /**
360 366
      * 商机状态推进
361
-     * @author Michael_xu
362 367
      * @param business_id 商机ID
363 368
      * @param status_id 推进商机状态ID
364 369
      * @return
365
-     */ 
370
+     * @author Michael_xu
371
+     */
366 372
     public function advance()
367 373
     {
368 374
         $param = $this->param;
369 375
         $userInfo = $this->userInfo;
370 376
         $userModel = new \app\admin\model\User();
371
-        $is_end = $param['is_end'] ? : 0; //1赢单2输单3无效
377
+        $is_end = $param['is_end'] ?: 0; //1赢单2输单3无效
372 378
         if (!$param['business_id']) {
373 379
             return resultArray(['error' => '参数错误']);
374 380
         }
@@ -380,13 +386,13 @@ class Business extends ApiCommon
380 386
         $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'update');
381 387
         //读写权限
382 388
         $rwPre = $userModel->rwPre($userInfo['id'], $businessInfo['ro_user_id'], $businessInfo['rw_user_id'], 'update');
383
-        if (!in_array($businessInfo['owner_user_id'],$auth_user_ids) && !$rwPre) {
389
+        if (!in_array($businessInfo['owner_user_id'], $auth_user_ids) && !$rwPre) {
384 390
             header('Content-Type:application/json; charset=utf-8');
385
-            exit(json_encode(['code'=>102,'error'=>'无权操作']));
391
+            exit(json_encode(['code' => 102, 'error' => '无权操作']));
386 392
         }
387
-
388
-        $status_id = $param['status_id'] ? : $businessInfo['status_id'];
389
-        $statusInfo = db('crm_business_status')->where(['type_id' => $businessInfo['type_id'],'status_id' => $status_id])->find();
393
+        
394
+        $status_id = $param['status_id'] ?: $businessInfo['status_id'];
395
+        $statusInfo = db('crm_business_status')->where(['type_id' => $businessInfo['type_id'], 'status_id' => $status_id])->find();
390 396
         if (!$statusInfo && !$is_end) {
391 397
             return resultArray(['error' => '参数错误']);
392 398
         }
@@ -409,69 +415,72 @@ class Business extends ApiCommon
409 415
             if (empty($businessStatusName) && $is_end == 3) $businessStatusName = '无效';
410 416
             # 添加活动记录
411 417
             Db::name('crm_activity')->insert([
412
-                'type'             => 3,
413
-                'activity_type'    => 5,
418
+                'type' => 3,
419
+                'activity_type' => 5,
414 420
                 'activity_type_id' => $businessInfo['business_id'],
415
-                'content'          => '阶段变更为  ' . $businessStatusName,
416
-                'create_user_id'   => $businessInfo['owner_user_id'],
417
-                'update_time'      => time(),
418
-                'create_time'      => time(),
419
-                'customer_ids'     => ',' . $businessInfo['customer_id'] . ','
421
+                'content' => '阶段变更为  ' . $businessStatusName,
422
+                'create_user_id' => $businessInfo['owner_user_id'],
423
+                'update_time' => time(),
424
+                'create_time' => time(),
425
+                'customer_ids' => ',' . $businessInfo['customer_id'] . ','
420 426
             ]);
421
-
422
-			//推进记录添加
423
-            $temp['status_id'] = $status_id ? : 0;
424
-			$temp['is_end'] = $is_end ? : 0;
425
-			$temp['business_id'] = $param['business_id'];
426
-			$temp['create_time'] = time();
427
+            
428
+            //推进记录添加
429
+            $temp['status_id'] = $status_id ?: 0;
430
+            $temp['is_end'] = $is_end ?: 0;
431
+            $temp['business_id'] = $param['business_id'];
432
+            $temp['create_time'] = time();
427 433
             $temp['owner_user_id'] = $userInfo['id'];
428
-			$temp['remark'] = $param['remark'] ? : '';
429
-			Db::name('CrmBusinessLog')->insert($temp);
430
-
431
-			# 返回商机阶段数据
432
-			$typeId = db('crm_business')->where('business_id', $param['business_id'])->value('type_id');
433
-			$businessStatus = db('crm_business_status')->where('type_id', $typeId)->select();
434
-			$result = [
435
-			    'business_id' => $param['business_id'],
436
-                'type_id'     => $typeId,
437
-                'status_id'   => $param['status_id'],
434
+            $temp['remark'] = $param['statusRemark'] ?: '';
435
+            Db::name('CrmBusinessLog')->insert($temp);
436
+            
437
+            # 返回商机阶段数据
438
+            $typeId = db('crm_business')->where('business_id', $param['business_id'])->value('type_id');
439
+            $businessStatus = db('crm_business_status')->where('type_id', $typeId)->select();
440
+            $result = [
441
+                'business_id' => $param['business_id'],
442
+                'type_id' => $typeId,
443
+                'status_id' => $param['status_id'],
438 444
                 'status_list' => $businessStatus
439 445
             ];
440
-
446
+            
441 447
             return resultArray(['data' => $result]);
442 448
         }
443 449
     }
444 450
     
445 451
     /**
446 452
      * 商机导出
447
-     * @author Michael_xu
448
-     * @param 
453
+     * @param
449 454
      * @return
455
+     * @author Michael_xu
450 456
      */
451 457
     public function excelExport()
452 458
     {
453 459
         $param = $this->param;
454 460
         $userInfo = $this->userInfo;
455 461
         $param['user_id'] = $userInfo['id'];
462
+        $action_name = '导出全部';
456 463
         if ($param['business_id']) {
457
-           $param['business_id'] = ['condition' => 'in','value' => $param['business_id'],'form_type' => 'text','name' => ''];
458
-           $param['is_excel'] = 1;
459
-        }        
460
-
464
+            $param['business_id'] = ['condition' => 'in', 'value' => $param['business_id'], 'form_type' => 'text', 'name' => ''];
465
+            $param['is_excel'] = 1;
466
+            $action_name = '导出选中';
467
+        }
468
+        
461 469
         $excelModel = new \app\admin\model\Excel();
462 470
         // 导出的字段列表
463 471
         $fieldModel = new \app\admin\model\Field();
464 472
         $field_list = $fieldModel->getIndexFieldConfig('crm_business', $userInfo['id']);
465 473
         // 文件名
466
-        $file_name = '5kcrm_business_'.date('Ymd');
467
-
474
+        $file_name = '5kcrm_business_' . date('Ymd');
475
+        
468 476
         $model = model('Business');
469 477
         $temp_file = $param['temp_file'];
470 478
         unset($param['temp_file']);
471 479
         $page = $param['page'] ?: 1;
472 480
         unset($param['page']);
473 481
         unset($param['export_queue_index']);
474
-        return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
482
+        RecordActionLog($userInfo['id'], 'crm_customer', 'excelexport', $action_name, '', '', '导出商机');
483
+        return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
475 484
             $param['page'] = $page;
476 485
             $param['limit'] = $limit;
477 486
             $data = $model->getDataList($param);
@@ -479,7 +488,7 @@ class Business extends ApiCommon
479 488
             return $data;
480 489
         });
481 490
     }
482
-
491
+    
483 492
     /**
484 493
      * 设置关注
485 494
      *
@@ -489,19 +498,19 @@ class Business extends ApiCommon
489 498
      */
490 499
     public function star()
491 500
     {
492
-        $userId   = $this->userInfo['id'];
501
+        $userId = $this->userInfo['id'];
493 502
         $targetId = $this->param['target_id'];
494
-        $type     = $this->param['type'];
495
-
503
+        $type = $this->param['type'];
504
+        
496 505
         if (empty($userId) || empty($targetId) || empty($type)) return resultArray(['error' => '缺少必要参数!']);
497
-
506
+        
498 507
         if (!$this->setStar($type, $userId, $targetId)) {
499 508
             return resultArray(['error' => '设置关注失败!']);
500 509
         }
501
-
510
+        
502 511
         return resultArray(['data' => '设置关注成功!']);
503 512
     }
504
-
513
+    
505 514
     /**
506 515
      * 系统信息
507 516
      *
@@ -513,14 +522,14 @@ class Business extends ApiCommon
513 522
     public function system()
514 523
     {
515 524
         if (empty($this->param['id'])) return resultArray(['error' => '参数错误!']);
516
-
525
+        
517 526
         $businessModel = new \app\crm\model\Business();
518
-
527
+        
519 528
         $data = $businessModel->getSystemInfo($this->param['id']);
520
-
529
+        
521 530
         return resultArray(['data' => $data]);
522 531
     }
523
-
532
+    
524 533
     /**
525 534
      * table栏数量统计
526 535
      *
@@ -532,50 +541,50 @@ class Business extends ApiCommon
532 541
     public function count()
533 542
     {
534 543
         if (empty($this->param['business_id'])) return resultArray(['error' => '参数错误!']);
535
-
544
+        
536 545
         $businessId = $this->param['business_id'];
537
-
546
+        
538 547
         $userInfo = $this->userInfo;
539
-
548
+        
540 549
         # 查询联系人和商机关联数据
541 550
         $contactsIds = Db::name('crm_contacts_business')->where('business_id', $businessId)->column('contacts_id');
542
-
551
+        
543 552
         # 联系人
544 553
         $contactsAuth = $this->getContactsSearchWhere($userInfo['id']);
545 554
         $contactsCount = Db::name('crm_contacts')->whereIn('contacts_id', $contactsIds)->where($contactsAuth)->count();
546
-
555
+        
547 556
         # 合同
548 557
         $contractAuth = $this->getContractSearchWhere($userInfo['id']);
549 558
         $contractCount = Db::name('crm_contract')->where('business_id', $businessId)->where($contractAuth)->count();
550
-
559
+        
551 560
         # 查询商机和产品的关联表
552 561
         $productIds = Db::name('crm_business_product')->where('business_id', $businessId)->column('product_id');
553
-
562
+        
554 563
         # 产品
555 564
         $productAuth = $this->getProductSearchWhere();
556 565
         $productCount = Db::name('crm_product')->whereIn('product_id', $productIds)->whereIn('owner_user_id', $productAuth)->count();
557
-
566
+        
558 567
         # 附件
559 568
         $fileCount = Db::name('crm_business_file')->alias('business')->join('__ADMIN_FILE__ file', 'file.file_id = business.file_id', 'LEFT')->where('business_id', $businessId)->count();
560
-
569
+        
561 570
         # 团队
562 571
         $business = Db::name('crm_business')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('business_id', $businessId)->find();
563
-        $business['ro_user_id']    = explode(',', trim($business['ro_user_id'], ','));
564
-        $business['rw_user_id']    = explode(',', trim($business['rw_user_id'], ','));
572
+        $business['ro_user_id'] = explode(',', trim($business['ro_user_id'], ','));
573
+        $business['rw_user_id'] = explode(',', trim($business['rw_user_id'], ','));
565 574
         $business['owner_user_id'] = [$business['owner_user_id']];
566 575
         $teamCount = array_filter(array_unique(array_merge($business['ro_user_id'], $business['rw_user_id'], $business['owner_user_id'])));
567
-
576
+        
568 577
         $data = [
569
-            'contactCount'  => $contactsCount,
578
+            'contactCount' => $contactsCount,
570 579
             'contractCount' => $contractCount,
571
-            'fileCount'     => $fileCount,
572
-            'memberCount'   => count($teamCount),
573
-            'productCount'  => $productCount
580
+            'fileCount' => $fileCount,
581
+            'memberCount' => count($teamCount),
582
+            'productCount' => $productCount
574 583
         ];
575
-
584
+        
576 585
         return resultArray(['data' => $data]);
577 586
     }
578
-
587
+    
579 588
     /**
580 589
      * 设置首要联系人
581 590
      *
@@ -587,13 +596,13 @@ class Business extends ApiCommon
587 596
     {
588 597
         $businessId = $this->param['business_id'];
589 598
         $contactsId = $this->param['contacts_id'];
590
-
599
+        
591 600
         if (empty($businessId) || empty($contactsId)) return resultArray(['error' => '参数错误!']);
592
-
601
+        
593 602
         if (!Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $contactsId])) {
594 603
             return resultArray(['error' => '操作失败!']);
595 604
         }
596
-
605
+        
597 606
         return resultArray(['data' => '操作成功!']);
598 607
     }
599 608
 }

+ 9
- 0
application/crm/controller/BusinessStatus.php Zobrazit soubor

@@ -126,11 +126,20 @@ class BusinessStatus extends ApiCommon
126 126
     {
127 127
         $businessStatusModel = model('BusinessStatus');
128 128
         $param = $this->param;
129
+        $userInfo=$this->userInfo;
129 130
         if ($param['id'] == 1) {
130 131
            return resultArray(['error' => '系统数据,不能操作']); 
131 132
         }
132 133
         $status = $param['status'] ? : '0';
133 134
         if (db('crm_business_type')->where(['type_id' => $param['id']])->setField('status', $status)) {
135
+            $data=db('crm_business_type')->where(['type_id' => $param['id']])->find();
136
+            if($status==0){
137
+                $status='停用了商机组:'.$data['name'];
138
+            }else{
139
+                $status='启用了商机组:'.$data['name'];
140
+            }
141
+            # 系统操作日志
142
+            SystemActionLog($userInfo['id'], 'crm_business_type','customer', $param['id'],  'update',$data['name'] , '', '',$status);
134 143
             return resultArray(['data' => '操作成功']);
135 144
         } else {
136 145
             return resultArray(['error' => $businessStatusModel->getError()]);

+ 44
- 6
application/crm/controller/Contacts.php Zobrazit soubor

@@ -185,8 +185,12 @@ class Contacts extends ApiCommon
185 185
             //删除关联附件
186 186
             $fileModel->delRFileByModule('crm_contacts',$delIds);
187 187
             //删除关联操作记录
188
-            $actionRecordModel->delDataById(['types'=>'crm_contacts','action_id'=>$delIds]);            
189
-            actionLog($delIds,'','',''); 
188
+            $actionRecordModel->delDataById(['types'=>'crm_contacts','action_id'=>$delIds]);
189
+            $userInfo = $this->userInfo;
190
+            foreach ($contacts_id as $k => $v) {
191
+                $data = $contactsModel->getDataById($v);
192
+                RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $data['name'], '', '', '删除了联系人:' . $data['name']);
193
+            }
190 194
         }        
191 195
         if ($errorMessage) {
192 196
             return resultArray(['error' => $errorMessage]);
@@ -247,8 +251,10 @@ class Contacts extends ApiCommon
247 251
                 $errorMessage[] = $contactsInfo['name'].'"转移失败,错误原因:数据出错;';
248 252
                 continue;
249 253
             }
250
-			updateActionLog($userInfo['id'], 'crm_contacts', $contacts_id, '', '', '将联系人转移给:' . $owner_user_info['realname']);			
254
+			updateActionLog($userInfo['id'], 'crm_contacts', $contacts_id, '', '', '将联系人转移给:' . $owner_user_info['realname']);
255
+            RecordActionLog($userInfo['id'], 'crm_contacts', 'transfer',$contactsInfo['name'], '','','将联系人:'.$contactsInfo['name'].'转移给:' . $owner_user_info['realname']);
251 256
         }
257
+        
252 258
         if (!$errorMessage) {
253 259
             return resultArray(['data' => '转移成功']);
254 260
         } else {
@@ -267,13 +273,41 @@ class Contacts extends ApiCommon
267 273
         $param = $this->param;
268 274
         $userInfo = $this->userInfo;
269 275
         $excelModel = new \app\admin\model\Excel();
270
-
276
+    
271 277
         // 导出的字段列表
272 278
         $fieldModel = new \app\admin\model\Field();
273
-        $fieldParam['types'] = 'crm_contacts'; 
274
-        $fieldParam['action'] = 'excel'; 
279
+        $fieldParam['types'] = 'crm_contacts';
280
+        $fieldParam['action'] = 'excel';
275 281
         $field_list = $fieldModel->field($fieldParam);
276 282
         $res = $excelModel->excelImportDownload($field_list, 'crm_contacts', $save_path);
283
+        # 下次升级
284
+//        $param = $this->param;
285
+//        $userInfo = $this->userInfo;
286
+//        $excelModel = new \app\admin\model\Excel();
287
+//
288
+//        // 导出的字段列表
289
+//        $fieldModel = new \app\admin\model\Field();
290
+//        $fieldParam['types'] = 'crm_contacts';
291
+//        $fieldParam['action'] = 'excel';
292
+//        $field_list = $fieldModel->field($fieldParam);
293
+//        $array=[];
294
+//        $field=[1=>[
295
+//            'field'=>'owner_user_id',
296
+//            'types'=>'crm_contacts',
297
+//            'name'=>'负责人',
298
+//            'form_type'=>'user',
299
+//            'default_value'=>'',
300
+//            'is_unique' => 1,
301
+//            'is_null' => 1,
302
+//            'input_tips' =>'',
303
+//            'setting' => Array(),
304
+//            'is_hidden'=>0,
305
+//            'writeStatus' => 1,
306
+//            'value' => '']
307
+//        ];
308
+//        $first_array = array_splice($field_list, 0, 2);
309
+//        $array = array_merge($first_array, $field, $field_list);
310
+//        $res = $excelModel->excelImportDownload($array, 'crm_contacts', $save_path);
277 311
     }  
278 312
 
279 313
     /**
@@ -287,9 +321,11 @@ class Contacts extends ApiCommon
287 321
         $param = $this->param;
288 322
         $userInfo = $this->userInfo;
289 323
         $param['user_id'] = $userInfo['id'];
324
+        $action_name='导出全部';
290 325
         if ($param['contacts_id']) {
291 326
            $param['contacts_id'] = ['condition' => 'in','value' => $param['contacts_id'],'form_type' => 'text','name' => ''];
292 327
            $param['is_excel'] = 1;
328
+            $action_name='导出选中';
293 329
         }        
294 330
 
295 331
         $excelModel = new \app\admin\model\Excel();
@@ -305,6 +341,7 @@ class Contacts extends ApiCommon
305 341
         $page = $param['page'] ?: 1;
306 342
         unset($param['page']);
307 343
         unset($param['export_queue_index']);
344
+        RecordActionLog($userInfo['id'],'crm_contracts','excelexport',$action_name,'','','导出联系人');
308 345
         return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
309 346
             $param['page'] = $page;
310 347
             $param['limit'] = $limit;
@@ -334,6 +371,7 @@ class Contacts extends ApiCommon
334 371
 //        if (!$res) {
335 372
 //            return resultArray(['error'=>$excelModel->getError()]);
336 373
 //        }
374
+        RecordActionLog($userInfo['id'],'crm_contacts','excel','导入联系人','','','导入联系人');
337 375
         return resultArray(['data' => $excelModel->getError()]);
338 376
     }  
339 377
 

+ 12
- 3
application/crm/controller/Contract.php Zobrazit soubor

@@ -143,7 +143,7 @@ class Contract extends ApiCommon
143 143
         $receivablesModel = new \app\crm\model\Receivables();
144 144
         $param = $this->param;
145 145
         $userInfo = $this->userInfo;
146
-        $data = $contractModel->getDataById($param['id']);
146
+        $data = $contractModel->getDataById($param['id'], $userInfo['id']);
147 147
         //判断权限
148 148
         $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'read');
149 149
         //读权限
@@ -324,6 +324,7 @@ class Contract extends ApiCommon
324 324
                 $delIds[] = $v;
325 325
             }             
326 326
         }
327
+        $dataInfo = $contractModel->where('contract_id',['in',$delIds])->select();
327 328
         if ($delIds) {
328 329
             $data = $contractModel->delDatas($delIds);
329 330
             if (!$data) {
@@ -337,7 +338,10 @@ class Contract extends ApiCommon
337 338
             $actionRecordModel->delDataById(['types'=>'crm_contract','action_id'=>$delIds]);
338 339
             // 删除回款记录
339 340
             \app\crm\model\ReceivablesPlan::where(['contract_id' => ['IN', $delIds]])->delete();
340
-            actionLog($delIds,'','','');
341
+            $userInfo = $this->userInfo;
342
+            foreach ($dataInfo as $k => $v) {
343
+                RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['name'], '', '', '删除了合同:' . $v['name']);
344
+            }
341 345
         }
342 346
         if ($errorMessage) {
343 347
             return resultArray(['error' => $errorMessage]);
@@ -425,7 +429,9 @@ class Contract extends ApiCommon
425 429
             }
426 430
 
427 431
             //修改记录
428
-            updateActionLog($userInfo['id'], 'crm_contract', $contract_id, '', '', '将合同转移给:'.$ownerUserName);        
432
+            updateActionLog($userInfo['id'], 'crm_contract', $contract_id, '', '', '将合同转移给:'.$ownerUserName);
433
+            RecordActionLog($userInfo['id'], 'crm_contract', 'transfer',$contractInfo['name'], '','','将合同:'.$contractInfo['name'].'转移给:' . $ownerUserName);
434
+    
429 435
         }
430 436
         if (!$errorMessage) {
431 437
             return resultArray(['data' => '转移成功']);
@@ -676,9 +682,11 @@ class Contract extends ApiCommon
676 682
         $param = $this->param;
677 683
         $userInfo = $this->userInfo;
678 684
         $param['user_id'] = $userInfo['id'];
685
+        $action_name = '导出全部';
679 686
         if ($param['contract_id']) {
680 687
            $param['contract_id'] = ['condition' => 'in','value' => $param['contract_id'],'form_type' => 'text','name' => ''];
681 688
            $param['is_excel'] = 1;
689
+            $action_name='导出选中';
682 690
         }
683 691
         $excelModel = new \app\admin\model\Excel();
684 692
         // 导出的字段列表
@@ -693,6 +701,7 @@ class Contract extends ApiCommon
693 701
         $page = $param['page'] ?: 1;
694 702
         unset($param['page']);
695 703
         unset($param['export_queue_index']);
704
+        RecordActionLog($userInfo['id'],'crm_contract','excelexport',$action_name,'','','导出合同');
696 705
         return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
697 706
             $param['page'] = $page;
698 707
             $param['limit'] = $limit;

+ 219
- 37
application/crm/controller/Customer.php Zobrazit soubor

@@ -29,7 +29,7 @@ class Customer extends ApiCommon
29 29
     {
30 30
         $action = [
31 31
             'permission' => ['exceldownload', 'setfollow', 'delete'],
32
-            'allow' => ['read', 'system', 'count', 'poolauthority']
32
+            'allow' => ['read', 'system', 'count', 'poolauthority', 'level']
33 33
         ];
34 34
         Hook::listen('check_auth', $action);
35 35
         $request = Request::instance();
@@ -156,6 +156,8 @@ class Customer extends ApiCommon
156 156
     public function delete()
157 157
     {
158 158
         $param = $this->param;
159
+        $user=new ApiCommon();
160
+        $userInfo = $user->userInfo;
159 161
         // 是否客户池
160 162
         if ($param['isSeas'] == 1) {
161 163
             $permission = checkPerByAction('crm', 'customer', 'poolDelete');
@@ -227,6 +229,7 @@ class Customer extends ApiCommon
227 229
                 $delIds[] = $v;
228 230
             }
229 231
         }
232
+        $dataInfo = $customerModel->where('customer_id',['in',$delIds])->select();
230 233
         if ($delIds) {
231 234
             $delRes = $customerModel->delDatas($delIds);
232 235
             if (!$delRes) {
@@ -238,7 +241,9 @@ class Customer extends ApiCommon
238 241
             $fileModel->delRFileByModule('crm_customer', $delIds);
239 242
             //删除关联操作记录
240 243
             $actionRecordModel->delDataById(['types' => 'crm_customer', 'action_id' => $delIds]);
241
-            actionLog($delIds, '', '', '');
244
+            foreach ($dataInfo as $k => $v) {
245
+                RecordActionLog($userInfo['id'], 'crm_customer', 'delete', $v['name'], '', '', '删除了客户:' . $v['name']);
246
+            }
242 247
         }
243 248
         if ($errorMessage) {
244 249
             return resultArray(['error' => $errorMessage]);
@@ -374,6 +379,7 @@ class Customer extends ApiCommon
374 379
             }
375 380
             //修改记录
376 381
             updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户转移给:' . $ownerUserName);
382
+            RecordActionLog($userInfo['id'], 'crm_customer', 'transfer',$customerInfo['name'], '','','将客户:'.$customerInfo['name'].'转移给:' . $ownerUserName);
377 383
         }
378 384
         if (!$errorMessage) {
379 385
             return resultArray(['data' => '转移成功']);
@@ -390,48 +396,160 @@ class Customer extends ApiCommon
390 396
      */
391 397
     public function putInPool()
392 398
     {
393
-        $param = $this->param;
399
+        if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要放入公海的客户!']);
400
+        if (!is_array($this->param['customer_id'])) return resultArray(['error' => '客户ID格式不正确!']);
401
+        if (empty($this->param['pool_id'])) return resultArray(['error' => '请选择公海!']);
402
+
394 403
         $userInfo = $this->userInfo;
395
-        $customerModel = model('Customer');
396
-        $settingModel = new \app\crm\model\Setting();
397
-        if (!$param['customer_id'] || !is_array($param['customer_id'])) {
398
-            return resultArray(['error' => '请选择需要放入公海的客户']);
404
+        $userId = $userInfo['id'];
405
+        $customerIds = $this->param['customer_id'];
406
+        $poolId = $this->param['pool_id'];
407
+
408
+        # 消息数据
409
+        $message = [];
410
+
411
+        # 获取客户数据
412
+        $customerData = [];
413
+        $customerList = db('crm_customer')->field(['customer_id', 'owner_user_id', 'name'])->whereIn('customer_id', $customerIds)->select();
414
+        foreach ($customerList AS $key => $value) {
415
+            $customerData[$value['customer_id']] = $value;
399 416
         }
400
-        $data = [];
401
-        $data['owner_user_id'] = 0;
402
-        $data['is_lock'] = 0;
403
-        $data['update_time'] = time();
404
-        $errorMessage = [];
405
-        foreach ($param['customer_id'] as $customer_id) {
406
-            $customerInfo = [];
407
-            $customerInfo = db('crm_customer')->where(['customer_id' => $customer_id])->find();
408
-            if (!$customerInfo) {
409
-                $errorMessage[] = '名称:为《' . $customerInfo['name'] . '》的客户放入公海失败,错误原因:数据不存在;';
410
-                continue;
411
-            }
412
-            //权限判断
413
-            if (!$customerModel->checkData($customer_id)) {
414
-                $errorMessage[] = '"' . $customerInfo['name'] . '"放入公海失败,错误原因:无权限';
417
+
418
+        # 整理数据
419
+        $ip = request()->ip();
420
+        $poolRelationData = [];
421
+        $poolRecordData = [];
422
+        $fieldRecordData = [];
423
+        $operationLogData = [];
424
+        foreach ($customerIds AS $key => $value)
425
+        {
426
+            if (empty($customerData[$value])) {
427
+                $message[] = '将客户放入公海失败,错误原因:数据不存在!';
428
+                unset($customerIds[(int)$key]);
429
+
415 430
                 continue;
416 431
             }
417
-            //将团队成员全部清除
418
-            $data['ro_user_id'] = '';
419
-            $data['rw_user_id'] = '';
420
-            $resCustomer = db('crm_customer')->where(['customer_id' => $customer_id])->update($data);
421
-            if (!$resCustomer) {
422
-                $errorMessage[] = '"' . $customerInfo['name'] . '"放入公海失败,错误原因:数据出错;';
432
+
433
+            if (isset($customerData[$value]['owner_user_id']) && empty($customerData[$value]['owner_user_id'])) {
434
+                $message[] = '将客户《' . $customerData[$value]['name'] . '》放入公海失败,错误原因:已经处于公海!';
435
+                unset($customerIds[(int)$key]);
436
+
423 437
                 continue;
424 438
             }
425
-            //联系人负责人清除
426
-            db('crm_contacts')->where(['customer_id' => $customer_id])->update(['owner_user_id' => 0]);
427
-            //修改记录
428
-            updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户放入公海');
439
+
440
+            # 公海关联数据
441
+            $poolRelationData[] = [
442
+                'pool_id' => $poolId,
443
+                'customer_id' => $value
444
+            ];
445
+            # 公海操作记录数据
446
+            $poolRecordData[] = [
447
+                'customer_id' => $value,
448
+                'user_id' => $userId,
449
+                'pool_id' => $poolId,
450
+                'type' => 2,
451
+                'create_time' => time()
452
+            ];
453
+            # 字段操作记录数据
454
+            $fieldRecordData[] = [
455
+                'user_id'     => $userId,
456
+                'types'       => 'crm_customer',
457
+                'action_id'   => $value,
458
+                'content'     => '将客户放入公海',
459
+                'create_time' => time()
460
+            ];
461
+            # 数据操作日志数据
462
+            $operationLogData[] = [
463
+                'user_id'     => $userId,
464
+                'client_ip'   => $ip,
465
+                'module'      => 'crm_customer',
466
+                'action_id'   => $value,
467
+                'content'     => '将客户放入公海',
468
+                'create_time' => time(),
469
+                'action_name' => 'update',
470
+                'target_name' => !empty($customerData[$value]['name']) ? $customerData[$value]['name'] : ''
471
+            ];
429 472
         }
430
-        if (!$errorMessage) {
431
-            return resultArray(['data' => '操作成功']);
432
-        } else {
433
-            return resultArray(['error' => $errorMessage]);
473
+
474
+        if (empty($customerIds)) return resultArray(['error' => $message]);
475
+
476
+        Db::startTrans();
477
+        try {
478
+            # 修改客户数据
479
+            Db::name('crm_customer')->whereIn('customer_id', $customerIds)->exp('before_owner_user_id', 'owner_user_id')->update([
480
+                'ro_user_id' => '',
481
+                'rw_user_id' => '',
482
+                'owner_user_id' => 0,
483
+                'into_pool_time' => time()
484
+            ]);
485
+
486
+            # 删除联系人的负责人
487
+            Db::name('crm_contacts')->whereIn('customer_id', $customerIds)->update(['owner_user_id' => 0]);
488
+
489
+            # 将客户放入公海
490
+            Db::name('crm_customer_pool_relation')->insertAll($poolRelationData);
491
+
492
+            # 公海操作记录
493
+            Db::name('crm_customer_pool_record')->insertAll($poolRecordData);
494
+
495
+            # 字段操作记录
496
+            Db::name('admin_action_record')->insertAll($fieldRecordData);
497
+
498
+            # 数据操作日志
499
+            Db::name('admin_operation_log')->insertAll($operationLogData);
500
+
501
+            Db::commit();
502
+        } catch (\Exception $e) {
503
+            Db::rollback();
504
+
505
+            $message = ['操作失败!'];
434 506
         }
507
+
508
+        return resultArray(!empty($message) ? ['error' => $message] : ['data' => '操作成功!']);
509
+
510
+//        $param = $this->param;
511
+//        $userInfo = $this->userInfo;
512
+//        $customerModel = model('Customer');
513
+//        $settingModel = new \app\crm\model\Setting();
514
+//        if (!$param['customer_id'] || !is_array($param['customer_id'])) {
515
+//            return resultArray(['error' => '请选择需要放入公海的客户']);
516
+//        }
517
+//        $data = [];
518
+//        $data['owner_user_id'] = 0;
519
+//        $data['is_lock'] = 0;
520
+//        $data['update_time'] = time();
521
+//        $errorMessage = [];
522
+//        foreach ($param['customer_id'] as $customer_id) {
523
+//            $customerInfo = [];
524
+//            $customerInfo = db('crm_customer')->where(['customer_id' => $customer_id])->find();
525
+//            if (!$customerInfo) {
526
+//                $errorMessage[] = '名称:为《' . $customerInfo['name'] . '》的客户放入公海失败,错误原因:数据不存在;';
527
+//                continue;
528
+//            }
529
+//            //权限判断
530
+//            if (!$customerModel->checkData($customer_id)) {
531
+//                $errorMessage[] = '"' . $customerInfo['name'] . '"放入公海失败,错误原因:无权限';
532
+//                continue;
533
+//            }
534
+//            //将团队成员全部清除
535
+//            $data['ro_user_id'] = '';
536
+//            $data['rw_user_id'] = '';
537
+//            $resCustomer = db('crm_customer')->where(['customer_id' => $customer_id])->update($data);
538
+//            if (!$resCustomer) {
539
+//                $errorMessage[] = '"' . $customerInfo['name'] . '"放入公海失败,错误原因:数据出错;';
540
+//                continue;
541
+//            }
542
+//            //联系人负责人清除
543
+//            db('crm_contacts')->where(['customer_id' => $customer_id])->update(['owner_user_id' => 0]);
544
+//            //修改记录
545
+//            updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户放入公海');
546
+//            RecordActionLog($userInfo['id'],'crm_pool','pool',$customerInfo['name'],'','','将客户'.$customerInfo['name'].'放入公海');
547
+//        }
548
+//        if (!$errorMessage) {
549
+//            return resultArray(['data' => '操作成功']);
550
+//        } else {
551
+//            return resultArray(['error' => $errorMessage]);
552
+//        }
435 553
     }
436 554
     
437 555
     /**
@@ -483,6 +601,11 @@ class Customer extends ApiCommon
483 601
             }
484 602
             //修改记录
485 603
             updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户' . $lock_name);
604
+            if($is_lock == 2){
605
+                RecordActionLog($userInfo['id'], 'crm_customer', 'islock',$customerInfo['name'], '','','将客户'.$customerInfo['name'].$lock_name );
606
+            }else{
607
+                RecordActionLog($userInfo['id'], 'crm_customer', 'lock',$customerInfo['name'], '','','将客户'.$customerInfo['name'].$lock_name );
608
+            }
486 609
         }
487 610
         if (!$errorMessage) {
488 611
             return resultArray(['data' => '操作成功']);
@@ -542,6 +665,7 @@ class Customer extends ApiCommon
542 665
             db('crm_contacts')->where(['customer_id' => $v])->update(['owner_user_id' => $userInfo['id']]);
543 666
             //修改记录
544 667
             updateActionLog($userInfo['id'], 'crm_customer', $v, '', '', '领取了客户');
668
+            RecordActionLog($userInfo['id'], 'crm_customer', 'update',$dataName, '','','领取了客户:'.$dataName);
545 669
         }
546 670
         if (!$errorMessage) {
547 671
             return resultArray(['data' => '领取成功']);
@@ -599,6 +723,8 @@ class Customer extends ApiCommon
599 723
             $data['rw_user_id'] = '';
600 724
             # 处理分配标识,待办事项专用
601 725
             $data['is_allocation'] = 1;
726
+            # 获取客户的时间
727
+            $data['obtain_time'] = time();
602 728
             $resCustomer = db('crm_customer')->where(['customer_id' => $v])->update($data);
603 729
             if (!$resCustomer) {
604 730
                 $errorMessage[] = '客户《' . $dataName . '》分配失败,错误原因:数据出错;';
@@ -606,6 +732,7 @@ class Customer extends ApiCommon
606 732
             db('crm_contacts')->where(['customer_id' => $v])->update(['owner_user_id' => $owner_user_id]);
607 733
             //修改记录
608 734
             updateActionLog($userInfo['id'], 'crm_customer', $v, '', '', '将客户分配给:' . $ownerUserName);
735
+            RecordActionLog($userInfo['id'], 'crm_customer', 'distribute',$dataName, '','','将客户'.$dataName.'分配给:' . $ownerUserName);
609 736
             //站内信
610 737
             $send_user_id[] = $owner_user_id;
611 738
             $sendContent = $userInfo['realname'] . '将客户《' . $dataName . '》,分配给您';
@@ -631,8 +758,10 @@ class Customer extends ApiCommon
631 758
         $param = $this->param;
632 759
         $userInfo = $this->userInfo;
633 760
         $param['user_id'] = $userInfo['id'];
761
+        $action_name='导出全部';
634 762
         if ($param['customer_id']) {
635 763
             $param['customer_id'] = ['condition' => 'in', 'value' => $param['customer_id'], 'form_type' => 'text', 'name' => ''];
764
+            $action_name='导出选中';
636 765
         }
637 766
         $param['is_excel'] = 1;
638 767
         $excelModel = new \app\admin\model\Excel();
@@ -648,6 +777,7 @@ class Customer extends ApiCommon
648 777
         $page = $param['page'] ?: 1;
649 778
         unset($param['page']);
650 779
         unset($param['export_queue_index']);
780
+        RecordActionLog($userInfo['id'],'crm_customer','excelexport',$action_name,'','','导出客户');
651 781
         return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
652 782
             $param['page'] = $page;
653 783
             $param['limit'] = $limit;
@@ -655,6 +785,7 @@ class Customer extends ApiCommon
655 785
             $data['list'] = $model->exportHandle($data['list'], $field_list, 'customer');
656 786
             return $data;
657 787
         });
788
+       
658 789
     }
659 790
     
660 791
     /**
@@ -668,13 +799,40 @@ class Customer extends ApiCommon
668 799
         $param = $this->param;
669 800
         $userInfo = $this->userInfo;
670 801
         $excelModel = new \app\admin\model\Excel();
671
-        
802
+    
672 803
         // 导入的字段列表
673 804
         $fieldModel = new \app\admin\model\Field();
674 805
         $fieldParam['types'] = 'crm_customer';
675 806
         $fieldParam['action'] = 'excel';
676 807
         $field_list = $fieldModel->field($fieldParam);
677 808
         $excelModel->excelImportDownload($field_list, 'crm_customer', $save_path);
809
+        # 下次升级
810
+//        $param = $this->param;
811
+//        $userInfo = $this->userInfo;
812
+//        $excelModel = new \app\admin\model\Excel();
813
+//
814
+//        // 导入的字段列表
815
+//        $fieldModel = new \app\admin\model\Field();
816
+//        $fieldParam['types'] = 'crm_customer';
817
+//        $fieldParam['action'] = 'excel';
818
+//        $field_list = $fieldModel->field($fieldParam);
819
+//        $field=[1=>[
820
+//           'field'=>'owner_user_id',
821
+//           'types'=>'crm_customer',
822
+//           'name'=>'负责人',
823
+//           'form_type'=>'user',
824
+//           'default_value'=>'',
825
+//           'is_unique' => 1,
826
+//           'is_null' => 1,
827
+//           'input_tips' =>'',
828
+//           'setting' => Array(),
829
+//            'is_hidden'=>0,
830
+//            'writeStatus' => 1,
831
+//            'value' => '']
832
+//        ];
833
+//        $first_array = array_splice($field_list, 2,0, $field);
834
+//        $array = array_merge($first_array, $field, $field_list);
835
+//        $excelModel->excelImportDownload($field_list, 'crm_customer', $save_path);
678 836
     }
679 837
     
680 838
     
@@ -697,6 +855,7 @@ class Customer extends ApiCommon
697 855
         $file = request()->file('file');
698 856
         // $res = $excelModel->importExcel($file, $param, $this);
699 857
         $res = $excelModel->batchImportData($file, $param, $this);
858
+        RecordActionLog($userInfo['id'],'crm_customer','excel','导入客户','','','导入客户');
700 859
         return resultArray(['data' => $excelModel->getError()]);
701 860
     }
702 861
     
@@ -762,6 +921,7 @@ class Customer extends ApiCommon
762 921
         $param['user_id'] = $userInfo['id'];
763 922
         if ($param['customer_id']) {
764 923
             $param['customer_id'] = ['condition' => 'in', 'value' => $param['customer_id'], 'form_type' => 'text', 'name' => ''];
924
+            $action_name='导出选中';
765 925
         }
766 926
         $param['is_excel'] = 1;
767 927
         $excelModel = new \app\admin\model\Excel();
@@ -781,6 +941,7 @@ class Customer extends ApiCommon
781 941
         $page = $param['page'] ?: 1;
782 942
         unset($param['page']);
783 943
         unset($param['export_queue_index']);
944
+        RecordActionLog($userInfo['id'],'crm_customer','excelexport',$action_name,'','','导出客户');
784 945
         return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param) {
785 946
             $param['page'] = $page;
786 947
             $param['limit'] = $limit;
@@ -847,6 +1008,11 @@ class Customer extends ApiCommon
847 1008
             }
848 1009
             //修改记录
849 1010
             updateActionLog($userInfo['id'], 'crm_customer', $customer_id, ['deal_status' => $dataInfo['deal_status']], ['deal_status' => $data['deal_status']]);
1011
+            if($param['status']==1){
1012
+                RecordActionLog($userInfo['id'], 'crm_customer', 'status',$dataInfo['name'], '','','修改客户:'.$dataInfo['name'].'成交状态:'.$statusArr[$param['status']]);
1013
+            }else{
1014
+                RecordActionLog($userInfo['id'], 'crm_customer', 'status',$dataInfo['name'], '','','修改客户:'.$dataInfo['name'].'成交状态:'.$statusArr[$param['status']]);
1015
+            }
850 1016
         }
851 1017
         if (!$errorMessage) {
852 1018
             return resultArray(['data' => '操作成功']);
@@ -1031,4 +1197,20 @@ class Customer extends ApiCommon
1031 1197
         
1032 1198
         return resultArray(['data' => $authority]);
1033 1199
     }
1200
+
1201
+    /**
1202
+     * 客户级别列表
1203
+     *
1204
+     * @author fanqi
1205
+     * @since 2021-03-29
1206
+     * @return \think\response\Json
1207
+     */
1208
+    public function level()
1209
+    {
1210
+        $data = db('admin_field')->where(['types' => 'crm_customer', 'field' => 'level'])->value('setting');
1211
+
1212
+        $data = explode(chr(10), $data);
1213
+
1214
+        return resultArray(['data' => $data]);
1215
+    }
1034 1216
 }

+ 364
- 0
application/crm/controller/CustomerPool.php Zobrazit soubor

@@ -0,0 +1,364 @@
1
+<?php
2
+/**
3
+ * 客户公海
4
+ *
5
+ * @author fanqi
6
+ * @since 2021-04-13
7
+ */
8
+
9
+namespace app\crm\controller;
10
+
11
+use app\admin\controller\ApiCommon;
12
+use app\crm\logic\CustomerPoolLogic;
13
+use think\Hook;
14
+use think\Request;
15
+use think\response\Json;
16
+
17
+class CustomerPool extends ApiCommon
18
+{
19
+    /**
20
+     * 用于判断权限
21
+     * @permission 无限制
22
+     * @allow 登录用户可访问
23
+     * @other 其他根据系统设置
24
+     **/
25
+    public function _initialize()
26
+    {
27
+        $action = [
28
+            'permission' => [],
29
+            'allow' => [
30
+                'index',
31
+                'read',
32
+                'pondlist',
33
+                'field',
34
+                'advanced',
35
+                'authority',
36
+                'receive',
37
+                'distribute',
38
+                'delete',
39
+                'fieldconfig',
40
+                'setfieldwidth',
41
+                'setfieldconfig',
42
+                'exceldownload',
43
+                'import',
44
+                'export'
45
+            ]
46
+        ];
47
+        Hook::listen('check_auth',$action);
48
+        $request = Request::instance();
49
+        $a = strtolower($request->action());
50
+        if (!in_array($a, $action['permission'])) {
51
+            parent::_initialize();
52
+        }
53
+    }
54
+
55
+    /**
56
+     * 公海列表
57
+     *
58
+     * @author fanqi
59
+     * @since 2021-04-14
60
+     * @return Json
61
+     */
62
+    public function index()
63
+    {
64
+        if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
65
+
66
+        $data = (new CustomerPoolLogic())->getPoolList($this->param);
67
+
68
+        return resultArray(['data' => $data]);
69
+    }
70
+
71
+    /**
72
+     * 详情
73
+     *
74
+     * @author fanqi
75
+     * @since 2021-04-14
76
+     * @return Json
77
+     */
78
+    public function read()
79
+    {
80
+        if (empty($this->param['pool_id']) || empty($this->param['customer_id'])) return resultArray(['error' => '参数错误!']);
81
+
82
+        $userInfo = $this->userInfo;
83
+        $param = $this->param;
84
+        $param['user_id'] = $userInfo['id'];
85
+
86
+        $data = (new CustomerPoolLogic())->getPoolData($param);
87
+
88
+        return resultArray(['data' => $data]);
89
+    }
90
+
91
+    /**
92
+     * 删除公海客户
93
+     *
94
+     * @author fanqi
95
+     * @since 2021-04-15
96
+     * @return Json
97
+     */
98
+    public function delete()
99
+    {
100
+        if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的客户!']);
101
+
102
+        $this->param['user_id'] = $this->userInfo['id'];
103
+
104
+        $result = (new CustomerPoolLogic())->deletePoolCustomer($this->param);
105
+
106
+        if (!empty($result)) return resultArray(['error' => $result]);
107
+
108
+        return resultArray(['data' => '删除成功!']);
109
+    }
110
+
111
+    /**
112
+     * 公海池列表
113
+     *
114
+     * @author fanqi
115
+     * @since 2021-04-13
116
+     * @return Json
117
+     */
118
+    public function pondList()
119
+    {
120
+        $data = (new CustomerPoolLogic())->getPondList(['user_id' => $this->userInfo['id'], 'structure_id' => $this->userInfo['structure_id']]);
121
+
122
+        return resultArray(['data' => $data]);
123
+    }
124
+
125
+    /**
126
+     * 公海字段
127
+     *
128
+     * @author fanqi
129
+     * @since 2021-04-13
130
+     * @return Json
131
+     */
132
+    public function field()
133
+    {
134
+        if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
135
+
136
+        $userInfo = $this->userInfo;
137
+        $param = $this->param;
138
+        $param['user_id'] = $userInfo['id'];
139
+
140
+        $data = (new CustomerPoolLogic())->getFieldList($param);
141
+
142
+        return resultArray(['data' => $data]);
143
+    }
144
+
145
+    /**
146
+     * 高级筛选字段列表
147
+     *
148
+     * @author fanqi
149
+     * @since 2021-04-14
150
+     * @return Json
151
+     */
152
+    public function advanced()
153
+    {
154
+        if (empty($this->param['types'])) return resultArray(['error' => '缺少模块类型!']);
155
+
156
+        $data = (new CustomerPoolLogic())->getAdvancedFilterFieldList($this->param);
157
+
158
+        return resultArray(['data' => $data]);
159
+    }
160
+
161
+    /**
162
+     * 领取公海池客户
163
+     *
164
+     * @author fanqi
165
+     * @since 2021-04-15
166
+     * @return Json
167
+     */
168
+    public function receive()
169
+    {
170
+        if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要领取的公海客户!']);
171
+
172
+        $param = $this->param;
173
+        $param['user_id'] = $this->userInfo['id'];
174
+
175
+        $result = (new CustomerPoolLogic())->receiveCustomers($param);
176
+
177
+        if (!empty($result)) return resultArray(['error' => $result]);
178
+
179
+        return resultArray(['data' => '领取成功!']);
180
+    }
181
+
182
+    /**
183
+     * 分配公海客户
184
+     *
185
+     * @author fanqi
186
+     * @since 2021-04-15
187
+     * @return Json
188
+     */
189
+    public function distribute()
190
+    {
191
+        if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要分配的公海客户!']);
192
+        if (empty($this->param['user_id'])) return resultArray(['error' => '请选择要分配的员工!']);
193
+
194
+        $result = (new CustomerPoolLogic())->distributeCustomer($this->param);
195
+
196
+        if (!empty($result)) return resultArray(['error' => $result]);
197
+
198
+        return resultArray(['data' => '分配成功!']);
199
+    }
200
+
201
+    // 公海客户导入模板下载
202
+    public function excelDownload($save_path='')
203
+    {
204
+        $excelModel = new \app\admin\model\Excel();
205
+        $param=$this->param;
206
+        $field_list=$this->fieldsData($param);
207
+        $excelModel->excelImportDownload($field_list, 'crm_customer', $save_path);
208
+    }
209
+
210
+    // 导入
211
+    public function import()
212
+    {
213
+        $param = $this->param;
214
+        $userInfo = $this->userInfo;
215
+        $excelModel = new \app\admin\model\Excel();
216
+        $param['create_user_id'] = $userInfo['id'];
217
+        $param['owner_user_id'] = $userInfo['id'];
218
+        $param['deal_time'] = time();
219
+        $param['types'] = 'crm_customer';
220
+        $file = request()->file('file');
221
+        // $res = $excelModel->importExcel($file, $param, $this);
222
+        $res = $excelModel->batchImportData($file, $param, $this);
223
+        RecordActionLog($userInfo['id'],'crm_customer','excel','导入公海客户','','','导入公海客户');
224
+        return resultArray(['data' => $excelModel->getError()]);
225
+    }
226
+
227
+    // 导出
228
+    public function export()
229
+    {
230
+        $param = $this->param;
231
+        $userInfo = $this->userInfo;
232
+        $action_name='导出全部';
233
+        if ($param['customer_id']) {
234
+            $action_name='导出选中';
235
+        }
236
+        $param['is_excel'] = 1;
237
+        $excelModel = new \app\admin\model\Excel();
238
+        // 导出的字段列表
239
+        $fieldModel = new \app\admin\model\Field();
240
+        $field_list=$this->fieldsData($param);
241
+        $field=[
242
+            1=>[
243
+            'field'=>'before_owner_user_name',
244
+            'types'=>'crm_customer',
245
+            'name'=>'前负责人',
246
+            ],
247
+            2=>[
248
+                'field'=>'into_pool_time',
249
+                'types'=>'crm_customer',
250
+                'name'=>'进入公海时间',
251
+            ]
252
+        ];
253
+        $field_list=array_merge($field_list,$field);
254
+        // 文件名
255
+        $file_name = '5kcrm_customer_' . date('Ymd');
256
+        $model = model('Customer');
257
+        $temp_file = $param['temp_file'];
258
+        unset($param['temp_file']);
259
+        $page = $param['page'] ?: 1;
260
+        unset($param['page']);
261
+        unset($param['export_queue_index']);
262
+      
263
+        return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
264
+            $param['page'] = $page;
265
+            $param['limit'] = $limit;
266
+            $data = (new CustomerPoolLogic())->getPoolList($param);
267
+            $data['list'] = $model->exportHandle($data['list'], $field_list, 'customer');
268
+            return $data;
269
+        });
270
+        RecordActionLog($userInfo['id'],'crm_customer','excelexport',$action_name,'','','导出客户');
271
+        return resultArray(['error' => 'error']);
272
+    }
273
+
274
+    /**
275
+     * 公海权限
276
+     *
277
+     * @author fanqi
278
+     * @since 2021-04-14
279
+     * @return Json
280
+     */
281
+    public function authority()
282
+    {
283
+        $param = $this->param;
284
+        $param['user_id'] = $this->userInfo['id'];
285
+        $param['structure_id'] = $this->userInfo['structure_id'];
286
+
287
+        $data = (new CustomerPoolLogic())->getAuthorityData($param);
288
+
289
+        return resultArray(['data' => $data]);
290
+    }
291
+
292
+    /**
293
+     * 公海字段样式
294
+     *
295
+     * @author fanqi
296
+     * @since 2021-04-22
297
+     * @return Json
298
+     */
299
+    public function fieldConfig()
300
+    {
301
+        if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
302
+
303
+        $param = $this->param;
304
+        $userInfo = $this->userInfo;
305
+        $param['user_id'] = $userInfo['id'];
306
+
307
+        $data = (new CustomerPoolLogic())->getFieldConfigIndex($param);
308
+
309
+        return resultArray(['data' => $data]);
310
+    }
311
+
312
+    /**
313
+     * 设置公海字段宽度
314
+     *
315
+     * @author fanqi
316
+     * @since 2021-04-22
317
+     * @return Json
318
+     */
319
+    public function setFieldWidth()
320
+    {
321
+        if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
322
+        if (empty($this->param['field'])) return resultArray(['error' => '缺少字段名称!']);
323
+        if (empty($this->param['width'])) return resultArray(['error' => '缺少宽度值!']);
324
+
325
+        $param = $this->param;
326
+        $userInfo = $this->userInfo;
327
+        $param['user_id'] = $userInfo['id'];
328
+
329
+        (new CustomerPoolLogic())->setFieldWidth($param);
330
+
331
+        return resultArray(['data' => '操作成功!']);
332
+    }
333
+
334
+    /**
335
+     * 设置公海字段样式
336
+     *
337
+     * @author fanqi
338
+     * @since 2021-04-22
339
+     * @return Json
340
+     */
341
+    public function setFieldConfig()
342
+    {
343
+        if (empty($this->param['pool_id'])) return resultArray(['缺少公海ID!']);
344
+        if (empty($this->param['value']) && empty($this->param['hide_value'])) return resultArray(['error' => '字段参数错误!']);
345
+
346
+        $param = $this->param;
347
+        $userInfo = $this->userInfo;
348
+        $param['user_id'] = $userInfo['id'];
349
+
350
+        (new CustomerPoolLogic())->setFieldConfig($param);
351
+
352
+        return resultArray(['data' => '操作成功!']);
353
+    }
354
+    public function fieldsData($param){
355
+        $pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select();
356
+        $fieldModel = new \app\admin\model\Field();
357
+        $fieldParam['types'] = 'crm_customer';
358
+        $fieldParam['action'] = 'excel';
359
+        $merge_list = $fieldModel->field($fieldParam);
360
+        $field_list=array_intersect($merge_list,$pool_list);
361
+        return $field_list;
362
+        
363
+    }
364
+}

+ 3
- 0
application/crm/controller/Index.php Zobrazit soubor

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

+ 22
- 11
application/crm/controller/Invoice.php Zobrazit soubor

@@ -153,6 +153,7 @@ class Invoice extends ApiCommon
153 153
         # 更新crm_number_sequence表中的last_date、create_time字段
154 154
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
155 155
         updateActionLog($param['create_user_id'], 'crm_invoice', $invoice_id, '', '', '创建了发票');
156
+        RecordActionLog($param['create_user_id'],'crm_invoice','save',$param['invoice_apple_number'],'','','新增了发票'.$param['invoice_apple_number']);
156 157
 
157 158
         # 创建待办事项的关联数据
158 159
         $checkUserIds = db('crm_invoice')->where('invoice_id', $invoice_id)->value('check_user_id');
@@ -229,8 +230,8 @@ class Invoice extends ApiCommon
229 230
         if (empty($param['invoice_type']))         return resultArray(['error' => '请选择开票类型!']);
230 231
         if (empty($param['title_type']))           return resultArray(['error' => '请选择抬头类型!']);
231 232
         if (empty($param['examineStatus']))        return resultArray(['error' => '缺少审批状态!']);
232
-        $userId = $this->userInfo['id']; 
233
-
233
+        $userId = $this->userInfo['id'];
234
+        $dataInfo = $this->get($param['invoice_id']);
234 235
         # 审批是否停用
235 236
         $examineStatus = $param['examineStatus'];
236 237
         # 删除无用参数
@@ -320,8 +321,8 @@ class Invoice extends ApiCommon
320 321
         # 更新crm_number_sequence表中的last_date、create_time字段
321 322
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
322 323
         //修改记录
323
-        // updateActionLog($param['user_id'], 'crm_invoice', $param['invoice_id'], $dataInfo, $param);
324
-
324
+        updateActionLog($param['user_id'], 'crm_invoice', $param['invoice_id'], $dataInfo, $param);
325
+        RecordActionLog($param['user_id'], 'crm_invoice', 'update',$dataInfo['invoice_apple_number'], $dataInfo, $param);
325 326
         # 删除待办事项的关联数据
326 327
         db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'types_id' => ['eq', $param['invoice_id']]])->delete();
327 328
         # 创建待办事项的关联数据
@@ -372,14 +373,17 @@ class Invoice extends ApiCommon
372 373
         }
373 374
 
374 375
         if (!$status) return resultArray(['error' => '不能删除审批中或审批结束的发票信息!']);
375
-
376
+        $dataInfo=db('crm_invoice')->where('invoice_id',['in',$idArray])->select();
376 377
         if (!$invoiceLogic->delete($idArray)) return resultArray(['error' => '删除失败!']);
377 378
 
378 379
         # 删除附件
379 380
         $fileModel->delRFileByModule('crm_invoice', $idArray);
380 381
         //删除关联操作记录
381 382
         $actionRecordModel->delDataById(['types'=>'crm_invoice','action_id'=>$idArray]);
382
-
383
+        $userInfo = $this->userInfo;
384
+        foreach ($dataInfo as $k => $v) {
385
+            RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['invoice_apple_number'], '', '', '删除了回款:' . $v['invoice_apple_number']);
386
+        }
383 387
         return resultArray(['data' => '删除成功!']);
384 388
     }
385 389
 
@@ -393,13 +397,19 @@ class Invoice extends ApiCommon
393 397
     {
394 398
         $ownerUserId = $this->param['owner_user_id'];
395 399
         $invoiceIds  = $this->param['invoice_id'];
396
-
400
+        $userModel = new \app\admin\model\User();
401
+        $userInfo=$this->userInfo;
397 402
         if (empty($ownerUserId))    return resultArray(['error' => '请选择负责人!']);
398 403
         if (empty($invoiceIds))     return resultArray(['error' => '请选择发票!']);
399 404
         if (!is_array($invoiceIds)) return resultArray(['error' => '发票ID类型错误!']);
400 405
 
401 406
         if ($invoiceLogic->transfer($invoiceIds, $ownerUserId) === false) return resultArray(['error' => '操作失败!']);
402
-
407
+        $owner_user_info = $userModel->getUserById($ownerUserId);
408
+        foreach ($invoiceIds as $v){
409
+            $invoice_info=db('crm_invoice')->where('invoice_id',$v)->find();
410
+            updateActionLog($userInfo['id'], 'crm_invoice', $v, '', '', '将发票转移给:' . $owner_user_info['realname']);
411
+            RecordActionLog($userInfo['id'], 'crm_invoice', 'transfer',$invoice_info['invoice_apple_number'], '','','将发票:'.$invoice_info['invoice_apple_number'].'转移给:' . $owner_user_info['realname']);
412
+        }
403 413
         return resultArray(['data' => '操作成功!']);
404 414
     }
405 415
 
@@ -628,14 +638,15 @@ class Invoice extends ApiCommon
628 638
     public function resetInvoiceStatus(InvoiceLogic $invoiceLogic)
629 639
     {
630 640
         if (empty($this->param['invoice_id'])) resultArray(['error' => '参数错误!']);
631
-
641
+        $userInfo = $this->userInfo;
632 642
         $this->param['real_invoice_date'] = !empty($this->param['real_invoice_date']) ? $this->param['real_invoice_date'] : date('Y-m-d');
633 643
 
634 644
         # 开票状态
635 645
         $this->param['invoice_status'] = 1;
636
-
646
+        $invoice_info=db('crm_invoice')->where('invoice_id',$this->param['invoice_id'])->find();
637 647
         if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']);
638
-
648
+        RecordActionLog($userInfo['id'], 'crm_invoice', 'update',$invoice_info['invoice_apple_number'], '','','将发票:'.$invoice_info['invoice_apple_number'].'重置开票状态');
639 649
         return resultArray(['data' => '操作成功!']);
650
+
640 651
     }
641 652
 }

+ 41
- 3
application/crm/controller/Leads.php Zobrazit soubor

@@ -175,6 +175,7 @@ class Leads extends ApiCommon
175 175
                 $delIds[] = $v;
176 176
             }            
177 177
         }
178
+        $dataInfo = $leadsModel->where('leads_id',['in',$delIds])->select();
178 179
         if ($delIds) {
179 180
             $data = $leadsModel->delDatas($delIds);
180 181
             if (!$data) {
@@ -186,7 +187,10 @@ class Leads extends ApiCommon
186 187
             $fileModel->delRFileByModule('crm_leads', $delIds);
187 188
             //删除关联操作记录
188 189
             $actionRecordModel->delDataById(['types' => 'crm_leads', 'action_id' => $delIds]);
189
-            actionLog($delIds, '', '', '');
190
+            $userInfo = $this->userInfo;
191
+            foreach ($dataInfo as $k => $v) {
192
+                RecordActionLog($userInfo['id'], 'crm_leads', 'delete', $v['name'], '', '', '删除了线索:' . $v['name']);
193
+            }
190 194
         }
191 195
         if ($errorMessage) {
192 196
             return resultArray(['error' => $errorMessage]);
@@ -250,6 +254,7 @@ class Leads extends ApiCommon
250 254
             db('crm_leads')->where(['leads_id' => $leads_id])->update($leadsData);
251 255
             //修改记录
252 256
             updateActionLog($userInfo['id'], 'crm_customer', $resCustomer['customer_id'], '', '', '将线索"' . $leadsInfo['name'] . '转化为客户');
257
+            RecordActionLog($userInfo['id'],'crm_leads','save',$leadsInfo['name'],'','','将线索'.$leadsInfo['name'].'转化为客户');
253 258
             # 将线索下的跟进记录同步至客户下
254 259
             $record = db('crm_activity')->field('activity_id', true)->where(['type' => 1, 'activity_type' => 1, 'activity_type_id' => $leads_id])->select();
255 260
             foreach ($record as $key1 => $value1) {
@@ -323,6 +328,8 @@ class Leads extends ApiCommon
323 328
             }
324 329
             //修改记录
325 330
             updateActionLog($userInfo['id'], 'crm_leads', $leads_id, '', '', '将线索转移给:' . $ownerUserName);
331
+            RecordActionLog($userInfo['id'], 'crm_leads', 'transfer',$leadsInfo['name'], '','','将线索:'.$leadsInfo['name'].'转移给:' . $ownerUserName);
332
+    
326 333
         }
327 334
         if (!$errorMessage) {
328 335
             return resultArray(['data' => '转移成功']);
@@ -339,7 +346,7 @@ class Leads extends ApiCommon
339 346
      */
340 347
     public function excelDownload($save_path = '')
341 348
     {
342
-
349
+    
343 350
         $param = $this->param;
344 351
         $userInfo = $this->userInfo;
345 352
         $excelModel = new \app\admin\model\Excel();
@@ -350,6 +357,33 @@ class Leads extends ApiCommon
350 357
         $field_list = $fieldModel->field($fieldParam);
351 358
         // $field_list = $fieldModel->getIndexFieldList('crm_leads', $userInfo['id']);
352 359
         $data = $excelModel->excelImportDownload($field_list, 'crm_leads', $save_path);
360
+        
361
+        # 下次升级使用
362
+//        $param = $this->param;
363
+//        $userInfo = $this->userInfo;
364
+//        $excelModel = new \app\admin\model\Excel();
365
+//        // 导出的字段列表
366
+//        $fieldModel = new \app\admin\model\Field();
367
+//        $fieldParam['types'] = 'crm_leads';
368
+//        $fieldParam['action'] = 'excel';
369
+//        $field_list = $fieldModel->field($fieldParam);
370
+//        $field=[1=>[
371
+//            'field'=>'owner_user_id',
372
+//            'types'=>'crm_leads',
373
+//            'name'=>'负责人',
374
+//            'form_type'=>'user',
375
+//            'default_value'=>'',
376
+//            'is_unique' => 1,
377
+//            'is_null' => 1,
378
+//            'input_tips' =>'',
379
+//            'setting' => Array(),
380
+//            'is_hidden'=>0,
381
+//            'writeStatus' => 1,
382
+//            'value' => '']
383
+//        ];
384
+//        $first_array = array_splice($field_list, 0, 2);
385
+//        $array = array_merge($first_array, $field, $field_list);
386
+//        $data = $excelModel->excelImportDownload($array, 'crm_leads', $save_path);
353 387
 
354 388
         return resultArray(['data' => $data]);
355 389
     }
@@ -365,9 +399,11 @@ class Leads extends ApiCommon
365 399
         $param = $this->param;
366 400
         $userInfo = $this->userInfo;
367 401
         $param['user_id'] = $userInfo['id'];
402
+        $action_name='导出全部';
368 403
         if ($param['leads_id']) {
369 404
             $param['leads_id'] = ['condition' => 'in', 'value' => $param['leads_id'], 'form_type' => 'text', 'name' => ''];
370 405
             $param['is_excel'] = 1;
406
+            $action_name='导出选中';
371 407
         }
372 408
 
373 409
         $excelModel = new \app\admin\model\Excel();
@@ -383,6 +419,7 @@ class Leads extends ApiCommon
383 419
         $page = $param['page'] ?: 1;
384 420
         unset($param['page']);
385 421
         unset($param['export_queue_index']);
422
+        RecordActionLog($userInfo['id'],'crm_leads','excelexport',$action_name,'','','导出线索');
386 423
         return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $field_list, $param) {
387 424
             $param['page'] = $page;
388 425
             $param['limit'] = $limit;
@@ -405,13 +442,14 @@ class Leads extends ApiCommon
405 442
         $excelModel = new \app\admin\model\Excel();
406 443
         $param['types'] = 'crm_leads';
407 444
         $param['create_user_id'] = $userInfo['id'];
408
-        $param['owner_user_id'] = $param['owner_user_id'] ?: $userInfo['id'];
409 445
         $file = request()->file('file');
410 446
         // $res = $excelModel->importExcel($file, $param);
411 447
         $res = $excelModel->batchImportData($file, $param, $this);
412 448
         if (!$res) {
413 449
             return resultArray(['error' => $excelModel->getError()]);
414 450
         }
451
+        RecordActionLog($userInfo['id'],'crm_leads','excel','导入线索','','','导入线索');
452
+    
415 453
         return resultArray(['data' => $excelModel->getError()]);
416 454
     }
417 455
 

+ 150
- 0
application/crm/controller/Market.php Zobrazit soubor

@@ -0,0 +1,150 @@
1
+<?php
2
+namespace app\crm\controller;
3
+
4
+use app\admin\controller\ApiCommon;
5
+use think\Hook;
6
+use think\Request;
7
+use app\crm\logic\MarketLogic;
8
+
9
+class Market extends ApiCommon{
10
+    /**
11
+     * 用于判断权限
12
+     * @permission 无限制
13
+     * @allow 登录用户可访问
14
+     * @other 其他根据系统设置
15
+     **/
16
+    public function _initialize()
17
+    {
18
+        $action = [
19
+            'permission'=>['exceldownload'],
20
+            'allow'=>['index','save','read','update','marketlist']
21
+        ];
22
+        Hook::listen('check_auth',$action);
23
+        $request = Request::instance();
24
+        $a = strtolower($request->action());
25
+        if (!in_array($a, $action['permission'])) {
26
+            parent::_initialize();
27
+        }
28
+    }
29
+    
30
+    /**
31
+     * 市场活动列表
32
+     * @author      alvin guogaobo
33
+     * @version     1.0 版本号
34
+     * @since       2021/4/26 0026 17:15
35
+     */
36
+    public function index(){
37
+        $marketLogic=new MarketLogic;
38
+        $param=$this->param;
39
+        $userInfo = $this->userInfo;
40
+        $param['user_id'] = $userInfo['id'];
41
+        $data = $marketLogic->getDataList($param);
42
+        return resultArray(['data' => $data]);
43
+    }
44
+    
45
+    /**
46
+     * 关联对象列表
47
+     * @author      alvin guogaobo
48
+     * @version     1.0 版本号
49
+     * @since       2021/4/26 0026 17:14
50
+     */
51
+    public function marketList(){
52
+        $marketLogic=new MarketLogic;
53
+        $data = $marketLogic->marketList();
54
+        return resultArray(['data' => $data]);
55
+    }
56
+    public function save(){
57
+        $marketLogic=new MarketLogic;
58
+        $param = $this->param;
59
+        $userInfo = $this->userInfo;
60
+        $param['create_user_id'] = $userInfo['id'];
61
+        # 检查活动图片
62
+        if (!empty($param['cover_images']) && count(explode(',', $param['cover_images'])) > 9) {
63
+            return resultArray(['error' => '最多只能上次9张产品图片!']);
64
+        }
65
+    
66
+        # 检查活动详情图片
67
+        if (!empty($param['details_images']) && count(explode(',', $param['details_images'])) > 9) {
68
+            return resultArray(['error' => '最多只能上次9张产品详情图片!']);
69
+        }
70
+    
71
+        if ($marketLogic->createData($param)) {
72
+            return resultArray(['data' => '添加成功']);
73
+        } else {
74
+            return resultArray(['error' => '添加失败']);
75
+        }
76
+    }
77
+    public function update(){
78
+        $marketLogic=new MarketLogic;
79
+        $param = $this->param;
80
+        $userInfo = $this->userInfo;
81
+        $param['user_id'] = $userInfo['id'];
82
+    
83
+        # 检查产品图片
84
+        if (!empty($param['cover_images']) && count(explode(',', $param['cover_images'])) > 9) {
85
+            return resultArray(['error' => '最多只能上次9张产品图片!']);
86
+        }
87
+    
88
+        # 检查产品详情图片
89
+        if (!empty($param['details_images']) && count(explode(',', $param['details_images'])) > 9) {
90
+            return resultArray(['error' => '最多只能上次9张产品详情图片!']);
91
+        }
92
+    
93
+        if ($marketLogic->updateDataById($param, $param['id'])) {
94
+            return resultArray(['data' => '编辑成功']);
95
+        } else {
96
+            return resultArray(['error' => '编辑失败']);
97
+        }
98
+    }
99
+    public function read()
100
+    {
101
+        $marketLogic=new MarketLogic;
102
+        $userModel = new \app\admin\model\User();
103
+        $param = $this->param;
104
+        $userInfo = $this->userInfo;
105
+        $data = $marketLogic->getDataById($param['id'], $userInfo['id']);
106
+        //判断权限
107
+        $auth_user_ids = $userModel->getUserByPer('crm', 'Market', 'read');
108
+        if (!in_array($data['owner_user_id'], $auth_user_ids)) {
109
+            //无权限
110
+            $authData['dataAuth'] = (int)0;
111
+            return resultArray(['data' => $authData]);
112
+        }
113
+        if (!$data) {
114
+            return resultArray(['error' => $marketLogic->getError()]);
115
+        }
116
+        return resultArray(['data' => $data]);
117
+    }
118
+    public function delete(){
119
+        $marketLogic=new MarketLogic;
120
+        $userInfo = $this->userInfo;
121
+        $id_list = (array) $this->param['id'];
122
+        $id_list['user_id']=$userInfo['id'];
123
+        $id_list = array_map('intval', $id_list);
124
+        $data=$marketLogic->delete($id_list);
125
+        if($data){
126
+            return resultArray(['data' => '删除成功']);
127
+        }else{
128
+            return resultArray(['error' => '删除失败']);
129
+        }
130
+    }
131
+    public function enables(){
132
+        $marketModel = model('Market');
133
+        $param = $this->param;
134
+        $userInfo=$this->userInfo;
135
+        $id = [$param['flow_id']];
136
+        $data = $marketModel->enableDatas($id, $param['status']);
137
+        # 系统操作日志
138
+        if (!$data) {
139
+            return resultArray(['error' => $marketModel->getError()]);
140
+        }
141
+        if($param['status']==0){
142
+            $content='禁用了:';
143
+        }else{
144
+            $content='启用了:';
145
+        }
146
+        $dataInfo=db('admin_examine_flow')->where('flow_id',$param['flow_id'])->find();
147
+        SystemActionLog($userInfo['id'], 'admin_examine','approval', $param['flow_id'], 'update', $dataInfo['name'], '', '',$content.$dataInfo['name']);
148
+        return resultArray(['data' => '操作成功']);
149
+    }
150
+}

+ 32
- 34
application/crm/controller/Message.php Zobrazit soubor

@@ -207,14 +207,15 @@ class Message extends ApiCommon
207 207
             }
208 208
         }
209 209
         # 待进入公海提醒
210
-        if ($configData['remind_config'] == 1) {
210
+        $pool = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
211
+        if (!empty($pool)) {
211 212
             $remindCustomerTime  = cache('remindCustomerTime'.$userInfo['id']);
212 213
             $remindCustomerCount = cache('remindCustomerCount'.$userInfo['id']);
213 214
             if (time() <= $remindCustomerTime) {
214 215
                 $data['putInPoolRemind'] = (int)$remindCustomerCount;
215 216
             } else {
216 217
                 $remindCustomer = $this->remindCustomer(true);
217
-                $data['putInPoolRemind'] = $remindCustomer['dataCount'] ? : 0;
218
+                $data['putInPoolRemind'] = !empty($remindCustomer['dataCount']) ? $remindCustomer['dataCount'] : 0;
218 219
                 cache('remindCustomerCount'.$userInfo['id'], $data['putInPoolRemind']);
219 220
                 cache('remindCustomerTime'.$userInfo['id'], time() + 180);
220 221
             }
@@ -661,7 +662,7 @@ class Message extends ApiCommon
661 662
     }  
662 663
 
663 664
     /**
664
-     * 待进入客户池(默认5天)
665
+     * 待进入客户池
665 666
      * @author Michael_xu
666 667
      * @return 
667 668
      */
@@ -684,16 +685,19 @@ class Message extends ApiCommon
684 685
         $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userInfo['id'])] : $userInfo['id'];
685 686
 
686 687
         # 是否提醒
687
-        $remind = db('crm_config')->where('name', 'remind_config')->value('value');
688
-
689
-        $whereData              = $param ? : [];
690
-        $whereData['is_remind'] = !empty($remind) ? 1 : 0;
691
-        $whereData['user_id']   = $userInfo['id'];
692
-        $whereData['scene_id']  = db('admin_scene')->where(['types' => 'crm_customer','bydata' => 'me'])->value('scene_id');
693
-        if ($isSub) {
694
-            $whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => 'sub'])->value('scene_id');
688
+        $data = [];
689
+        $remind = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
690
+        if (!empty($remind)) {
691
+            $whereData = $param ? : [];
692
+            $whereData['is_remind'] = 1;
693
+            $whereData['user_id'] = $userInfo['id'];
694
+            $whereData['pool_remain'] = 0;
695
+            $whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => 'me'])->value('scene_id');
696
+            if ($isSub) {
697
+                $whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => 'sub'])->value('scene_id');
698
+            }
699
+            $data = $customerModel->getDataList($whereData);
695 700
         }
696
-        $data = $customerModel->getDataList($whereData);
697 701
         if ($types == 'list') {
698 702
             return resultArray(['data' => $data]);
699 703
         }
@@ -859,30 +863,24 @@ class Message extends ApiCommon
859 863
         # 处理待进入公海
860 864
         if ($type == 'putInPoolRemind') {
861 865
             if (!empty($typeId)) {
862
-                Db::name('crm_customer')->whereIn('customer_id', $typeId)->update([
863
-                    'follow'      => '已跟进',
864
-                    'last_time'   => time(),
865
-                    'deal_time'   => time(),
866
-                    'update_time' => time(),
867
-                ]);
866
+                Db::name('crm_customer')->whereIn('customer_id', $typeId)->update(['pool_remain' => 1]);
868 867
             } else {
869
-                $whereData['page']      = 1;
870
-                $whereData['limit']     = 100;
871
-                $whereData['is_remind'] = db('crm_config')->where('name', 'remind_config')->value('value');;
872
-                $whereData['user_id']   = $userId;
873
-                $whereData['scene_id']  = db('admin_scene')->where(['types' => 'crm_customer','bydata' => empty($isSub) ? 'me' : 'sub'])->value('scene_id');
874
-                $whereData['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userId)] : $userId;
875
-                $poolCustomers = (new \app\crm\model\Customer())->getDataList($whereData);
876
-                $ids = [];
877
-                foreach ($poolCustomers['list'] AS $key => $value) {
878
-                    if (!empty($value['customer_id'])) $ids[] = $value['customer_id'];
868
+                $poolConfig = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
869
+                if (!empty($poolConfig)) {
870
+                    $whereData['page'] = 1;
871
+                    $whereData['limit'] = 100;
872
+                    $whereData['is_remind'] = 1;
873
+                    $whereData['user_id'] = $userId;
874
+                    $whereData['pool_remain'] = 0;
875
+                    $whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => empty($isSub) ? 'me' : 'sub'])->value('scene_id');
876
+                    $whereData['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userId)] : $userId;
877
+                    $poolCustomers = (new \app\crm\model\Customer())->getDataList($whereData);
878
+                    $ids = [];
879
+                    foreach ($poolCustomers['list'] AS $key => $value) {
880
+                        if (!empty($value['customer_id'])) $ids[] = $value['customer_id'];
881
+                    }
882
+                    if (!empty($ids)) Db::name('crm_customer')->whereIn('customer_id', $ids)->update(['pool_remain' => 1]);
879 883
                 }
880
-                if (!empty($ids)) Db::name('crm_customer')->whereIn('customer_id', $ids)->update([
881
-                    'follow'      => '已跟进',
882
-                    'last_time'   => time(),
883
-                    'deal_time'   => time(),
884
-                    'update_time' => time(),
885
-                ]);
886 884
             }
887 885
         }
888 886
 

+ 67
- 0
application/crm/controller/Preview.php Zobrazit soubor

@@ -0,0 +1,67 @@
1
+<?php
2
+
3
+namespace app\crm\controller;
4
+
5
+use think\Controller;
6
+use think\Request;
7
+
8
+class Preview extends Controller
9
+{
10
+    public function previewPdf(Request $request)
11
+    {
12
+        # 处理跨域
13
+//        header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
14
+//        header('Access-Control-Allow-Credentials: true');
15
+//        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
16
+//        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId");
17
+        # 相应类型
18
+        header('Content-Type: application/pdf');
19
+        header('Transfer-Encoding: chunked');
20
+
21
+        $key = $request->param('key');
22
+
23
+        $data = db('admin_printing_data')->field(['type', 'content'])->where('key', $key)->find();
24
+
25
+        $contentArray = json_decode($data['content'], true);
26
+        $content      = $contentArray['data'];
27
+
28
+        require_once(EXTEND_PATH.'tcpdf'.DS.'config'.DS.'tcpdf_config.php');
29
+        require_once(EXTEND_PATH.'tcpdf'.DS.'tcpdf.php');
30
+
31
+        $tcpdf = new \TCPDF();
32
+
33
+        // 设置PDF页面边距:LEFT,TOP,RIGHT
34
+        $tcpdf->SetMargins(10, 10, 10);
35
+
36
+        // 设置字体,防止中文乱码
37
+        $tcpdf->SetFont('simsun', '', 10);
38
+
39
+        // 设置文件信息
40
+//        $tcpdf->SetCreator(TITLE_NAME);
41
+//        $tcpdf->SetAuthor(TITLE_NAME);
42
+        $tcpdf->SetTitle("打印内容预览");
43
+
44
+        // 删除预定义的打印 页眉/页尾
45
+        $tcpdf->setPrintHeader(false);
46
+
47
+        // 设置文档对齐,间距,字体,图片
48
+        $tcpdf->SetCreator(PDF_CREATOR);
49
+        $tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
50
+        $tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
51
+
52
+        // 自动分页
53
+        $tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
54
+        $tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
55
+        $tcpdf->setFontSubsetting(true);
56
+        $tcpdf->setPageMark();
57
+
58
+        $tcpdf->AddPage();
59
+        $html = $content;
60
+        $tcpdf->writeHTML($html, true, false, true, true, '');
61
+        $tcpdf->lastPage();
62
+
63
+        $tcpdf->Output(ROOT_PATH.DS.'public'.DS.'temp'.DS.'pdf'.DS.'print.pdf','I');
64
+
65
+        exit($this->fetch('preview', ['key' => $key]));
66
+    }
67
+}

+ 111
- 11
application/crm/controller/Printing.php Zobrazit soubor

@@ -10,6 +10,10 @@ namespace app\crm\controller;
10 10
 
11 11
 use app\admin\controller\ApiCommon;
12 12
 use app\crm\logic\PrintingLogic;
13
+use PhpOffice\PhpWord\IOFactory;
14
+use PhpOffice\PhpWord\PhpWord;
15
+use PhpOffice\PhpWord\Shared\Html;
16
+use think\Controller;
13 17
 use think\Hook;
14 18
 use think\Request;
15 19
 
@@ -18,8 +22,8 @@ class Printing extends ApiCommon
18 22
     public function _initialize()
19 23
     {
20 24
         $action = [
21
-            'permission'=>[''],
22
-            'allow'=>['printingdata', 'template', 'setrecord', 'getrecord']
25
+            'permission'=>['previewData'],
26
+            'allow'=>['printingdata', 'template', 'setrecord', 'getrecord', 'preview', 'down']
23 27
         ];
24 28
         Hook::listen('check_auth',$action);
25 29
         $request = Request::instance();
@@ -43,12 +47,9 @@ class Printing extends ApiCommon
43 47
         $actionId   = $this->param['action_id'];
44 48
         $templateId = $this->param['template_id'];
45 49
         $type       = $this->param['type'];
50
+        $recordId   = $this->param['record_id'];
46 51
 
47
-        if (empty($actionId))   return resultArray(['error' => '请选择打印的数据!']);
48
-        if (empty($templateId)) return resultArray(['error' => '请选择打印的模板!']);
49
-        if (empty($type))       return resultArray(['error' => '请选择打印的类型!']);
50
-
51
-        $data = $printingLogic->getPrintingData($type, $actionId, $templateId);
52
+        $data = $printingLogic->getPrintingData($type, $actionId, $templateId, $recordId);
52 53
 
53 54
         return resultArray(['data' => $data]);
54 55
     }
@@ -79,9 +80,10 @@ class Printing extends ApiCommon
79 80
      */
80 81
     public function setRecord(PrintingLogic $printingLogic)
81 82
     {
82
-        if (empty($this->param['type']))        return resultArray(['error' => '请选择模块!']);
83
-        if (empty($this->param['action_id']))   return resultArray(['error' => '缺少数据ID!']);
84
-        if (empty($this->param['template_id'])) return resultArray(['error' => '缺少模板ID!']);
83
+        if (empty($this->param['type']))          return resultArray(['error' => '请选择模块!']);
84
+        if (empty($this->param['action_id']))     return resultArray(['error' => '缺少数据ID!']);
85
+        if (empty($this->param['template_id']))   return resultArray(['error' => '缺少模板ID!']);
86
+        if (empty($this->param['recordContent'])) return resultArray(['error' => '缺少打印内容!']);
85 87
 
86 88
         $userId = $this->userInfo['id'];
87 89
 
@@ -101,10 +103,108 @@ class Printing extends ApiCommon
101 103
      */
102 104
     public function getRecord(PrintingLogic $printingLogic)
103 105
     {
104
-        if (empty($this->param['type'])) return resultArray(['error' => '请选择模块!']);
106
+        if (empty($this->param['crmType'])) return resultArray(['error' => '请选择模块!']);
107
+        if (empty($this->param['typeId']))  return resultArray(['error' => '缺少数据ID']);
105 108
 
106 109
         $data = $printingLogic->getRecord($this->param, $this->userInfo['id']);
107 110
 
108 111
         return resultArray(['data' => $data]);
109 112
     }
113
+
114
+    /**
115
+     * 保存打印内容
116
+     *
117
+     * @param user_id 用户id
118
+     * @param type 类型(work,pdf)
119
+     * @param content 打印内容
120
+     * @author fanqi
121
+     * @date 2021-03-25
122
+     * @return \think\response\Json
123
+     */
124
+    public function preview(PrintingLogic $printingLogic)
125
+    {
126
+        if (empty($this->param['type'])) return resultArray(['error' => '缺少类型参数!']);
127
+        if (empty($this->param['content'])) return resultArray(['error' => '缺少打印内容!']);
128
+
129
+        $userInfo = $this->userInfo;
130
+        $this->param['user_id'] = $userInfo['id'];
131
+
132
+        $key = $printingLogic->preview($this->param);
133
+
134
+        return resultArray(['data' => $key]);
135
+    }
136
+
137
+    /**
138
+     * 打下打印文件
139
+     * @param string key 打印数据的唯一key
140
+     * @author fanqi
141
+     * @date 2021-03-26
142
+     * @return \think\response\Json
143
+     */
144
+    public function down()
145
+    {
146
+        if (empty($this->param['key'])) return resultArray(['error' => '参数错误!']);
147
+
148
+        $data = db('admin_printing_data')->field(['type', 'content'])->where('key', $this->param['key'])->find();
149
+
150
+        $type         = $data['type'];
151
+        $contentArray = json_decode($data['content'], true);
152
+        $content      = $contentArray['data'];
153
+
154
+        if ($type == 'pdf') {
155
+            require_once(EXTEND_PATH.'tcpdf'.DS.'config'.DS.'tcpdf_config.php');
156
+            require_once(EXTEND_PATH.'tcpdf'.DS.'tcpdf.php');
157
+
158
+            $tcpdf = new \TCPDF();
159
+
160
+            // 设置PDF页面边距:LEFT,TOP,RIGHT
161
+            $tcpdf->SetMargins(10, 10, 10);
162
+
163
+            // 设置字体,防止中文乱码
164
+            $tcpdf->SetFont('simsun', '', 10);
165
+
166
+            // 设置文件信息
167
+            $tcpdf->SetCreator(TITLE_NAME);
168
+            $tcpdf->SetAuthor(TITLE_NAME);
169
+            $tcpdf->SetTitle("打印文件");
170
+
171
+            // 删除预定义的打印 页眉/页尾
172
+            $tcpdf->setPrintHeader(false);
173
+
174
+            // 设置文档对齐,间距,字体,图片
175
+            $tcpdf->SetCreator(PDF_CREATOR);
176
+            $tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
177
+            $tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
178
+
179
+            // 自动分页
180
+            $tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
181
+            $tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
182
+            $tcpdf->setFontSubsetting(true);
183
+            $tcpdf->setPageMark();
184
+
185
+            $tcpdf->AddPage();
186
+            $html = $content;
187
+            $tcpdf->writeHTML($html, true, false, true, true, '');
188
+            $tcpdf->lastPage();
189
+            $tcpdf->Output('print.PDF','I');
190
+        }
191
+
192
+        if ($type == 'word') {
193
+            $fileName = 'print.docx';
194
+            header("Cache-Control: no-cache, must-revalidate");
195
+            header("Pragma: no-cache");
196
+            header("Content-Type: application/octet-stream");
197
+            header("Content-Disposition: attachment; filename=$fileName");
198
+            header('Transfer-Encoding: chunked');
199
+
200
+            $html = '<html xmlns:v="urn:schemas-microsoft-com:vml" 
201
+            xmlns:o="urn:schemas-microsoft-com:office:office" 
202
+            xmlns:w="urn:schemas-microsoft-com:office:word"  
203
+            xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" 
204
+            xmlns="http://www.w3.org/TR/REC-html40">';
205
+            $html .= '<head><meta charset="UTF-8" /></head>';
206
+
207
+            echo $html . '<body>'.$content .'</body></html>';
208
+        }
209
+    }
110 210
 }

+ 62
- 10
application/crm/controller/Product.php Zobrazit soubor

@@ -94,7 +94,8 @@ class Product extends ApiCommon
94 94
         $productModel = model('Product');
95 95
         $userModel = new \app\admin\model\User();
96 96
         $param = $this->param;
97
-        $data = $productModel->getDataById($param['id']);
97
+        $userInfo = $this->userInfo;
98
+        $data = $productModel->getDataById($param['id'], $userInfo['id']);
98 99
         //判断权限
99 100
         $auth_user_ids = $userModel->getUserByPer('crm', 'product', 'read');
100 101
         if (!in_array($data['owner_user_id'], $auth_user_ids)) {
@@ -151,6 +152,8 @@ class Product extends ApiCommon
151 152
         $data = [];
152 153
         $data['status'] = ($param['status'] == '上架') ? '上架' : '下架'; 
153 154
         $data['update_time'] = time();
155
+        $userModel = new \app\admin\model\User();
156
+        $owner_user_info = $userModel->getUserById($this->param['owner_user_id']);
154 157
         if (!is_array($param['id'])) {
155 158
             $productIds[] = $param['id'];
156 159
         } else {
@@ -163,6 +166,16 @@ class Product extends ApiCommon
163 166
         if (!$res) {
164 167
             return resultArray(['error' => '操作失败']);
165 168
         }
169
+        foreach ($productIds as $v){
170
+            $product_info=db('crm_product')->where('product_id',$v)->find();
171
+           if($param['status'] == '上架'){
172
+               updateActionLog($userInfo['id'], 'crm_product', $v, '', '', '将产品上架');
173
+               RecordActionLog($userInfo['id'], 'crm_product', 'up',$product_info['name'], '','','将产品上架');
174
+            }else{
175
+               updateActionLog($userInfo['id'], 'crm_product', $v, '', '', '将产品下架');
176
+               RecordActionLog($userInfo['id'], 'crm_product', 'down',$product_info['name'], '','','将产品下架');
177
+            }}
178
+        
166 179
         return resultArray(['data' => $data['status'].'成功']);
167 180
     }
168 181
 
@@ -177,13 +190,40 @@ class Product extends ApiCommon
177 190
         $param = $this->param;
178 191
         $userInfo = $this->userInfo;
179 192
         $excelModel = new \app\admin\model\Excel();
180
-
193
+    
181 194
         // 导出的字段列表
182 195
         $fieldModel = new \app\admin\model\Field();
183
-        $fieldParam['types'] = 'crm_product'; 
184
-        $fieldParam['action'] = 'excel'; 
196
+        $fieldParam['types'] = 'crm_product';
197
+        $fieldParam['action'] = 'excel';
185 198
         $field_list = $fieldModel->field($fieldParam);
186 199
         $excelModel->excelImportDownload($field_list, 'crm_product', $save_path);
200
+        # 下次升级
201
+//        $param = $this->param;
202
+//        $userInfo = $this->userInfo;
203
+//        $excelModel = new \app\admin\model\Excel();
204
+//
205
+//        // 导出的字段列表
206
+//        $fieldModel = new \app\admin\model\Field();
207
+//        $fieldParam['types'] = 'crm_product';
208
+//        $fieldParam['action'] = 'excel';
209
+//        $field_list = $fieldModel->field($fieldParam);
210
+//        $field=[1=>[
211
+//            'field'=>'owner_user_id',
212
+//            'types'=>'crm_product',
213
+//            'name'=>'负责人',
214
+//            'form_type'=>'user',
215
+//            'default_value'=>'',
216
+//            'is_unique' => 1,
217
+//            'is_null' => 1,
218
+//            'input_tips' =>'',
219
+//            'setting' => Array(),
220
+//            'is_hidden'=>0,
221
+//            'writeStatus' => 1,
222
+//            'value' => '']
223
+//        ];
224
+//        $first_array = array_splice($field_list, 0, 2);
225
+//        $array = array_merge($first_array, $field, $field_list);
226
+//        $excelModel->excelImportDownload($array, 'crm_product', $save_path);
187 227
     }  
188 228
 
189 229
     /**
@@ -197,8 +237,10 @@ class Product extends ApiCommon
197 237
         $param = $this->param;
198 238
         $userInfo = $this->userInfo;
199 239
         $param['user_id'] = $userInfo['id'];
240
+        $action_name='导出全部';
200 241
         if ($param['product_id']) {
201 242
            $param['product_id'] = ['condition' => 'in','value' => $param['product_id'],'form_type' => 'text','name' => ''];
243
+            $action_name='导出选中';
202 244
         }        
203 245
 
204 246
         $excelModel = new \app\admin\model\Excel();
@@ -214,6 +256,7 @@ class Product extends ApiCommon
214 256
         $page = $param['page'] ?: 1;
215 257
         unset($param['page']);
216 258
         unset($param['export_queue_index']);
259
+        RecordActionLog($userInfo['id'],'crm_product','excelexport',$action_name,'','','导出产品');
217 260
         return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
218 261
             $param['page'] = $page;
219 262
             $param['limit'] = $limit;
@@ -239,6 +282,7 @@ class Product extends ApiCommon
239 282
         $param['owner_user_id'] = $param['owner_user_id'] ? : $userInfo['id'];
240 283
         $file = request()->file('file');
241 284
         $res = $excelModel->batchImportData($file, $param, $this);
285
+        RecordActionLog($userInfo['id'],'crm_product','excel','导入产品','','','导入产品');
242 286
         return resultArray(['data' => $excelModel->getError()]);
243 287
     }
244 288
 
@@ -283,8 +327,8 @@ class Product extends ApiCommon
283 327
             if ($isDel) {
284 328
                 $delIds[] = $v;
285 329
             }
286
-        }     
287
-        
330
+        }
331
+        $dataInfo = $productModel->where('product_id',['in',$delIds])->select();
288 332
         if ($delIds) {
289 333
             // 开启事务
290 334
             ProductModel::startTrans();
@@ -298,7 +342,10 @@ class Product extends ApiCommon
298 342
                 // 操作记录
299 343
                 (new ActionRecordModel)->delDataById('crm_product', $delIds);
300 344
                 // 添加删除记录
301
-                actionLog($delIds, '', '', '');
345
+                $userInfo = $this->userInfo;
346
+                foreach ($dataInfo as $k => $v) {
347
+                    RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['name'], '', '', '删除了产品:' . $v['name']);
348
+                }
302 349
                 return resultArray(['data' => '删除成功']);
303 350
             } else {
304 351
                 // 事务回滚
@@ -359,11 +406,16 @@ class Product extends ApiCommon
359 406
     {
360 407
         if (empty($this->param['product_id']) || !is_array($this->param['product_id'])) return resultArray(['error' => '产品参数错误!']);
361 408
         if (empty($this->param['owner_user_id'])) return resultArray(['error' => '请选择要变更的负责人']);
362
-
409
+        $userModel = new \app\admin\model\User();
410
+        $userInfo=$this->userInfo;
363 411
         $productModel = new \app\crm\model\Product();
364
-
365 412
         if (!$productModel->transfer($this->param)) return resultArray(['error' => '操作失败!']);
366
-
413
+        $owner_user_info = $userModel->getUserById($this->param['owner_user_id']);
414
+        foreach ($this->param['product_id'] as $v){
415
+            $product_info=db('crm_product')->where('product_id',$v)->find();
416
+            updateActionLog($userInfo['id'], 'crm_product', $v, '', '', '将产品转移给:' . $owner_user_info['realname']);
417
+            RecordActionLog($userInfo['id'], 'crm_product', 'transfer',$product_info['name'], '','','将产品:'.$product_info['name'].'转移给:' . $owner_user_info['realname']);
418
+        }
367 419
         return resultArray(['data' => '操作成功!']);
368 420
     }
369 421
 }

+ 1
- 1
application/crm/controller/ProductCategory.php Zobrazit soubor

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

+ 12
- 2
application/crm/controller/Receivables.php Zobrazit soubor

@@ -66,8 +66,10 @@ class Receivables extends ApiCommon
66 66
         $param = $this->param;
67 67
         $userInfo = $this->userInfo;
68 68
         $param['user_id'] = $userInfo['id'];
69
+        $action_name = '导出全部';
69 70
         if ($param['receivables_id']) {
70 71
             $param['receivables_id'] = ['condition' => 'in', 'value' => $param['receivables_id'], 'form_type' => 'text', 'name' => ''];
72
+            $action_name='导出选中';
71 73
         }
72 74
         $excelModel = new \app\admin\model\Excel();
73 75
         // 导出的字段列表
@@ -81,6 +83,7 @@ class Receivables extends ApiCommon
81 83
         $page = $param['page'] ?: 1;
82 84
         unset($param['page']);
83 85
         unset($param['export_queue_index']);
86
+        RecordActionLog($userInfo['id'],'crm_receivables','excelexport',$action_name,'','','导出回款');
84 87
         return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
85 88
             $param['page'] = $page;
86 89
             $param['limit'] = $limit;
@@ -174,7 +177,8 @@ class Receivables extends ApiCommon
174 177
         $receivablesModel = model('Receivables');
175 178
         $userModel = new \app\admin\model\User();
176 179
         $param = $this->param;
177
-        $data = $receivablesModel->getDataById($param['id']);
180
+        $userInfo = $this->userInfo;
181
+        $data = $receivablesModel->getDataById($param['id'], $userInfo['id']);
178 182
         
179 183
         //判断权限
180 184
         $auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'read');
@@ -338,6 +342,7 @@ class Receivables extends ApiCommon
338 342
                 $delIds[] = $v;
339 343
             }
340 344
         }
345
+        $dataInfo = $receivablesModel->where('receivables_id',['in',$delIds])->select();
341 346
         if ($delIds) {
342 347
             $data = $receivablesModel->delDatas($delIds);
343 348
             if (!$data) {
@@ -349,7 +354,10 @@ class Receivables extends ApiCommon
349 354
             $fileModel->delRFileByModule('crm_receivables', $delIds);
350 355
             //删除关联操作记录
351 356
             $actionRecordModel->delDataById(['types' => 'crm_receivables', 'action_id' => $delIds]);
352
-            actionLog($delIds, '', '', '');
357
+            $userInfo = $this->userInfo;
358
+            foreach ($dataInfo as $k => $v) {
359
+                RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['number'], '', '', '删除了回款:' . $v['number']);
360
+            }
353 361
         }
354 362
         
355 363
         if ($errorMessage) {
@@ -594,6 +602,8 @@ class Receivables extends ApiCommon
594 602
                 continue;
595 603
             }
596 604
             updateActionLog($userInfo['id'], 'crm_receivables', $receivables_id, '', '', '将回款转移给:' . $owner_user_info['realname']);
605
+            RecordActionLog($userInfo['id'], 'crm_receivables', 'transfer',$receivables_info['number'], '','','将回款:'.$receivables_info['number'].'转移给:' . $owner_user_info['realname']);
606
+    
597 607
         }
598 608
         if (!$errorMessage) {
599 609
             return resultArray(['data' => '转移成功']);

+ 29
- 47
application/crm/controller/Setting.php Zobrazit soubor

@@ -26,24 +26,9 @@ class Setting extends ApiCommon
26 26
         $action = [
27 27
             'permission' => [''],
28 28
             'allow' => [
29
-                'config',
30
-                'configdata',
31
-                'team',
32
-                'teamsave',
33
-                'contractday',
34
-                'recordlist',
35
-                'recordedit',
36
-                'customerconfiglist',
37
-                'customerconfigsave',
38
-                'customerconfigupdate',
39
-                'customerconfigdelete',
40
-                'numberSequenceAdd',
41
-                'quitteam',
42
-                'setvisitday',
43
-                'getvisitday',
44
-                'setnumber',
45
-                'customerconfigdel',
46
-                'numbersequencelist'
29
+                'config', 'configdata', 'team', 'teamsave', 'contractday', 'recordlist', 'recordedit', 'customerconfiglist',
30
+                'customerconfigsave', 'customerconfigupdate', 'customerconfigdelete', 'numberSequenceAdd', 'quitteam',
31
+                'setvisitday', 'getvisitday', 'setnumber', 'customerconfigdel', 'numbersequencelist',
47 32
             ]
48 33
         ];
49 34
         Hook::listen('check_auth', $action);
@@ -307,7 +292,7 @@ class Setting extends ApiCommon
307 292
                 $param['type'] = $param['type'] ?: 1;
308 293
                 $param['is_del'] = $param['is_del'] ?: 3;
309 294
                 $param['owner_user_id'] = $userInfo['id'];
310
-                if (!$param['is_del']) {
295
+                if (empty($param['is_del'])) {
311 296
                     $res = $settingModel->createTeamData($param);
312 297
                     if (!$res) {
313 298
                         $errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
@@ -320,12 +305,25 @@ class Setting extends ApiCommon
320 305
                             ],
321 306
                             $param['user_id']
322 307
                         );
308
+                        $username=db('admin_user')->where('id',['in',$param['user_id']])->column('realname');
309
+                        RecordActionLog($userInfo['id'], 'crm_customer', 'teamSave',$dataInfo['name'], '','','给' . $typesName. $dataInfo['name'].'添加了团队成员 :'.implode(',',$username));
323 310
                     }
324 311
                 } else {
325 312
                     $res = $settingModel->createTeamData($param);
326 313
                     if (!$res) {
327 314
                         $errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
315
+                    }else{
316
+                        (new Message())->send(
317
+                            Message::TEAM_END,
318
+                            [
319
+                                'title' => $dataInfo['name'],
320
+                                'action_id' => $v
321
+                            ],
322
+                            $param['user_id']
323
+                        );
328 324
                     }
325
+                    $username=db('admin_user')->where('id',['in',$param['user_id']])->column('realname');
326
+                    RecordActionLog($userInfo['id'], 'crm_customer', 'teamSave',$dataInfo['name'], '','','移除了' . $typesName. $dataInfo['name'].'团队成员 :'.implode(',',$username));
329 327
                 }
330 328
 
331 329
             }
@@ -352,11 +350,14 @@ class Setting extends ApiCommon
352 350
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
353 351
         }
354 352
         $param = $this->param;
353
+        $userInfo=$this->userInfo;
355 354
         $data = [];
356 355
         $contract_day = $param['contract_day'] ? intval($param['contract_day']) : 0;
357 356
         $contract_config = $param['contract_config'] ? intval($param['contract_config']) : 0;
358 357
         $res = db('crm_config')->where(['name' => 'contract_config'])->update(['value' => $contract_config]);
359 358
         if ($contract_day && $contract_config == 1) $res = db('crm_config')->where(['name' => 'contract_day'])->update(['value' => $contract_day]);
359
+        # 系统操作日志
360
+        SystemActionLog($userInfo['id'], 'crm_config','customer', 1, 'update','' , '', '','编辑了合同到期提醒设置');
360 361
         return resultArray(['data' => '设置成功']);
361 362
     }
362 363
 
@@ -373,6 +374,7 @@ class Setting extends ApiCommon
373 374
     public function recordEdit()
374 375
     {
375 376
         $param = $this->param;
377
+        $userInfo=$this->userInfo;
376 378
         //权限判断
377 379
         if (!checkPerByAction('admin', 'crm', 'setting')) {
378 380
             header('Content-Type:application/json; charset=utf-8');
@@ -383,14 +385,18 @@ class Setting extends ApiCommon
383 385
             $record_type = db('crm_config')->where(['name' => 'record_type'])->find();
384 386
             if ($record_type) {
385 387
                 $res = db('crm_config')->where(['name' => 'record_type'])->update(['value' => $array]);
388
+                $id=$record_type['id'];
386 389
             } else {
387 390
                 $data = array();
388 391
                 $data['name'] = 'record_type';
389 392
                 $data['value'] = $array;
390 393
                 $data['description'] = '跟进记录类型';
391
-                $res = db('crm_config')->insert($data);
394
+                $res = db('crm_config')->insertGetId($data);
395
+                $id=$res;
396
+                $record_type['description']='跟进记录类型';
392 397
             }
393 398
             if ($res) {
399
+                SystemActionLog($userInfo['id'], 'crm_config','customer', $id,  'update',$record_type['description'] , '', '','编辑了跟进记录类型:'.$record_type['description']);
394 400
                 return resultArray(['data' => '设置成功']);
395 401
             } else {
396 402
                 return resultArray(['error' => '设置失败,请重试!']);
@@ -522,29 +528,6 @@ class Setting extends ApiCommon
522 528
         return resultArray(['data' => $data]);
523 529
     }
524 530
 
525
-    /**
526
-     * 编号添加
527
-     *
528
-     * @return \think\response\Json
529
-     */
530
-    public function numberSequenceAdd()
531
-    {
532
-        //权限判断
533
-        if (!checkPerByAction('admin', 'crm', 'setting')) {
534
-            header('Content-Type:application/json; charset=utf-8');
535
-            exit(json_encode(['code' => 102, 'error' => '无权操作']));
536
-        }
537
-        $userInfo = $this->userInfo;
538
-        $param = $this->param;
539
-        $param['user_id'] = $userInfo['id'];
540
-        $numberSequenceModel = new \app\crm\model\NumberSequence();
541
-        $res = $numberSequenceModel->createData($param);
542
-        if (!$res) {
543
-            return resultArray(['error' => $numberSequenceModel->getError()]);
544
-        }
545
-        return resultArray(['data' => '创建成功']);
546
-    }
547
-
548 531
     /**
549 532
      * 编号修改
550 533
      *
@@ -605,7 +588,7 @@ class Setting extends ApiCommon
605 588
 
606 589
         return resultArray(['data' => '操作成功!']);
607 590
     }
608
-
591
+    
609 592
     /**
610 593
      * 获取回访提醒
611 594
      *
@@ -614,12 +597,11 @@ class Setting extends ApiCommon
614 597
     public function getVisitDay()
615 598
     {
616 599
         $settingModel = new \app\crm\model\Setting();
617
-
600
+        
618 601
         $data = $settingModel->getVisitDay();
619
-
602
+        
620 603
         return resultArray(['data' => $data]);
621 604
     }
622
-
623 605
     /**
624 606
      * 设置自动编号
625 607
      *

+ 1
- 2
application/crm/controller/Visit.php Zobrazit soubor

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

+ 115
- 71
application/crm/logic/ActivityLogic.php Zobrazit soubor

@@ -8,6 +8,7 @@
8 8
 
9 9
 namespace app\crm\logic;
10 10
 
11
+use app\admin\controller\ApiCommon;
11 12
 use app\admin\model\Group;
12 13
 use app\crm\model\Activity;
13 14
 use think\Db;
@@ -77,27 +78,110 @@ class ActivityLogic
77 78
             $recordWhere['type'] = ['neq', 1];
78 79
         }
79 80
 
81
+        # 处理公共查询参数
82
+        if (!empty($param['interval_day'])) {
83
+            $commonWhere['update_time'] = ['egt', time() - 86400 * $param['interval_day']];
84
+            $commonWhere['update_time'] = ['elt', time()];
85
+        }
86
+        if (!empty($param['start_date']) && !empty($param['end_date'])) {
87
+            $commonWhere['update_time'] = ['egt', strtotime($param['start_date'].' 00:00:00')];
88
+            $commonWhere['update_time'] = ['elt', strtotime($param['end_date'].' 23:59:59')];
89
+        }
90
+        if (!empty($param['search'])) {
91
+            $commonWhere['content'] = ['like', '%' . $param['search'] . '%'];
92
+        }
93
+        if (!empty($param['activity_type'])) {
94
+            $commonWhere['activity_type'] = $param['activity_type'];
95
+        }
96
+
97
+        # 客户模块的额外查询条件
98
+        $contactsData    = [];
99
+        $businessData    = [];
100
+        $contractData    = [];
101
+        $receivablesData = [];
102
+
103
+        # 联系人ID串
104
+        $contacts = Db::name('crm_contacts')->field(['contacts_id'])->where('customer_id', $param['activity_type_id'])->select();
105
+        if (!empty($contacts)) {
106
+            $contactsData['activity_type']    = 3;
107
+            $contactsData['activity_type_id'] = array_reduce($contacts, function ($result, $value) {
108
+                return array_merge($result, array_values($value));
109
+            }, []);
110
+        }
111
+
112
+        # 商机ID串
113
+        $business = Db::name('crm_business')->field(['business_id'])->where('customer_id', $param['activity_type_id'])->select();
114
+        if (!empty($business)) {
115
+            $businessData['activity_type']    = 5;
116
+            $businessData['activity_type_id'] = array_reduce($business, function ($result, $value) {
117
+                return array_merge($result, array_values($value));
118
+            }, []);
119
+        }
120
+
121
+        # 合同ID串
122
+        $contract = Db::name('crm_contract')->field(['contract_id'])->where('customer_id', $param['activity_type_id'])->select();
123
+        if (!empty($contract)) {
124
+            $contractData['activity_type'] = 6;
125
+            $contractData['activity_type_id'] = array_reduce($contract, function ($result, $value) {
126
+                return array_merge($result, array_values($value));
127
+            }, []);
128
+        }
129
+
130
+        # 回款ID串
131
+        $receivables = Db::name('crm_receivables')->field(['receivables_id'])->where('customer_id', $param['activity_type_id'])->select();
132
+        if (!empty($receivables)) {
133
+            $receivablesData['activity_type'] = 7;
134
+            $receivablesData['activity_type_id'] = array_reduce($receivables, function ($result, $value) {
135
+                return array_merge($result, array_values($value));
136
+            }, []);
137
+        }
138
+
80 139
         # 设置时间分组查询条件,第一页就是当天的数据,第二页就是下一天的数据
81 140
         $datetime = Db::name('crm_activity')
82 141
             ->field('update_time')
83 142
             ->where($recordWhere)
84 143
             ->where('status', 1)
85
-            ->where(function ($query) use ($param) {
144
+            ->where(function ($query) use ($param, $contactsData, $businessData, $contractData, $receivablesData) {
86 145
                 $query->whereOr(function ($query) use ($param) {
87 146
                     $query->where('activity_type_id', $param['activity_type_id']);
88 147
                     $query->where('activity_type', $this->moduleToNumber[$param['module']]);
89 148
                 });
90
-                $query->whereOr('customer_ids', 'like', ',%'.$param['activity_type_id'].'%,');
91
-                $query->whereOr('contacts_ids', 'like', ',%'.$param['activity_type_id'].'%,');
92
-                $query->whereOr('contract_ids', 'like', ',%'.$param['activity_type_id'].'%,');
93
-                $query->whereOr('business_ids', 'like', ',%'.$param['activity_type_id'].'%,');
94
-                $query->whereOr('leads_ids', 'like', ',%'.$param['activity_type_id'].'%,');
149
+                $query->whereOr('customer_ids', 'like', '%,'.$param['activity_type_id'].',%');
150
+                $query->whereOr('contacts_ids', 'like', '%,'.$param['activity_type_id'].',%');
151
+                $query->whereOr('contract_ids', 'like', '%,'.$param['activity_type_id'].',%');
152
+                $query->whereOr('business_ids', 'like', '%,'.$param['activity_type_id'].',%');
153
+                $query->whereOr('leads_ids', 'like', '%,'.$param['activity_type_id'].',%');
154
+                if (!empty($contactsData)) {
155
+                    $query->whereOr(function ($query) use ($contactsData) {
156
+                        $query->where('activity_type', $contactsData['activity_type']);
157
+                        $query->whereIn('activity_type_id', $contactsData['activity_type_id']);
158
+                    });
159
+                }
160
+                if (!empty($businessData)) {
161
+                    $query->whereOr(function ($query) use ($businessData) {
162
+                        $query->where('activity_type', $businessData['activity_type']);
163
+                        $query->whereIn('activity_type_id', $businessData['activity_type_id']);
164
+                    });
165
+                }
166
+                if (!empty($contractData)) {
167
+                    $query->whereOr(function ($query) use ($contractData) {
168
+                        $query->where('activity_type', $contractData['activity_type']);
169
+                        $query->whereIn('activity_type_id', $contractData['activity_type_id']);
170
+                    });
171
+                }
172
+                if (!empty($receivablesData)) {
173
+                    $query->whereOr(function ($query) use ($receivablesData) {
174
+                        $query->where('activity_type', $receivablesData['activity_type']);
175
+                        $query->whereIn('activity_type_id', $receivablesData['activity_type_id']);
176
+                    });
177
+                }
95 178
             })
179
+            ->where($commonWhere)
96 180
             ->order('update_time', 'desc')
97 181
             ->group('update_time')
98 182
             ->select();
99
-        $dateGroup = [0 => '']; // 加一个占位,page是从1开始
100
-        $dateWhere = [0 => []]; // 加一个占位,page是从1开始
183
+        $dateGroup = [0 => '']; // 加一个占位,page从1开始
184
+        $dateWhere = [0 => []]; // 加一个占位,page从1开始
101 185
         foreach ($datetime AS $key => $value) {
102 186
             $date = date('Y-m-d', $value['update_time']);
103 187
             if (!in_array($date, $dateGroup)) {
@@ -118,22 +202,6 @@ class ActivityLogic
118 202
             return ['lastPage' => true, 'list' => [], 'time' => ''];
119 203
         }
120 204
 
121
-        # 处理公共查询参数
122
-        if (!empty($param['interval_day'])) {
123
-            $commonWhere['update_time'] = ['egt', time() - 86400 * $param['interval_day']];
124
-            $commonWhere['update_time'] = ['elt', time()];
125
-        }
126
-        if (!empty($param['start_date']) && !empty($param['end_date'])) {
127
-            $commonWhere['update_time'] = ['egt', strtotime($param['start_date'])];
128
-            $commonWhere['update_time'] = ['elt', strtotime($param['end_date'])];
129
-        }
130
-        if (!empty($param['search'])) {
131
-            $commonWhere['content'] = ['like', '%' . $param['search'] . '%'];
132
-        }
133
-        if (!empty($param['activity_type'])) {
134
-            $commonWhere['activity_type'] = $param['activity_type'];
135
-        }
136
-
137 205
         # 组织线索、客户、联系人、商机、合同下的查询条件
138 206
         switch ($param['module']) {
139 207
             case 'leads' :
@@ -143,47 +211,6 @@ class ActivityLogic
143 211
                 };
144 212
                 break;
145 213
             case 'customer' :
146
-                $contactsData    = [];
147
-                $businessData    = [];
148
-                $contractData    = [];
149
-                $receivablesData = [];
150
-
151
-                # 联系人ID串
152
-                $contacts = Db::name('crm_contacts')->field(['contacts_id'])->where('customer_id', $param['activity_type_id'])->select();
153
-                if (!empty($contacts)) {
154
-                    $contactsData['activity_type']    = 3;
155
-                    $contactsData['activity_type_id'] = array_reduce($contacts, function ($result, $value) {
156
-                        return array_merge($result, array_values($value));
157
-                    }, []);
158
-                }
159
-
160
-                # 商机ID串
161
-                $business = Db::name('crm_business')->field(['business_id'])->where('customer_id', $param['activity_type_id'])->select();
162
-                if (!empty($business)) {
163
-                    $businessData['activity_type']    = 5;
164
-                    $businessData['activity_type_id'] = array_reduce($business, function ($result, $value) {
165
-                        return array_merge($result, array_values($value));
166
-                    }, []);
167
-                }
168
-
169
-                # 合同ID串
170
-                $contract = Db::name('crm_contract')->field(['contract_id'])->where('customer_id', $param['activity_type_id'])->select();
171
-                if (!empty($contract)) {
172
-                    $contractData['activity_type'] = 6;
173
-                    $contractData['activity_type_id'] = array_reduce($contract, function ($result, $value) {
174
-                        return array_merge($result, array_values($value));
175
-                    }, []);
176
-                }
177
-
178
-                # 回款ID串
179
-                $receivables = Db::name('crm_receivables')->field(['receivables_id'])->where('customer_id', $param['activity_type_id'])->select();
180
-                if (!empty($receivables)) {
181
-                    $receivablesData['activity_type'] = 7;
182
-                    $receivablesData['activity_type_id'] = array_reduce($receivables, function ($result, $value) {
183
-                        return array_merge($result, array_values($value));
184
-                    }, []);
185
-                }
186
-
187 214
                 # 客户模块查询条件
188 215
                 $customerWhere = function ($query) use ($param, $contactsData, $businessData, $contractData, $receivablesData) {
189 216
                     $query->whereOr(function ($query) use ($param) {
@@ -292,7 +319,7 @@ class ActivityLogic
292 319
  
293 320
         $fileModel = new \app\admin\model\File();
294 321
         foreach ($dataArray AS $key => $value) {
295
-            # 用户信息 todo 有模型文件,时间问题,暂时将查询写在循环中
322
+            # 用户信息
296 323
             $realname = Db::name('admin_user')->where('id', $dataArray[$key]['create_user_id'])->find();
297 324
             $dataArray[$key]['create_user_name'] = $realname['realname'];
298 325
             $dataArray[$key]['thumb_img'] =  $realname['thumb_img'] ? getFullPath($realname['thumb_img']) : '';;
@@ -418,7 +445,6 @@ class ActivityLogic
418 445
         $param['create_time']    = time();
419 446
         $param['update_time']    = time();
420 447
         if (!empty($param['contacts_ids'])) $param['contacts_ids'] = ',' . $param['contacts_ids'] . ',';
421
-
422 448
         $activityJson = Activity::create($param);
423 449
         if (empty($activityJson)) return false;
424 450
 
@@ -454,7 +480,8 @@ class ActivityLogic
454 480
 
455 481
             $eventModel->createData($data);
456 482
         }
457
-
483
+        $activity=[1 =>'线索', 2=> '客户', 3 =>'联系人' ,4 =>'产品', 5 =>'商机', 6 =>'合同' ,7=>'回款' ,8=>'日志' ,9=>'审批' ,10=>'日程' ,11=>'任务' ,12 =>'发邮件'];
484
+        RecordActionLog($param['create_user_id'],'crm_activity','save',$activity[$param['activity_type']],'','','新增了跟进记录'.$param['content']);
458 485
         return true;
459 486
     }
460 487
 
@@ -472,12 +499,11 @@ class ActivityLogic
472 499
         $fileIds     = !empty($param['file_id'])  ? $param['file_id']      : [];
473 500
         unset($param['is_event']);
474 501
         unset($param['file_id']);
475
-
476 502
         $param['type']         = 1;
477 503
         $param['next_time']    = strtotime($param['next_time']);
478 504
         $param['business_ids'] = !empty($param['business_ids']) ? arrayToString($param['business_ids']) : '';
479 505
         $param['update_time']  = time();
480
-
506
+        $dataInfo=db('crm_activity')->where('activity_id',$param['activity_id'])->find();
481 507
         if (!Activity::update($param)) return false;
482 508
 
483 509
         # 设置最后跟进记录
@@ -514,7 +540,6 @@ class ActivityLogic
514 540
 
515 541
             $eventModel->createData($data);
516 542
         }
517
-
518 543
         return true;
519 544
     }
520 545
 
@@ -538,6 +563,9 @@ class ActivityLogic
538 563
             if ($activityInfo['activity_type'] == 3) db('crm_contacts_file')->whereIn('file_id', $fileIds)->delete();
539 564
             if ($activityInfo['activity_type'] == 5) db('crm_business_file')->whereIn('file_id', $fileIds)->delete();
540 565
             if ($activityInfo['activity_type'] == 6) db('crm_contract_file')->whereIn('file_id', $fileIds)->delete();
566
+            $user=new ApiCommon();
567
+            $userInfo=$user->userInfo;
568
+            RecordActionLog($userInfo['id'],'crm_activity','delete','删除跟进记录','','','删除了'.$recordModules[$types].$name);
541 569
             return true;
542 570
         } else {
543 571
             return false;
@@ -795,4 +823,20 @@ class ActivityLogic
795 823
 
796 824
         $model->where($primaryKey, $typeId)->update(['last_time' => time(), 'last_record' => $content]);
797 825
     }
826
+    
827
+    /**
828
+     * 跟进记录导出
829
+     * @param $field_list
830
+     * @param $data
831
+     *
832
+     * @author      alvin guogaobo
833
+     * @version     1.0 版本号
834
+     * @since       2021/4/21 0021 09:35
835
+     */
836
+    public function excelExport($field_list,$data){
837
+        $excelModel = new \app\admin\model\Excel();
838
+        $file_name='activity_record';
839
+        $title='跟进记录';
840
+        $excelModel->taskExportCsv($file_name, $field_list, $title, $data);
841
+    }
798 842
 }

+ 2
- 0
application/crm/logic/CommonLogic.php Zobrazit soubor

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

+ 1084
- 0
application/crm/logic/CustomerPoolLogic.php
Diff nebyl zobrazen, protože je příliš veliký
Zobrazit soubor


+ 74
- 67
application/crm/logic/IndexLogic.php Zobrazit soubor

@@ -22,7 +22,7 @@ class IndexLogic extends Common
22 22
         '11' => 'november',
23 23
         '12' => 'december',
24 24
     ];
25
-
25
+    
26 26
     /**
27 27
      * @param $param
28 28
      * @return array
@@ -46,7 +46,7 @@ class IndexLogic extends Common
46 46
         $userIds = $whereArr['userIds'];
47 47
         $between_time = $whereArr['between_time'];
48 48
         $last_between_time = $lastArr['between_time'];
49
-      
49
+        
50 50
         
51 51
         $customerNum = 0; //新增客户
52 52
         $customerLastNum = 0; //上期对比
@@ -64,13 +64,13 @@ class IndexLogic extends Common
64 64
         $contractLastMoneyNum = 0; //上期对比
65 65
         $receivablesMoneyNum = 0; //新增回款金额
66 66
         $receivablesLastMoneyNum = 0; //上期对比
67
-
67
+        
68 68
         $where = [];
69 69
         $where['owner_user_id']['value'] = $userIds;
70 70
         $where['create_time']['start'] = $between_time[0];
71 71
         $where['create_time']['end'] = $between_time[1];
72 72
         $where['getCount'] = 1;
73
-
73
+        
74 74
         $customer_auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'index');
75 75
         $contacts_auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'index');
76 76
         $business_auth_user_ids = $userModel->getUserByPer('crm', 'business', 'index');
@@ -89,7 +89,7 @@ class IndexLogic extends Common
89 89
                 'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? :[-1],
90 90
             ])
91 91
         );
92
-
92
+        
93 93
         $resLastCount = queryCache(
94 94
             $this->getCountSql([
95 95
                 'start_time' => $last_between_time[0],
@@ -102,7 +102,7 @@ class IndexLogic extends Common
102 102
                 'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? : [-1],
103 103
             ])
104 104
         );
105
-
105
+        
106 106
         $customerNum = (int)$resCount[0]['count1'] ?: 0;
107 107
         $contactsNum = (int)$resCount[1]['count1'] ?: 0;
108 108
         $businessNum = (int)$resCount[2]['count1'] ?: 0;
@@ -111,7 +111,7 @@ class IndexLogic extends Common
111 111
         $contractMoneyNum = $resCount[3]['count2'] ?: 0;
112 112
         $receivablesMoneyNum = $resCount[4]['count1'] ?: 0;
113 113
         $recordNum = (int)$resCount[5]['count1'] ?: 0;
114
-
114
+        
115 115
         $customerLastNum = (int)$resLastCount[0]['count1'] ?: 0;
116 116
         $contactsLastNum = (int)$resLastCount[1]['count1'] ?: 0;
117 117
         $businessLastNum = (int)$resLastCount[2]['count1'] ?: 0;
@@ -120,34 +120,34 @@ class IndexLogic extends Common
120 120
         $contractLastMoneyNum = $resLastCount[3]['count2'] ?: 0;
121 121
         $receivablesLastMoneyNum = $resLastCount[4]['count'] ?: 0;
122 122
         $recordLastNum = (int)$resLastCount[5]['count'] ?: 0;
123
-
123
+        
124 124
         $data = [];
125 125
         $data['data']['customerNum'] = $customerNum;
126 126
         $data['prev']['customerNum'] = $this->getProportion($customerNum, $customerLastNum);
127
-
127
+        
128 128
         $data['data']['contactsNum'] = $contactsNum;
129 129
         $data['prev']['contactsNum'] = $this->getProportion($contactsNum, $contactsLastNum);
130
-
130
+        
131 131
         $data['data']['businessNum'] = $businessNum;
132 132
         $data['prev']['businessNum'] = $this->getProportion($businessNum, $businessLastNum);
133
-
133
+        
134 134
         $data['data']['contractNum'] = $contractNum;
135 135
         $data['prev']['contractNum'] = $this->getProportion($contractNum, $contractLastNum);
136
-
136
+        
137 137
         $data['data']['recordNum'] = $recordNum;
138 138
         $data['prev']['recordNum'] = $this->getProportion($recordNum, $recordLastNum);
139
-
139
+        
140 140
         $data['data']['businessMoneyNum'] = $businessMoneyNum;
141 141
         $data['prev']['businessMoneyNum'] = $this->getProportion($businessMoneyNum, $businessLastMoneyNum);
142
-
142
+        
143 143
         $data['data']['contractMoneyNum'] = $contractMoneyNum;
144 144
         $data['prev']['contractMoneyNum'] = $this->getProportion($contractMoneyNum, $contractLastMoneyNum);
145
-
145
+        
146 146
         $data['data']['receivablesMoneyNum'] = $receivablesMoneyNum;
147 147
         $data['prev']['receivablesMoneyNum'] = $this->getProportion($receivablesMoneyNum, $receivablesLastMoneyNum);
148 148
         return $data;
149 149
     }
150
-
150
+    
151 151
     public function getCountSql($param)
152 152
     {
153 153
         $configModel = new \app\crm\model\ConfigData();
@@ -162,9 +162,8 @@ class IndexLogic extends Common
162 162
         count(1) count1,
163 163
         0 count2
164 164
         FROM 5kcrm_crm_customer
165
-        WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
165
+        WHERE (create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . " OR obtain_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . ")
166 166
         and owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")
167
-        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 )
168 167
         UNION ALL
169 168
         SELECT
170 169
         count(1) AS count1,
@@ -173,7 +172,6 @@ class IndexLogic extends Common
173 172
          LEFT JOIN 5kcrm_crm_customer customer ON contacts.customer_id=customer.customer_id
174 173
         WHERE contacts.create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
175 174
         and contacts.owner_user_id IN (" . implode(',', $param['contacts_auth_user_ids']) . ")
176
-        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 )
177 175
         UNION ALL
178 176
         SELECT
179 177
         count(1) AS count1,
@@ -183,7 +181,7 @@ class IndexLogic extends Common
183 181
         and owner_user_id IN (" . implode(',', $param['business_auth_user_ids']) . ")
184 182
         UNION ALL
185 183
         SELECT
186
-        count(1) AS count1,
184
+        count( CASE WHEN check_status = 2 THEN 1 ELSE null END) AS count1,
187 185
         SUM( CASE WHEN check_status = 2 THEN money ELSE 0 END) AS count2
188 186
         FROM 5kcrm_crm_contract
189 187
         WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
@@ -208,7 +206,7 @@ class IndexLogic extends Common
208 206
         and create_user_id IN (" . implode(',', $param['record_auth_user_ids']) . ")";
209 207
         return $countSql;
210 208
     }
211
-
209
+    
212 210
     ///计算涨幅
213 211
     public function getProportion($now, $last)
214 212
     {
@@ -224,8 +222,8 @@ class IndexLogic extends Common
224 222
         }
225 223
         return $res;
226 224
     }
227
-
228
-
225
+    
226
+    
229 227
     /**
230 228
      * 遗忘数据统计
231 229
      * @return mixed
@@ -246,14 +244,14 @@ class IndexLogic extends Common
246 244
         $auth_customer_user_ids = $userModel->getUserByPer('crm', 'customer', 'index');
247 245
         $auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集
248 246
         $owner_user_ids = array('in', $auth_customer_user_ids);
249
-
247
+        
250 248
         $customerParam = [];
251 249
         $customerParam['limit'] = $param['limit'];
252 250
         $customerParam['page'] = $param['page'];
253 251
         $customerParam['search'] = $param['search'];
254 252
         $customerParam['getCount'] = 1;
255 253
         $customerParam['owner_user_id'] = $owner_user_ids;
256
-
254
+        
257 255
         $sevenDaysParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-1 week') . ") ";
258 256
         $fifteenDaysParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-15 day') . ") ";
259 257
         $oneMonthParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-30 day') . ") ";
@@ -266,10 +264,10 @@ class IndexLogic extends Common
266 264
         $data['threeMonth'] = $customerModel->getDataList(array_merge($customerParam, $threeMonthParam))['dataCount'] ?: 0;
267 265
         $data['sixMonth'] = $customerModel->getDataList(array_merge($customerParam, $sixMonthParam))['dataCount'] ?: 0;
268 266
         $data['unContactCustomerCount'] = $customerModel->getDataList(array_merge($customerParam, $unContactParam))['dataCount'] ?: 0;
269
-
267
+        
270 268
         return $data;
271 269
     }
272
-
270
+    
273 271
     /**
274 272
      * 遗忘数据列表
275 273
      * @return mixed
@@ -292,13 +290,13 @@ class IndexLogic extends Common
292 290
         $auth_customer_user_ids = $userModel->getUserByPer('crm', 'customer', 'index');
293 291
         $auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集
294 292
         $owner_user_ids = array('in', $auth_customer_user_ids);
295
-
293
+        
296 294
         $sql_unContactCustomerList = db('crm_customer')
297 295
             ->where(['owner_user_id' => $owner_user_ids])
298 296
             ->where('last_time < next_time AND next_time < now()')
299 297
             ->fetchSql()
300 298
             ->select();
301
-
299
+        
302 300
         $label = $param['label'];
303 301
         $day = $param['day'] ?: '';
304 302
         $customerParam = [];
@@ -306,7 +304,7 @@ class IndexLogic extends Common
306 304
         $customerParam['page'] = $param['page'];
307 305
         $customerParam['search'] = $param['search'];
308 306
         $customerParam['owner_user_id'] = $owner_user_ids;
309
-
307
+        
310 308
         switch ($label) {
311 309
             case 1 :
312 310
 //                ((( 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
330 328
         }
331 329
         return $customerModel->getDataList($customerParam);
332 330
     }
333
-
331
+    
334 332
     /**
335 333
      * 排行榜
336 334
      * @param $param
@@ -351,7 +349,7 @@ class IndexLogic extends Common
351 349
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
352 350
         $userIds = $whereArr['userIds'];
353 351
         $between_time = $whereArr['between_time'];
354
-
352
+        
355 353
         $auth_user_ids = $userModel->getUserByPer('bi', 'ranking', 'read');
356 354
         $auth_user_ids = $auth_user_ids ? array_intersect($userIds, $auth_user_ids) : []; //取交集
357 355
         switch ($param['label']) {
@@ -424,7 +422,6 @@ class IndexLogic extends Common
424 422
                     ->where([
425 423
                         'contract.owner_user_id' => ['in', $auth_user_ids],
426 424
                         'contract.create_time' => ['between', $between_time],
427
-                        'contract.check_status' => 2
428 425
                     ])
429 426
                     ->group('contract.owner_user_id')
430 427
                     ->order('count desc,owner_user_id asc')
@@ -433,6 +430,10 @@ class IndexLogic extends Common
433 430
             //新增客户数
434 431
             case '4':
435 432
                 //新增客户
433
+                $logMap=function ($query) use ($between_time) {
434
+                    $query->where('customer.create_time', array('between', $between_time))
435
+                        ->whereOr('customer.obtain_time', array('between', $between_time));
436
+                };
436 437
                 $list = db('crm_customer')
437 438
                     ->alias('customer')
438 439
                     ->join('__ADMIN_USER__ user', 'customer.create_user_id=user.id')
@@ -444,10 +445,10 @@ class IndexLogic extends Common
444 445
                         'user.thumb_img',
445 446
                         'structure.name',
446 447
                         'customer.owner_user_id as owner_user_id'])
447
-                    ->where([
448
-                        'customer.owner_user_id' => ['in', $auth_user_ids],
449
-                        'customer.create_time' => ['between', $between_time],
450
-                    ])
448
+                    ->where(
449
+                        'customer.owner_user_id' ,['in', $auth_user_ids]
450
+                    )
451
+                    ->where($logMap)
451 452
                     ->group('customer.owner_user_id')
452 453
                     ->order('count desc,owner_user_id asc')
453 454
                     ->select();
@@ -499,7 +500,7 @@ class IndexLogic extends Common
499 500
                     ->select();
500 501
                 break;
501 502
         }
502
-
503
+        
503 504
         //业绩目标
504 505
         $between_time = getTimeByType($param['type']);
505 506
         $start_time = $between_time[0];
@@ -558,12 +559,12 @@ class IndexLogic extends Common
558 559
             $ranking['ranking'][] = $v;
559 560
             $ranking['self'] = $list['self'];
560 561
         }
561
-
562
+        
562 563
         $data = [];
563 564
         $data = $ranking ?: [];
564 565
         return $data;
565 566
     }
566
-
567
+    
567 568
     /**
568 569
      * 数据汇总
569 570
      * @param $param
@@ -580,14 +581,14 @@ class IndexLogic extends Common
580 581
         $user_id = $param['user_id'] ?: [-1];
581 582
         $userIds = $whereArr['userIds'];
582 583
         $between_time = $whereArr['between_time'];
583
-
584
+        
584 585
         $customer_auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'index');
585 586
         $contacts_auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'index');
586 587
         $business_auth_user_ids = $userModel->getUserByPer('crm', 'business', 'index');
587 588
         $contract_auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'index');
588 589
         $receivables_auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index');
589 590
         $record_auth_user_ids = $userModel->getUserByPer('crm', 'activity', 'index');
590
-
591
+        
591 592
         $resDataArr = [];
592 593
         for ($i = 1; $i <= 5; $i++) {
593 594
             $resData = queryCache(
@@ -607,7 +608,7 @@ class IndexLogic extends Common
607 608
         }
608 609
         return $resDataArr;
609 610
     }
610
-
611
+    
611 612
     /**
612 613
      * [数据汇总sql]
613 614
      * @return
@@ -629,19 +630,17 @@ class IndexLogic extends Common
629 630
                 count(1) allCustomer,
630 631
                 COUNT(CASE WHEN deal_status = '已成交' THEN 1 ELSE NULL END) AS dealCustomer
631 632
                 FROM 5kcrm_crm_customer
632
-                WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
633
-                AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")
634
-                 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 )
635
-                ";
633
+                WHERE (create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . " OR obtain_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . ")
634
+                AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")";
636 635
                 break;
637 636
             case 2 :
638 637
                 $countSql = "SELECT
639 638
                  COUNT(distinct CASE WHEN  b.activity_type_id in (SELECT customer_id FROM 5kcrm_crm_customer
640
-                WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
641
-                AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")  AND next_time is not null
639
+                WHERE (create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . " OR obtain_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . ")
640
+                AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ") AND next_time is not null
642 641
                 ) THEN b.activity_type_id ELSE NULL END) as  activityNum
643 642
                 FROM 5kcrm_crm_activity AS b
644
-                WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
643
+                WHERE b.create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
645 644
                 AND b.type = '1'
646 645
                 AND b.activity_type = '2'
647 646
                 AND b.status = '1'
@@ -669,14 +668,15 @@ class IndexLogic extends Common
669 668
                 SUM( CASE WHEN r.check_status = 2 THEN r.money ELSE 0 END) AS receivablesMoney,
670 669
                 SUM(CASE WHEN p.money > 0 THEN p.money ELSE 0 END) AS planMoney
671 670
                 FROM 5kcrm_crm_receivables as r
672
-                LEFT JOIN 5kcrm_crm_receivables_plan AS p ON p.receivables_id = r.receivables_id                 
671
+                LEFT JOIN 5kcrm_crm_receivables_plan AS p ON p.receivables_id = r.receivables_id
673 672
                 WHERE r.create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
674 673
                 AND r.owner_user_id IN (" . implode(',', $param['business_auth_user_ids']) . ")";
675 674
                 break;
676 675
         }
676
+        
677 677
         return $countSql;
678 678
     }
679
-
679
+    
680 680
     /**
681 681
      * 赢单输单查看
682 682
      */
@@ -708,7 +708,7 @@ class IndexLogic extends Common
708 708
         $data['businesslist'] = $businessList;
709 709
         return $data;
710 710
     }
711
-
711
+    
712 712
     /**
713 713
      * 仪表盘布局列表
714 714
      */
@@ -716,7 +716,7 @@ class IndexLogic extends Common
716 716
     {
717 717
         $data = [];
718 718
         $list = db('crm_dashboard')->where('user_id', $param['user_id'])->find();
719
-
719
+        
720 720
         if ($list) {
721 721
             $data = unserialize($list['dashboard']);
722 722
             return $data ?: [];
@@ -730,7 +730,7 @@ class IndexLogic extends Common
730 730
             $data['left'][2]['modelId'] = 7;
731 731
             $data['left'][2]['list'] = 1;
732 732
             $data['left'][2]['isHidden'] = 0;
733
-
733
+            
734 734
             $data['right'][0]['modelId'] = 2;
735 735
             $data['right'][0]['list'] = 2;
736 736
             $data['right'][0]['isHidden'] = 0;
@@ -742,16 +742,16 @@ class IndexLogic extends Common
742 742
             $data['right'][2]['isHidden'] = 0;
743 743
             return $data;
744 744
         }
745
-
745
+        
746 746
     }
747
-
747
+    
748 748
     /**
749 749
      * 修改自定义仪表盘
750 750
      * @param $param
751 751
      */
752 752
     public function updateDashboard($param)
753 753
     {
754
-
754
+        
755 755
         $data = db('crm_dashboard')->where('user_id', $param['user_id'])->find();
756 756
         if ($data) {
757 757
             $list = db('crm_dashboard')->where('user_id', $param['user_id'])->update(['dashboard' => serialize($param['dashboard'])]);
@@ -760,9 +760,9 @@ class IndexLogic extends Common
760 760
             $list = db('crm_dashboard')->insert(['user_id' => $param['user_id'], 'dashboard' => serialize($param['dashboard'])]);
761 761
             return $list;
762 762
         }
763
-
763
+        
764 764
     }
765
-
765
+    
766 766
     /**
767 767
      * 跟进记录列表
768 768
      * @param $param
@@ -815,7 +815,7 @@ class IndexLogic extends Common
815 815
                 $end_time = $param['end_time'] ? strtotime($param['end_time'] . ' 23:59:59') : strtotime(date('Y-m-01', time()) . ' +1 month -1 day');
816 816
                 $type['t.create_time'] = ['between', [$start_time, $end_time]];
817 817
             }
818
-
818
+            
819 819
             if ($param['queryType'] == 0) {
820 820
                 $type['t.type'] = ['in', [1, 4]];
821 821
             } else {
@@ -865,7 +865,7 @@ class IndexLogic extends Common
865 865
                     $list[$k]['business_list'] = $activity_business ?: [];
866 866
                     $list[$k]['contacts_list'] = $activity_contacts ?: [];
867 867
                 }
868
-
868
+                
869 869
                 if ($v['activity_type'] == 3) {
870 870
                     $activity_name = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->find();
871 871
                     $list[$k]['activity_type_name'] = $activity_name['name'];
@@ -910,7 +910,12 @@ class IndexLogic extends Common
910 910
                 $dataInfo['contractList'] = $relation_list['contract_list'] ?: [];
911 911
                 $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
912 912
                 $list[$k]['dataInfo'] = $dataInfo ?: [];
913
-
913
+                
914
+                $list[$k]['relation'] = arrayToString(array_column($relationArr['businessList'], 'name')) . ' ' .
915
+                    arrayToString(array_column($relationArr['contactsList'], 'name')) . ' ' .
916
+                    arrayToString(array_column($relationArr['contractList'], 'name')) . ' ' .
917
+                    arrayToString(array_column($relationArr['customerList'], 'name'));
918
+                
914 919
             }
915 920
         } else {
916 921
             $list = db('crm_activity')
@@ -937,7 +942,7 @@ class IndexLogic extends Common
937 942
                     $list[$k]['business_list'] = $activity_business ?: [];
938 943
                     $list[$k]['contacts_list'] = $activity_contacts ?: [];
939 944
                 }
940
-
945
+                
941 946
                 if ($param['activity_type'] == 3) {
942 947
                     $activity_name = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->find();
943 948
                     $list[$k]['activity_type_name'] = $activity_name['name'];
@@ -982,10 +987,12 @@ class IndexLogic extends Common
982 987
                 $dataInfo['contractList'] = $relation_list['contract_list'] ?: [];
983 988
                 $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
984 989
                 $list[$k]['dataInfo'] = $dataInfo ?: [];
990
+                $list[$k]['contacts_ids'] = arrayToString(array_column($relationArr['contactsList'], 'name'));
991
+                $list[$k]['business_ids'] = arrayToString(array_column($relationArr['businessList'], 'name'));
985 992
             }
986 993
         }
987
-
988
-
994
+        
995
+        
989 996
         $data = [];
990 997
         $data['list'] = $list;
991 998
         $data['dataCount'] = $dataCount ?: 0;
@@ -999,7 +1006,7 @@ class IndexLogic extends Common
999 1006
             $data['firstPage'] = true;
1000 1007
             $data['lastPage'] = false;
1001 1008
         }
1002
-
1009
+        if(!empty($param['action'])) return $list;
1003 1010
         return $data ?: [];
1004 1011
     }
1005 1012
 }

+ 2
- 2
application/crm/logic/InvoiceLogic.php Zobrazit soubor

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

+ 243
- 0
application/crm/logic/MarketLogic.php Zobrazit soubor

@@ -0,0 +1,243 @@
1
+<?php
2
+namespace app\crm\logic;
3
+
4
+use think\Db;
5
+use think\Validate;
6
+use app\crm\model\Market;
7
+
8
+class MarketLogic{
9
+    /**
10
+     *
11
+     * @param $param
12
+     *
13
+     * @author      alvin guogaobo
14
+     * @version     1.0 版本号
15
+     * @since       2021/4/27 0027 09:46
16
+     */
17
+    public function getDataList($param){
18
+        $userModel = new \app\admin\model\User();
19
+        if($param['search']) {
20
+            $where['market_field_id'] = $param['search'];
21
+        }
22
+            //权限
23
+            $a = 'index';
24
+            $auth_user_ids = $userModel->getUserByPer('crm', 'market', $a);
25
+            $authMap['market.create_user_id'] = ['in', $auth_user_ids];
26
+        $list=db('crm_market')
27
+            ->alias('market')
28
+            ->join('__CRM_MARKET_CATEGORY__ market_category','market_category.r_id=market.market_field_id')
29
+            ->where($where)
30
+            ->where($authMap)
31
+            ->page($param['page'],$param['limit'])
32
+            ->order()
33
+            ->select();
34
+        return $list;
35
+    }
36
+    
37
+    /**
38
+     *
39
+     * @author      alvin guogaobo
40
+     * @version     1.0 版本号
41
+     * @since       2021/4/27 0027 09:46
42
+     */
43
+    public function marketList(){
44
+        $list=db('admin_market')->where('status',1)->field('types,name')->select();
45
+        $data=[
46
+            0=>[
47
+            'name'=>'客户',
48
+            'types'=>'crm_customer'
49
+        ],
50
+            1=>[
51
+                'name'=>'线索',
52
+                'types'=>'crm_leads'
53
+            ]
54
+        ];
55
+        $data=array_merge($data,$list);
56
+        return $data;
57
+    }
58
+    public function createData($param){
59
+        $fieldModel = new \app\admin\model\Field();
60
+        $dataInfo = db('crm_market')->where(['name' => $param['name']])->find();
61
+        if (isset($dataInfo)) {
62
+            // 自动验证
63
+            $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
64
+            $validate = new Validate($validateArr['rule'], $validateArr['message']);
65
+        
66
+            $result = $validate->check($param);
67
+            if (!$result) {
68
+                $this->error = $validate->getError();
69
+                return false;
70
+            }
71
+        }
72
+        if (db('crm_market')->data($param)->allowField(true)->isUpdate(false)->save()) {
73
+            updateActionLog($param['create_user_id'], 'crm_market', $this->product_id, '', '', '创建了市场活动');
74
+            RecordActionLog($param['create_user_id'], 'crm_market', 'save', $param['name'], '', '', '新增了市场活动' . $param['name']);
75
+            $data = [];
76
+            $data['product_id'] = $this->product_id;
77
+            return $data;
78
+        } else {
79
+            $this->error = '添加失败';
80
+            return false;
81
+        }
82
+    }
83
+    
84
+    /**
85
+     * 修改
86
+     * @param $param
87
+     * @param string $market_id
88
+     *
89
+     * @author      alvin guogaobo
90
+     * @version     1.0 版本号
91
+     * @since       2021/4/27 0027 15:57
92
+     */
93
+    public function updateDataById($param,$market_id = ''){
94
+        $fieldModel = new \app\admin\model\Field();
95
+        $dataInfo = db('crm_market')->where(['market_id' => $market_id])->find();
96
+        if (isset($dataInfo)) {
97
+            // 自动验证
98
+            $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
99
+            $validate = new Validate($validateArr['rule'], $validateArr['message']);
100
+        
101
+            $result = $validate->check($param);
102
+            if (!$result) {
103
+                $this->error = $validate->getError();
104
+                return false;
105
+            }
106
+        }
107
+        $param['market_id'] = $market_id;
108
+        if (db('crm_market')->update($param, ['market_id' => $market_id], true)) {
109
+            updateActionLog($param['create_user_id'], 'crm_market', $this->market_id, '', '', '编辑了市场活动');
110
+            RecordActionLog($param['create_user_id'], 'crm_market', 'update', $param['name'], '', '', '编辑了市场活动' . $param['name']);
111
+            $data = [];
112
+            $data['market_id'] = $this->market_id;
113
+            return $data;
114
+        } else {
115
+            $this->error = '添加失败';
116
+            return false;
117
+        }
118
+    }
119
+    
120
+    /**
121
+     * 删除
122
+     * @param $id_list
123
+     *
124
+     * @author      alvin guogaobo
125
+     * @version     1.0 版本号
126
+     * @since       2021/4/28 0028 10:48
127
+     */
128
+    public function delete($id_list){
129
+        $marketModel = model('Market');
130
+        // 错误信息
131
+        $delIds = [];
132
+        $error_message = [];
133
+        // 过滤后的ID
134
+        $id_list_filter = db('crm_market')->where(['market_id' => ['IN', $id_list]])->column('market_id');
135
+        $diff = array_diff($id_list, $id_list_filter);
136
+        if (!empty($diff)) {
137
+            foreach ($diff as $key => $val) {
138
+                $error_message[] = sprintf('ID为 %d 的活动删除失败,错误原因:数据不存在或已删除。', $val);
139
+            }
140
+            array_unshift($error_message, '数据已更新,刷新页面后重试!');
141
+            return resultArray(['error' => $error_message]);
142
+        }
143
+        //数据权限判断
144
+        $userModel = new \app\admin\model\User();
145
+        $auth_user_ids = $userModel->getUserByPer('crm', 'market', 'delete');
146
+        foreach ($id_list as $k => $v) {
147
+            $isDel = true;
148
+            //数据详情
149
+            $data = $this->getDataById($v);
150
+            if (!in_array($data['create_user_id'], $auth_user_ids)) {
151
+                $isDel = false;
152
+                $errorMessage[] = '名称为' . $data['name'] . '的活动删除失败,错误原因:无权操作';
153
+            }
154
+            if ($isDel) {
155
+                $delIds[] = $v;
156
+            }
157
+        }
158
+        $dataInfo = db('crm_market')->where('market_id',['in',$delIds])->select();
159
+        if ($delIds) {
160
+            // 软删除数据
161
+            $res = $marketModel::destroy(['market_id' => ['IN', $delIds]]);
162
+            if ($res == count($delIds)) {
163
+                // 添加删除记录
164
+                $userInfo = $this->userInfo;
165
+                foreach ($dataInfo as $k => $v) {
166
+                    RecordActionLog($id_list['user_id'], 'crm_market', 'delete', $v['name'], '', '', '删除了活动:' . $v['name']);
167
+                }
168
+                return resultArray(['data' => '删除成功']);
169
+            } else {
170
+                return resultArray(['error' => '删除失败']);
171
+            }
172
+        }
173
+        if ($errorMessage) {
174
+            return resultArray(['error' => $errorMessage]);
175
+        } else {
176
+            return resultArray(['data' => '删除成功']);
177
+        }
178
+    }
179
+    
180
+    /**
181
+     * 基本信息
182
+     * @param string $id
183
+     * @param int $userId
184
+     *
185
+     * @author      alvin guogaobo
186
+     * @version     1.0 版本号
187
+     * @since       2021/4/27 0027 18:03
188
+     */
189
+    public function getDataById($id = '', $userId = 0)
190
+    {
191
+        $map['market_id'] = $id;
192
+        $dataInfo = db('crm_market')->where($map)->find();
193
+        if (!$dataInfo) {
194
+            $this->error = '暂无此数据';
195
+            return false;
196
+        }
197
+        
198
+        # 获取封面图片
199
+        $dataInfo['cover_images'] = $this->getMarketImages($dataInfo['cover_images']);
200
+        # 获取详情图片
201
+        $dataInfo['details_images'] = $this->getMarketImages($dataInfo['details_images']);
202
+        
203
+        $userModel = new \app\admin\model\User();
204
+        $dataInfo['create_user_id_info'] = $userModel->getUserById($dataInfo['create_user_id']);
205
+    
206
+        $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
207
+        $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
208
+        // 字段授权
209
+        if (!empty($userId)) {
210
+            $grantData = getFieldGrantData($userId);
211
+            $userLevel = isSuperAdministrators($userId);
212
+            foreach ($dataInfo as $key => $value) {
213
+                if (!$userLevel && !empty($grantData['crm_market'])) {
214
+                    $status = getFieldGrantStatus($key, $grantData['crm_market']);
215
+                    # 查看权限
216
+                    if ($status['read'] == 0) unset($dataInfo[$key]);
217
+                }
218
+            }
219
+        }
220
+        return $dataInfo;
221
+    }
222
+    
223
+    /**
224
+     * 获取活动图片
225
+     * @param $fileIds
226
+     *
227
+     * @author      alvin guogaobo
228
+     * @version     1.0 版本号
229
+     * @since       2021/4/28 0028 10:36
230
+     */
231
+    private function getMarketImages($fileIds)
232
+    {
233
+        $files = Db::name('admin_file')->whereIn('file_id', $fileIds)->select();
234
+        
235
+        foreach ($files as $key => $value) {
236
+            $files[$key]['file_path'] = getFullPath($value['file_path']);
237
+            $files[$key]['file_path_thumb'] = getFullPath($value['file_path_thumb']);
238
+            $files[$key]['size'] = format_bytes($value['size']);
239
+        }
240
+        
241
+        return $files;
242
+    }
243
+}

+ 457
- 163
application/crm/logic/PrintingLogic.php Zobrazit soubor

@@ -15,30 +15,35 @@ class PrintingLogic
15 15
     /**
16 16
      * 获取打印数据
17 17
      *
18
-     * @param $type
19
-     * @param $actionId
20
-     * @param $templateId
18
+     * @param int $type 打印模板类型
19
+     * @param int $actionId 操作ID(商机数据ID、合同数据ID、回款数据ID)
20
+     * @param int $templateId 模板ID
21
+     * @param int $recordId 记录ID
22
+     * @author fanqi
23
+     * @since 2021-03-29
21 24
      * @return array|string|string[]
22
-     * @throws \think\db\exception\DataNotFoundException
23
-     * @throws \think\db\exception\ModelNotFoundException
24
-     * @throws \think\exception\DbException
25 25
      */
26
-    public function getPrintingData($type, $actionId, $templateId)
26
+    public function getPrintingData($type, $actionId, $templateId, $recordId)
27 27
     {
28 28
         $result  = [];
29 29
 
30
-        $content = htmlspecialchars_decode(Db::name('admin_printing')->where('id', $templateId)->value('content'));
30
+        $content = Db::name('admin_printing')->where('id', $templateId)->value('content');
31
+        $content = json_decode($content, true);
32
+        $content = $content['data'];
31 33
         $content = str_replace('\n', '', $content);
32 34
         $content = str_replace('\\', '', $content);
33 35
 
34 36
         # 商机模板
35
-        if ($type == 1) $result = $this->getBusinessData($actionId, $content);
37
+        if ($type == 5) $result = $this->getBusinessData($actionId, $content);
36 38
 
37 39
         # 合同模板
38
-        if ($type == 2) $result = $this->getContractData($actionId, $content);
40
+        if ($type == 6) $result = $this->getContractData($actionId, $content);
39 41
 
40 42
         # 回款模板
41
-        if ($type == 3) $result = $this->getReceivablesData($actionId, $content);
43
+        if ($type == 7) $result = $this->getReceivablesData($actionId, $content);
44
+
45
+        # 打印记录
46
+        if ($type == 20) $result = $this->getHistoryData($recordId);
42 47
 
43 48
         return $result;
44 49
     }
@@ -71,6 +76,7 @@ class PrintingLogic
71 76
             'type'        => $param['type'],
72 77
             'action_id'   => $param['action_id'],
73 78
             'template_id' => $param['template_id'],
79
+            'content'     => json_encode(['data' => $param['recordContent']]),
74 80
             'create_time' => time(),
75 81
             'update_time' => time()
76 82
         ];
@@ -95,8 +101,8 @@ class PrintingLogic
95 101
         $limit = !empty($param['limit']) ? $param['limit'] : 15;
96 102
         $page  = !empty($param['page'])  ? $param['page']  : 1;
97 103
 
98
-        $where['type']    = $param['type'];
99
-        $where['user_id'] = $userId;
104
+        $where['action_id'] = $param['typeId'];
105
+        $where['type']      = $param['crmType'];
100 106
 
101 107
         $count = Db::name('crm_printing_record')->where($where)->count();
102 108
         $data  = Db::name('crm_printing_record')->where($where)->limit(($page - 1) * $limit, $limit)->select();
@@ -105,6 +111,7 @@ class PrintingLogic
105 111
             $templateName = Db::name('admin_printing')->where('id', $value['template_id'])->value('name');
106 112
 
107 113
             $result[] = [
114
+                'record_id'     => $value['printing_id'],
108 115
                 'type'          => $value['type'],
109 116
                 'action_id'     => $value['action_id'],
110 117
                 'template_id'   => $value['template_id'],
@@ -128,6 +135,9 @@ class PrintingLogic
128 135
      */
129 136
     private function getBusinessData($id, $content)
130 137
     {
138
+        # 清除无用数据
139
+        $content = preg_replace("/[\t\n\r]+/", "", $content);
140
+        
131 141
         # 查询商机数据
132 142
         $businessData = Db::name('crm_business')->where('business_id', $id)->find();
133 143
         # 查询商机状态组
@@ -137,80 +147,158 @@ class PrintingLogic
137 147
         # 查询客户数据
138 148
         $customerData = Db::name('crm_customer')->where('customer_id', $businessData['customer_id'])->find();
139 149
         # 查询产品数据
140
-        $businessProduct = Db::name('crm_business_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal'])->where('business_id', $businessData['business_id'])->select();
150
+        $businessProduct = Db::name('crm_business_product')->where('business_id', $businessData['business_id'])->select();
141 151
         $productIdArray = [];
142
-        $productInfo    = [];
143 152
         foreach ($businessProduct AS $key => $value) {
144 153
             $productIdArray[] = $value['product_id'];
145
-            $productInfo[$value['product_id']] = $value;
146 154
         }
147 155
         $productList = Db::name('crm_product')->whereIn('product_id', $productIdArray)->select();
156
+        $productInfo = [];
157
+        foreach ($productList AS $key => $value) {
158
+            $productInfo[$value['product_id']] = $value;
159
+        }
160
+        # 产品类别数据
161
+        $productCategoryList = db('crm_product_category')->select();
162
+        $productCategoryData = [];
163
+        foreach ($productCategoryList AS $key => $value) {
164
+            $productCategoryData[$value['category_id']] = $value['name'];
165
+        }
148 166
         # 创建人
149 167
         $createUserName = Db::name('admin_user')->where('id', $businessData['create_user_id'])->value('realname');
150 168
         # 负责人
151 169
         $ownerUserName  = Db::name('admin_user')->where('id', $businessData['owner_user_id'])->value('realname');
170
+        # 产品自定义字段
171
+        $productFields = db('admin_field')->field(['field', 'name', 'form_type'])->where('types', 'crm_product')->select();
172
+
173
+        # 产品数据替换
174
+        preg_match_all('/<tr data-wk-table-tr-tag="value">(.*)<\/tr>/mU', $content, $productHtml);
175
+        if (!empty($productHtml[1])) {
176
+            foreach ($productHtml[1] AS $k => $v) {
177
+                if (empty($productHtml[0][$k])) continue;
178
+
179
+                $oldHtml     = $productHtml[0][$k]; # 保留旧HTML数据,用于str_str_replace函数查找替换
180
+                $replaceHtml = ''; # 要替换的HTML数据
181
+                foreach ($businessProduct AS $key => $value) {
182
+                    $replaceHtml .= '<tr data-wk-table-tr-tag="value">';
183
+                    $detail = str_replace('{产品名称}', $productInfo[$value['product_id']]['name'], $productHtml[1][$k]);
184
+                    $detail = str_replace('{产品编码}', $productInfo[$value['product_id']]['num'], $detail);
185
+                    $detail = str_replace('{单位}', $value['unit'], $detail);
186
+                    $detail = str_replace('{标准价格}', $value['price'], $detail);
187
+                    $detail = str_replace('{产品描述}', $productInfo[$value['product_id']]['description'], $detail);
188
+                    $detail = str_replace('{售价}', $value['sales_price'], $detail);
189
+                    $detail = str_replace('{数量}', (int)$value['num'], $detail);
190
+                    $detail = str_replace('{折扣}', (int)$value['discount'].'%', $detail);
191
+                    $detail = str_replace('{合计}', $value['subtotal'], $detail);
192
+                    foreach ($productFields AS $key1 => $value1) {
193
+                        switch ($value1['form_type']) {
194
+                            case 'user' :
195
+                                $productUsers = db('admin_user')->whereIn('id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('realname');
196
+                                $detail = str_replace('{'.$value1['name'].'}', implode(',', $productUsers), $detail);
197
+                                break;
198
+                            case 'structure' :
199
+                                $productStructure = db('admin_structure')->whereIn('id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('name');
200
+                                $detail = str_replace('{'.$value1['name'].'}', implode(',', $productStructure), $detail);
201
+                                break;
202
+                            case 'file' :
203
+                                $productFiles = db('admin_file')->whereIn('file_id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('name');
204
+                                $detail = str_replace('{'.$value1['name'].'}', implode(',', $productFiles), $detail);
205
+                                break;
206
+                            case 'datetime' :
207
+                                $productDatetime = !empty($productInfo[$value['product_id']][$value1['field']]) ? date('Y-m-d H:i:s', $productInfo[$value['product_id']][$value1['field']]) : '';
208
+                                $detail = str_replace('{'.$value1['name'].'}', $productDatetime, $detail);
209
+                                break;
210
+                            case 'category' :
211
+                                $categoryId = $productInfo[$value['product_id']]['category_id'];
212
+                                $detail = str_replace('{'.$value1['name'].'}', !empty($productCategoryData[$categoryId]) ? $productCategoryData[$categoryId] : '', $detail);
213
+                                break;
214
+                            default :
215
+                                $detail = str_replace('{'.$value1['name'].'}', trim($productInfo[$value['product_id']][$value1['field']], ','), $detail);
216
+                        }
217
+                    }
152 218
 
153
-        # 商机模板数据替换
154
-        $content = str_replace('{商机名称}', $businessData['name'], $content);
219
+                    if (strstr($detail, '{产品类别}')) {
220
+                        $categoryNam = Db::name('crm_product_category')->where('category_id', $productInfo[$value['product_id']]['category_id'])->value('name');
221
+                        $detail = str_replace('{产品类别}', $categoryNam, $detail);
222
+                    }
223
+
224
+                    $replaceHtml .= $detail . '</tr>';
225
+                }
226
+
227
+                $content = str_replace($oldHtml, $replaceHtml, $content);
228
+            }
229
+        }
230
+
231
+        # 替换商机数据
155 232
         $content = str_replace('{商机状态组}', $businessType, $content);
156 233
         $content = str_replace('{商机阶段}', $businessStatus, $content);
157
-        $content = str_replace('{商机金额}', $businessData['money'], $content);
158
-        $content = str_replace('{预计成交日期}', $businessData['deal_date'], $content);
159
-        $content = str_replace('{备注}', $businessData['remark'], $content);
160 234
         $content = str_replace('{负责人}', $createUserName, $content);
161 235
         $content = str_replace('{创建人}', $ownerUserName, $content);
162 236
         $content = str_replace('{创建日期}', date('Y-m-d H:i:s', $businessData['create_time']), $content);
163 237
         $content = str_replace('{更新日期}', date('Y-m-d H:i:s', $businessData['update_time']), $content);
164
-
165
-        # 客户模板数据替换
166
-        $content = str_replace('{客户名称}', $customerData['name'], $content);
167
-        $content = str_replace('{客户级别}', $customerData['level'], $content);
168
-        $content = str_replace('{客户行业}', $customerData['industry'], $content);
169
-        $content = str_replace('{客户来源}', $businessStatus, $content);
170
-        $content = str_replace('{成交状态}', $customerData['deal_status'], $content);
171
-        $content = str_replace('{电话}', $customerData['telephone'], $content);
172
-        $content = str_replace('{网址}', $customerData['website'], $content);
173
-        $content = str_replace('{手机}', $customerData['mobile'], $content);
174
-
175
-        # 产品模板数据替换
176
-        preg_match_all('/(data-wk-table-tr-tag="value")>(.*)<\/tr>/mU', $content, $productHtml);
177
-        if (!empty($productHtml[2])) {
178
-            # 循环匹配到的HTML数据
179
-            foreach ($productHtml[2] AS $key => $value) {
180
-                # 循环产品数据
181
-                $oldHtml     = $productHtml[0][$key]; # 保留旧HTML数据,用于str_str_replace函数查找替换
182
-                $replaceHtml = '';
183
-                foreach ($productList AS $k => $v) {
184
-                    if ($k == 0) {
185
-                        $replaceHtml .= 'data-wk-table-tr-tag="value">';
186
-                    } else {
187
-                        $replaceHtml .= '<tr data-wk-table-tr-tag="value">';
188
-                    }
189
-                    $value = str_replace('{产品名称}', $v['name'], $value);
190
-                    $value = str_replace('{产品编码}', $v['num'], $value);
191
-                    $value = str_replace('{单位}', $v['unit'], $value);
192
-                    $value = str_replace('{标准价格}', $v['price'], $value);
193
-                    $value = str_replace('{产品描述}', $v['description'], $value);
194
-                    $value = str_replace('{售价}', $productInfo[$v['product_id']]['sales_price'], $value);
195
-                    $value = str_replace('{数量}', $productInfo[$v['product_id']]['num'], $value);
196
-                    $value = str_replace('{折扣}', $productInfo[$v['product_id']]['discount'], $value);
197
-                    $value = str_replace('{整单折扣}', $businessData['discount_rate'], $value);
198
-                    $value = str_replace('{合计}', $productInfo[$v['product_id']]['subtotal'], $value);
199
-
200
-                    if (strstr($value, '{产品类别}')) {
201
-                        $categoryNam = Db::name('crm_product_category')->where('category_id', $v['category_id'])->value('name');
202
-                        $value = str_replace('{产品类别}', $categoryNam, $value);
203
-                    }
204
-
205
-                    $replaceHtml .= $value . '</tr>';
238
+        $businessFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_business')->select();
239
+        foreach ($businessFields AS $key => $value) {
240
+            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);
241
+            if (!empty($businessHtml[0])) {
242
+                $businessSourceData = $businessHtml[0];
243
+                switch ($value['form_type']) {
244
+                    case 'user' :
245
+                        $businessUsers = db('admin_user')->whereIn('id', trim($businessData[$value['field']], ','))->column('realname');
246
+                        $businessTargetData = str_replace('{'.$value['name'].'}', implode(',', $businessUsers), $businessHtml[0]);
247
+                        break;
248
+                    case 'structure' :
249
+                        $businessStructure = db('admin_structure')->whereIn('id', trim($businessData[$value['field']], ','))->column('name');
250
+                        $businessTargetData = str_replace('{'.$value['name'].'}', implode(',', $businessStructure), $businessHtml[0]);
251
+                        break;
252
+                    case 'file' :
253
+                        $businessFiles = db('admin_file')->whereIn('file_id', trim($businessData[$value['field']], ','))->column('name');
254
+                        $businessTargetData = str_replace('{'.$value['name'].'}', implode(',', $businessFiles), $businessHtml[0]);
255
+                        break;
256
+                    case 'datetime' :
257
+                        $businessDatetime = !empty($businessData[$value['field']]) ? date('Y-m-d H:i:s', $businessData[$value['field']]) : '';
258
+                        $businessTargetData = str_replace('{'.$value['name'].'}', $businessDatetime, $businessHtml[0]);
259
+                        break;
260
+                    default :
261
+                        $businessTargetData = str_replace('{'.$value['name'].'}', trim($businessData[$value['field']], ','), $businessHtml[0]);
206 262
                 }
263
+                $content = str_replace($businessSourceData, $businessTargetData, $content);
264
+            }
265
+        }
207 266
 
208
-                $content = str_replace($oldHtml, $replaceHtml, $content);
267
+        # 替换客户数据
268
+        $content = str_replace('{详细地址}', $customerData['detail_address'], $content);
269
+        $content = str_replace('{区域}', $customerData['address'], $content);
270
+        $customerFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_customer')->select();
271
+        foreach ($customerFields AS $key => $value) {
272
+            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);
273
+            if (!empty($customerHtml[0])) {
274
+                $customerSourceData = $customerHtml[0];
275
+                switch ($value['form_type']) {
276
+                    case 'user' :
277
+                        $customerUsers = db('admin_user')->whereIn('id', trim($customerData[$value['field']], ','))->column('realname');
278
+                        $customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerUsers), $customerHtml[0]);
279
+                        break;
280
+                    case 'structure' :
281
+                        $customerStructure = db('admin_structure')->whereIn('id', trim($customerData[$value['field']], ','))->column('name');
282
+                        $customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerStructure), $customerHtml[0]);
283
+                        break;
284
+                    case 'file' :
285
+                        $customerFiles = db('admin_file')->whereIn('file_id', trim($customerData[$value['field']], ','))->column('name');
286
+                        $customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerFiles), $customerHtml[0]);
287
+                        break;
288
+                    case 'datetime' :
289
+                        $customerDatetime = !empty($customerData[$value['field']]) ? date('Y-m-d H:i:s', $customerData[$value['field']]) : '';
290
+                        $customerTargetData = str_replace('{'.$value['name'].'}', $customerDatetime, $customerHtml[0]);
291
+                        break;
292
+                    default :
293
+                        $customerTargetData = str_replace('{'.$value['name'].'}', trim($customerData[$value['field']], ','), $customerHtml[0]);
294
+                }
295
+                $content = str_replace($customerSourceData, $customerTargetData, $content);
209 296
             }
210 297
         }
211 298
 
212 299
         # 替换整单折扣
213
-        $content = str_replace('{整单折扣}', $businessData['discount_rate'], $content);
300
+        $content = str_replace('{整单折扣}', (int)$businessData['discount_rate'].'%', $content);
301
+        $content = str_replace('{产品总金额}', $businessData['money'], $content);
214 302
 
215 303
         return $content;
216 304
     }
@@ -227,6 +315,9 @@ class PrintingLogic
227 315
      */
228 316
     private function getContractData($id, $content)
229 317
     {
318
+        # 清除无用数据
319
+        $content = preg_replace("/[\t\n\r]+/", "", $content);
320
+
230 321
         # 查询合同数据
231 322
         $contractData = Db::name('crm_contract')->where('contract_id', $id)->find();
232 323
         # 查询商机数据
@@ -236,18 +327,21 @@ class PrintingLogic
236 327
         # 查询联系人数据
237 328
         $contactsData = Db::name('crm_contacts')->where('contacts_id', $contractData['contacts_id'])->find();
238 329
         # 查询产品数据
239
-        $businessProduct = Db::name('crm_business_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal'])->where('business_id', $contractData['business_id'])->select();
330
+        $businessProduct = Db::name('crm_business_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal', 'unit'])->where('business_id', $contractData['business_id'])->select();
240 331
         $productIdArray = [];
241
-        $productInfo    = [];
242 332
         foreach ($businessProduct AS $key => $value) {
243 333
             $productIdArray[] = $value['product_id'];
244
-            $productInfo[$value['product_id']] = $value;
245 334
         }
246 335
         $productList = Db::name('crm_product')->whereIn('product_id', $productIdArray)->select();
336
+        $productInfo = [];
337
+        foreach ($productList AS $key => $value) {
338
+            $productInfo[$value['product_id']] = $value;
339
+        }
247 340
         # 回款金额
248 341
         $receivablesModel = new \app\crm\model\Receivables();
249 342
         $moneyInfo        = $receivablesModel->getMoneyByContractId($contractData['contract_id']);
250
-        $doneMoney        = $moneyInfo['doneMoney'] ? : 0.00;
343
+        $doneMoney        = !empty($moneyInfo['doneMoney']) ? $moneyInfo['doneMoney'] : 0.00;
344
+        $unMoney          = $moneyInfo['contractMoney'] - $doneMoney > 0 ? $moneyInfo['contractMoney'] - $doneMoney : 0.00;
251 345
         # 合同签约人
252 346
         $signerString = '';
253 347
         $signerArray = Db::name('admin_user')->field('realname')->whereIn('id', $contractData['order_user_id'])->select();
@@ -256,26 +350,112 @@ class PrintingLogic
256 350
         $createUserName = Db::name('admin_user')->where('id', $contractData['create_user_id'])->value('realname');
257 351
         # 负责人
258 352
         $ownerUserName  = Db::name('admin_user')->where('id', $contractData['owner_user_id'])->value('realname');
353
+        # 合同附件
354
+        $fileList = Db::name('crm_contract_file')->alias('contract')->join('__ADMIN_FILE__ file', 'file.file_id = contract.file_id', 'left')
355
+            ->where('contract.contract_id', $id)->column('file.file_path');
356
+        $fileInfo = [];
357
+        foreach ($fileList AS $key => $value) {
358
+            $fileInfo[] = getFullPath($value['file_path']);
359
+        }
360
+        # 产品类别数据
361
+        $productCategoryList = db('crm_product_category')->select();
362
+        $productCategoryData = [];
363
+        foreach ($productCategoryList AS $key => $value) {
364
+            $productCategoryData[$value['category_id']] = $value['name'];
365
+        }
366
+        # 产品自定义字段
367
+        $productFields = db('admin_field')->field(['field', 'name', 'form_type'])->where('types', 'crm_product')->select();
259 368
 
260
-        # 客户模板数据替换
261
-        $content = str_replace('{客户名称}', $customerData['name'], $content);
262
-        $content = str_replace('{客户级别}', $customerData['level'], $content);
263
-        $content = str_replace('{客户行业}', $customerData['industry'], $content);
264
-        $content = str_replace('{客户来源}', $customerData['source'], $content);
265
-        $content = str_replace('{成交状态}', $customerData['deal_status'], $content);
266
-        $content = str_replace('{网址}', $customerData['website'], $content);
267
-        $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);
268
-        $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);
269
-
270
-        # 合同模板数据替换
271
-        $content = str_replace('{合同编号}', $contractData['num'], $content);
272
-        $content = str_replace('{合同名称}', $contractData['name'], $content);
273
-        $content = str_replace('{客户名称}', $customerData['name'], $content);
369
+        # 产品模板数据替换
370
+        preg_match_all('/<tr data-wk-table-tr-tag="value">(.*)<\/tr>/mU', $content, $productHtml);
371
+        if (!empty($productHtml[1])) {
372
+            foreach ($productHtml[1] AS $k => $v) {
373
+                $oldHtml     = $productHtml[0][$k]; # 保留旧HTML数据,用于str_str_replace函数查找替换
374
+                $replaceHtml = ''; # 要替换的HTML数据
375
+                foreach ($businessProduct AS $key => $value) {
376
+                    $replaceHtml .= '<tr data-wk-table-tr-tag="value">';
377
+                    $detail = str_replace('{产品名称}', $productInfo[$value['product_id']]['name'], $productHtml[1][$k]);
378
+                    $detail = str_replace('{产品编码}', $productInfo[$value['product_id']]['num'], $detail);
379
+                    $detail = str_replace('{单位}', $value['unit'], $detail);
380
+                    $detail = str_replace('{标准价格}', $value['price'], $detail);
381
+                    $detail = str_replace('{产品描述}', $productInfo[$value['product_id']]['description'], $detail);
382
+                    $detail = str_replace('{售价}', $value['sales_price'], $detail);
383
+                    $detail = str_replace('{数量}', (int)$value['num'], $detail);
384
+                    $detail = str_replace('{折扣}', (int)$value['discount'].'%', $detail);
385
+                    $detail = str_replace('{合计}', $value['subtotal'], $detail);
386
+                    foreach ($productFields AS $key1 => $value1) {
387
+                        switch ($value1['form_type']) {
388
+                            case 'user' :
389
+                                $productUsers = db('admin_user')->whereIn('id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('realname');
390
+                                $detail = str_replace('{'.$value1['name'].'}', implode(',', $productUsers), $detail);
391
+                                break;
392
+                            case 'structure' :
393
+                                $productStructure = db('admin_structure')->whereIn('id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('name');
394
+                                $detail = str_replace('{'.$value1['name'].'}', implode(',', $productStructure), $detail);
395
+                                break;
396
+                            case 'file' :
397
+                                $productFiles = db('admin_file')->whereIn('file_id', trim($productInfo[$value['product_id']][$value1['field']], ','))->column('name');
398
+                                $detail = str_replace('{'.$value1['name'].'}', implode(',', $productFiles), $detail);
399
+                                break;
400
+                            case 'datetime' :
401
+                                $productDatetime = !empty($productInfo[$value['product_id']][$value1['field']]) ? date('Y-m-d H:i:s', $productInfo[$value['product_id']][$value1['field']]) : '';
402
+                                $detail = str_replace('{'.$value1['name'].'}', $productDatetime, $detail);
403
+                                break;
404
+                            case 'category' :
405
+                                $categoryId = $productInfo[$value['product_id']]['category_id'];
406
+                                $detail = str_replace('{'.$value1['name'].'}', !empty($productCategoryData[$categoryId]) ? $productCategoryData[$categoryId] : '', $detail);
407
+                                break;
408
+                            default :
409
+                                $detail = str_replace('{'.$value1['name'].'}', trim($productInfo[$value['product_id']][$value1['field']], ','), $detail);
410
+                        }
411
+                    }
412
+
413
+                    if (strstr($detail, '{产品类别}')) {
414
+                        $categoryNam = Db::name('crm_product_category')->where('category_id', $productInfo[$value['product_id']]['category_id'])->value('name');
415
+                        $detail = str_replace('{产品类别}', $categoryNam, $detail);
416
+                    }
417
+
418
+                    $replaceHtml .= $detail . '</tr>';
419
+                }
420
+                $content = str_replace($oldHtml, $replaceHtml, $content);
421
+            }
422
+        }
423
+
424
+        # 替换客户数据
425
+        $content = str_replace('{详细地址}', $customerData['detail_address'], $content);
426
+        $content = str_replace('{区域}', $customerData['address'], $content);
427
+        $customerFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_customer')->select();
428
+        foreach ($customerFields AS $key => $value) {
429
+            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);
430
+            if (!empty($customerHtml[0])) {
431
+                $customerSourceData = $customerHtml[0];
432
+                switch ($value['form_type']) {
433
+                    case 'user' :
434
+                        $customerUsers = db('admin_user')->whereIn('id', trim($customerData[$value['field']], ','))->column('realname');
435
+                        $customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerUsers), $customerHtml[0]);
436
+                        break;
437
+                    case 'structure' :
438
+                        $customerStructure = db('admin_structure')->whereIn('id', trim($customerData[$value['field']], ','))->column('name');
439
+                        $customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerStructure), $customerHtml[0]);
440
+                        break;
441
+                    case 'file' :
442
+                        $customerFiles = db('admin_file')->whereIn('file_id', trim($customerData[$value['field']], ','))->column('name');
443
+                        $customerTargetData = str_replace('{'.$value['name'].'}', implode(',', $customerFiles), $customerHtml[0]);
444
+                        break;
445
+                    case 'datetime' :
446
+                        $customerDatetime = !empty($customerData[$value['field']]) ? date('Y-m-d H:i:s', $customerData[$value['field']]) : '';
447
+                        $customerTargetData = str_replace('{'.$value['name'].'}', $customerDatetime, $customerHtml[0]);
448
+                        break;
449
+                    default :
450
+                        $customerTargetData = str_replace('{'.$value['name'].'}', trim($customerData[$value['field']], ','), $customerHtml[0]);
451
+                }
452
+                $content = str_replace($customerSourceData, $customerTargetData, $content);
453
+            }
454
+        }
455
+
456
+        # 替换合同数据
274 457
         $content = str_replace('{商机名称}', $businessData['name'], $content);
275
-        $content = str_replace('{下单时间}', $contractData['order_date'], $content);
276
-        $content = str_replace('{合同金额}', $contractData['money'], $content);
277
-        $content = str_replace('{合同开始时间}', $contractData['start_time'], $content);
278
-        $content = str_replace('{合同到期时间}', $contractData['end_time'], $content);
458
+        $content = str_replace('{合同附件}', implode(' | ', $fileInfo), $content);
279 459
         $content = str_replace('{客户签约人}', $contactsData['name'], $content);
280 460
         $content = str_replace('{公司签约人}', trim($signerString, '、'), $content);
281 461
         $content = str_replace('{负责人}', $createUserName, $content);
@@ -283,60 +463,70 @@ class PrintingLogic
283 463
         $content = str_replace('{创建日期}', date('Y-m-d H:i:s', $contractData['create_time']), $content);
284 464
         $content = str_replace('{更新日期}', date('Y-m-d H:i:s', $contractData['update_time']), $content);
285 465
         $content = str_replace('{已收款金额}', $doneMoney, $content);
286
-        $content = str_replace('{未收款金额}', $contractData['money'] - $doneMoney, $content);
287
-        $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);
466
+        $content = str_replace('{未收款金额}', $unMoney, $content);
467
+        $contractFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_contract')->select();
468
+        foreach ($contractFields AS $key => $value) {
469
+            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);
470
+            if (!empty($contractHtml[0])) {
471
+                $contractSourceData = $contractHtml[0];
472
+                switch ($value['form_type']) {
473
+                    case 'user' :
474
+                        $contractUsers = db('admin_user')->whereIn('id', trim($contractData[$value['field']], ','))->column('realname');
475
+                        $contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractUsers), $contractHtml[0]);
476
+                        break;
477
+                    case 'structure' :
478
+                        $contractStructure = db('admin_structure')->whereIn('id', trim($contractData[$value['field']], ','))->column('name');
479
+                        $contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractStructure), $contractHtml[0]);
480
+                        break;
481
+                    case 'file' :
482
+                        $contractFiles = db('admin_file')->whereIn('file_id', trim($contractData[$value['field']], ','))->column('name');
483
+                        $contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractFiles), $contractHtml[0]);
484
+                        break;
485
+                    case 'datetime' :
486
+                        $contractDatetime = !empty($contractData[$value['field']]) ? date('Y-m-d H:i:s', $contractData[$value['field']]) : '';
487
+                        $contractTargetData = str_replace('{'.$value['name'].'}', $contractDatetime, $contractHtml[0]);
488
+                        break;
489
+                    default :
490
+                        $contractTargetData = str_replace('{'.$value['name'].'}', trim($contractData[$value['field']], ','), $contractHtml[0]);
491
+                }
492
+                $content = str_replace($contractSourceData, $contractTargetData, $content);
493
+            }
494
+        }
288 495
 
289
-        # 联系人模板替换
290
-        $content = str_replace('{姓名}', $contactsData['name'], $content);
496
+        # 替换联系人数据
291 497
         $content = str_replace('{客户名称}', $customerData['name'], $content);
292
-        $content = str_replace('{电子邮箱}', $contactsData['email'], $content);
293
-        $content = str_replace('{是否关键决策人}', $contactsData['decision'], $content);
294
-        $content = str_replace('{职务}', $contactsData['post'], $content);
295
-        $content = str_replace('{性别}', $contactsData['sex'], $content);
296
-        $content = str_replace('{地址}', $contactsData['detail_address'], $content);
297
-        $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);
298
-        $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);
299
-        $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);
300
-
301
-        # 替换产品模板
302
-        preg_match_all('/(data-wk-table-tr-tag="value")>(.*)<\/tr>/mU', $content, $productHtml);
303
-        if (!empty($productHtml[2])) {
304
-            # 循环匹配到的HTML数据
305
-            foreach ($productHtml[2] AS $key => $value) {
306
-                # 循环产品数据
307
-                $oldHtml     = $productHtml[0][$key]; # 保留旧HTML数据,用于str_str_replace函数查找替换
308
-                $replaceHtml = '';
309
-                foreach ($productList AS $k => $v) {
310
-                    if ($k == 0) {
311
-                        $replaceHtml .= 'data-wk-table-tr-tag="value">';
312
-                    } else {
313
-                        $replaceHtml .= '<tr data-wk-table-tr-tag="value">';
314
-                    }
315
-                    $value = str_replace('{产品名称}', $v['name'], $value);
316
-                    $value = str_replace('{产品编码}', $v['num'], $value);
317
-                    $value = str_replace('{单位}', $v['unit'], $value);
318
-                    $value = str_replace('{标准价格}', $v['price'], $value);
319
-                    $value = str_replace('{产品描述}', $v['description'], $value);
320
-                    $value = str_replace('{售价}', $productInfo[$v['product_id']]['sales_price'], $value);
321
-                    $value = str_replace('{数量}', $productInfo[$v['product_id']]['num'], $value);
322
-                    $value = str_replace('{折扣}', $productInfo[$v['product_id']]['discount'], $value);
323
-                    $value = str_replace('{整单折扣}', $businessData['discount_rate'], $value);
324
-                    $value = str_replace('{合计}', $productInfo[$v['product_id']]['subtotal'], $value);
325
-
326
-                    if (strstr($value, '{产品类别}')) {
327
-                        $categoryNam = Db::name('crm_product_category')->where('category_id', $v['category_id'])->value('name');
328
-                        $value = str_replace('{产品类别}', $categoryNam, $value);
329
-                    }
330
-
331
-                    $replaceHtml .= $value . '</tr>';
498
+        $contactsFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_contacts')->select();
499
+        foreach ($contactsFields AS $key => $value) {
500
+            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);
501
+            if (!empty($contactsHtml[0])) {
502
+                $contactsSourceData = $contactsHtml[0];
503
+                switch ($value['form_type']) {
504
+                    case 'user' :
505
+                        $contactsUsers = db('admin_user')->whereIn('id', trim($contactsData[$value['field']], ','))->column('realname');
506
+                        $contactsTargetData = str_replace('{'.$value['name'].'}', implode(',', $contactsUsers), $contactsHtml[0]);
507
+                        break;
508
+                    case 'structure' :
509
+                        $contactsStructure = db('admin_structure')->whereIn('id', trim($contactsData[$value['field']], ','))->column('name');
510
+                        $contactsTargetData = str_replace('{'.$value['name'].'}', implode(',', $contactsStructure), $contactsHtml[0]);
511
+                        break;
512
+                    case 'file' :
513
+                        $contactsFiles = db('admin_file')->whereIn('file_id', trim($contactsData[$value['field']], ','))->column('name');
514
+                        $contactsTargetData = str_replace('{'.$value['name'].'}', implode(',', $contactsFiles), $contactsHtml[0]);
515
+                        break;
516
+                    case 'datetime' :
517
+                        $contactsDatetime = !empty($contactsData[$value['field']]) ? date('Y-m-d H:i:s', $contactsData[$value['field']]) : '';
518
+                        $contactsTargetData = str_replace('{'.$value['name'].'}', $contactsDatetime, $contactsHtml[0]);
519
+                        break;
520
+                    default :
521
+                        $contactsTargetData = str_replace('{'.$value['name'].'}', trim($contactsData[$value['field']], ','), $contactsHtml[0]);
332 522
                 }
333
-
334
-                $content = str_replace($oldHtml, $replaceHtml, $content);
335 523
             }
524
+            $content = str_replace($contactsSourceData, $contactsTargetData, $content);
336 525
         }
337 526
 
338 527
         # 替换整单折扣
339 528
         $content = str_replace('{整单折扣}', $businessData['discount_rate'], $content);
529
+        $content = str_replace('{产品总金额}', $businessData['money'], $content);
340 530
 
341 531
         return $content;
342 532
     }
@@ -360,7 +550,7 @@ class PrintingLogic
360 550
         # 查询客户数据
361 551
         $customerName = Db::name('crm_customer')->where('customer_id', $receivablesData['customer_id'])->value('name');
362 552
         # 查询商机数据
363
-        $businessName = Db::name('crm_business')->where('business_id', $contractData['business_id'])->find();
553
+        $businessName = Db::name('crm_business')->where('business_id', $contractData['business_id'])->value('name');
364 554
         # 查询联系人数据
365 555
         $contactsName = Db::name('crm_contacts')->where('contacts_id', $contractData['contacts_id'])->value('name');
366 556
         # 合同签约人
@@ -371,46 +561,150 @@ class PrintingLogic
371 561
         $contractCreate = Db::name('admin_user')->where('id', $contractData['create_user_id'])->value('realname');
372 562
         $contractOwner  = Db::name('admin_user')->where('id', $contractData['owner_user_id'])->value('realname');
373 563
         # 回款创建人、负责人
374
-        $receivablesCreate = Db::name('admin_user')->where('id', $contractData['create_user_id'])->value('realname');
375
-        $receivablesOwner  = Db::name('admin_user')->where('id', $contractData['owner_user_id'])->value('realname');
564
+        $receivablesCreate = Db::name('admin_user')->where('id', $receivablesData['create_user_id'])->value('realname');
565
+        $receivablesOwner  = Db::name('admin_user')->where('id', $receivablesData['owner_user_id'])->value('realname');
376 566
         # 回款金额
377 567
         $receivablesModel = new \app\crm\model\Receivables();
378 568
         $moneyInfo        = $receivablesModel->getMoneyByContractId($contractData['contract_id']);
379 569
         $doneMoney        = $moneyInfo['doneMoney'] ? : 0.00;
570
+        # 合同附件
571
+        $fileList = Db::name('crm_contract_file')->alias('contract')->join('__ADMIN_FILE__ file', 'file.file_id = contract.file_id', 'left')
572
+            ->where('contract.contract_id', $id)->column('file.file_path');
573
+        $fileInfo = [];
574
+        foreach ($fileList AS $key => $value) {
575
+            $fileInfo[] = getFullPath($value['file_path']);
576
+        }
577
+        # 期数
578
+        $plan = '';
579
+        if (!empty($receivablesData['plan_id'])) {
580
+            $plan = db('crm_receivables_plan')->where('plan_id', $receivablesData['plan_id'])->value('num');
581
+        }
380 582
 
381
-        # 合同模板数据替换
382
-        $content = str_replace('{合同编号}', $contractData['num'], $content);
383
-        $content = str_replace('{合同名称}', $contractData['name'], $content);
384
-        $content = str_replace('{客户名称}', $customerName, $content);
583
+        # 替换合同数据
385 584
         $content = str_replace('{商机名称}', $businessName, $content);
386
-        $content = str_replace('{下单时间}', $contractData['order_date'], $content);
387
-        $content = str_replace('{合同金额}', $contractData['money'], $content);
388
-        $content = str_replace('{合同开始时间}', $contractData['start_time'], $content);
389
-        $content = str_replace('{合同到期时间}', $contractData['end_time'], $content);
390 585
         $content = str_replace('{客户签约人}', $contactsName, $content);
391 586
         $content = str_replace('{公司签约人}', trim($signerString, '、'), $content);
392
-        $content = str_replace('{已收款金额}', $doneMoney, $content);
393
-        $content = str_replace('{未收款金额}', $contractData['money'] - $doneMoney, $content);
394
-        $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);
395
-        $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);
396
-        $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);
397
-        $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);
398
-        $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);
399
-
400
-        # 回款模板数据替换
401
-        $content = str_replace('{回款编号}', $receivablesData['number'], $content);
587
+        $contractFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_contract')->select();
588
+        foreach ($contractFields AS $key => $value) {
589
+            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);
590
+            if (!empty($contractHtml[0])) {
591
+                $contractSourceData = $contractHtml[0];
592
+                switch ($value['form_type']) {
593
+                    case 'user' :
594
+                        $contractUsers = db('admin_user')->whereIn('id', trim($contractData[$value['field']], ','))->column('realname');
595
+                        $contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractUsers), $contractHtml[0]);
596
+                        break;
597
+                    case 'structure' :
598
+                        $contractStructure = db('admin_structure')->whereIn('id', trim($contractData[$value['field']], ','))->column('name');
599
+                        $contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractStructure), $contractHtml[0]);
600
+                        break;
601
+                    case 'file' :
602
+                        $contractFiles = db('admin_file')->whereIn('file_id', trim($contractData[$value['field']], ','))->column('name');
603
+                        $contractTargetData = str_replace('{'.$value['name'].'}', implode(',', $contractFiles), $contractHtml[0]);
604
+                        break;
605
+                    case 'datetime' :
606
+                        $contractDatetime = !empty($contractData[$value['field']]) ? date('Y-m-d H:i:s', $contractData[$value['field']]) : '';
607
+                        $contractTargetData = str_replace('{'.$value['name'].'}', $contractDatetime, $contractHtml[0]);
608
+                        break;
609
+                    default :
610
+                        $contractTargetData = str_replace('{'.$value['name'].'}', trim($contractData[$value['field']], ','), $contractHtml[0]);
611
+                }
612
+                $content = str_replace($contractSourceData, $contractTargetData, $content);
613
+            }
614
+        }
615
+
616
+        # 替换回款数据
402 617
         $content = str_replace('{客户名称}', $customerName, $content);
403 618
         $content = str_replace('{合同编号}', $contractData['num'], $content);
404
-        $content = str_replace('{回款日期}', $receivablesData['return_time'], $content);
405
-        $content = str_replace('{回款方式}', $receivablesData['return_type'], $content);
406
-        $content = str_replace('{回款金额}', $receivablesData['money'], $content);
407
-        $content = str_replace('{期数}', '0期', $content);
408
-        $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);
409
-        $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);
410
-        $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);
411
-        $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);
412
-        $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);
619
+        $content = str_replace('{创建人}', $receivablesCreate, $content);
620
+        $content = str_replace('{负责人}', $receivablesOwner, $content);
621
+        $content = str_replace('{创建日期}', date('Y-m-d H:i:s', $receivablesData['create_time']), $content);
622
+        $content = str_replace('{更新日期}', date('Y-m-d H:i:s', $receivablesData['update_time']), $content);
623
+        $receivablesFields = db('admin_field')->field(['field', 'form_type', 'name'])->where('types', 'crm_receivables')->select();
624
+        foreach ($receivablesFields AS $key => $value) {
625
+            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);
626
+            if (!empty($receivablesHtml[0])) {
627
+                $receivablesSourceData = $receivablesHtml[0];
628
+                switch ($value['form_type']) {
629
+                    case 'user' :
630
+                        $receivablesUsers = db('admin_user')->whereIn('id', trim($receivablesData[$value['field']], ','))->column('realname');
631
+                        $receivablesTargetData = str_replace('{'.$value['name'].'}', implode(',', $receivablesUsers), $receivablesHtml[0]);
632
+                        break;
633
+                    case 'structure' :
634
+                        $receivablesStructure = db('admin_structure')->whereIn('id', trim($receivablesData[$value['field']], ','))->column('name');
635
+                        $receivablesTargetData = str_replace('{'.$value['name'].'}', implode(',', $receivablesStructure), $receivablesHtml[0]);
636
+                        break;
637
+                    case 'file' :
638
+                        $receivablesFiles = db('admin_file')->whereIn('file_id', trim($receivablesData[$value['field']], ','))->column('name');
639
+                        $receivablesTargetData = str_replace('{'.$value['name'].'}', implode(',', $receivablesFiles), $receivablesHtml[0]);
640
+                        break;
641
+                    case 'datetime' :
642
+                        $receivablesDatetime = !empty($receivablesData[$value['field']]) ? date('Y-m-d H:i:s', $receivablesData[$value['field']]) : '';
643
+                        $receivablesTargetData = str_replace('{'.$value['name'].'}', $receivablesDatetime, $receivablesHtml[0]);
644
+                        break;
645
+                    case 'receivables_plan' :
646
+                        $receivablesTargetData = str_replace('{'.$value['name'].'}', $plan, $receivablesHtml[0]);
647
+                        break;
648
+                    default :
649
+                        $receivablesTargetData = str_replace('{'.$value['name'].'}', trim($receivablesData[$value['field']], ','), $receivablesHtml[0]);
650
+                }
651
+                $content = str_replace($receivablesSourceData, $receivablesTargetData, $content);
652
+            }
653
+        }
413 654
 
414 655
         return $content;
415 656
     }
657
+
658
+    /**
659
+     * 保存预览数据
660
+     *
661
+     * @param $param user_id 用户id;type 类型(work,pdf);content 打印内容;
662
+     * @author fanqi
663
+     * @date 2021-03-25
664
+     * @return string
665
+     */
666
+    public function preview($param)
667
+    {
668
+        $userId  = $param['user_id'];
669
+        $type    = $param['type'];
670
+        $content = $param['content'];
671
+        $key     = md5(md5($content).$type);
672
+
673
+        $dataId = db('admin_printing_data')->where('key', $key)->value('data_id');
674
+
675
+        if (empty($dataId)) {
676
+            db('admin_printing_data')->insert([
677
+                'key'         => $key,
678
+                'content'     => json_encode(['data' => $content]),
679
+                'user_id'     => $userId,
680
+                'type'        => $type,
681
+                'create_time' => time()
682
+            ]);
683
+        }
684
+
685
+        return $key;
686
+    }
687
+
688
+    /**
689
+     * 获取打印记录数据
690
+     *
691
+     * @param int $printingId 记录ID
692
+     * @author fanqi
693
+     * @since 2021-03-29
694
+     * @return array
695
+     */
696
+    private function getHistoryData($printingId)
697
+    {
698
+        $data = db('crm_printing_record')->field(['type', 'content', 'template_id'])->where('printing_id', $printingId)->find();
699
+
700
+        $contentArray = !empty($data['content']) ? json_decode($data['content'], true) : ['data' => ''];
701
+
702
+        $result = [
703
+            'type' => (int)$data['type'],
704
+            'template_id' => (int)$data['template_id'],
705
+            'content' => $contentArray['data']
706
+        ];
707
+
708
+        return $result;
709
+    }
416 710
 }

+ 44
- 7
application/crm/logic/VisitLogic.php Zobrazit soubor

@@ -2,6 +2,7 @@
2 2
 
3 3
 namespace app\crm\logic;
4 4
 
5
+use app\admin\controller\ApiCommon;
5 6
 use app\admin\model\Common;
6 7
 use app\crm\model\Visit;
7 8
 use think\Db;
@@ -185,7 +186,7 @@ class VisitLogic extends Common
185 186
     /**
186 187
      * 回访详情
187 188
      */
188
-    public function getDataById($id = '')
189
+    public function getDataById($id = '', $userId = 0)
189 190
     {
190 191
         $dataInfo = db('crm_visit')->where('visit_id', $id)->find();
191 192
         if (!$dataInfo) {
@@ -210,6 +211,19 @@ class VisitLogic extends Common
210 211
         }
211 212
         $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
212 213
         $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
214
+        // 字段授权
215
+        if (!empty($userId)) {
216
+            $grantData = getFieldGrantData($userId);
217
+            $userLevel = isSuperAdministrators($userId);
218
+            foreach ($dataInfo AS $key => $value) {
219
+                if (!$userLevel && !empty($grantData['crm_visit'])) {
220
+                    $status = getFieldGrantStatus($key, $grantData['crm_visit']);
221
+
222
+                    # 查看权限
223
+                    if ($status['read'] == 0) unset($dataInfo[$key]);
224
+                }
225
+            }
226
+        }
213 227
         return $dataInfo;
214 228
     }
215 229
 
@@ -236,16 +250,25 @@ class VisitLogic extends Common
236 250
         if ($param['contract_id']) {
237 251
             Db::name('crm_contract')->where('contract_id', $param['contract_id'])->update(['is_visit' => 1]);
238 252
         }
239
-        //处理部门、员工、附件、多选类型字段
253
+        // 处理部门、员工、附件、多选类型字段
240 254
         $arrFieldAtt = $fieldModel->getArrayField('crm_visit');
241 255
         foreach ($arrFieldAtt as $k => $v) {
242 256
             if ($v == 'visit_user_id') continue;
243 257
             $param[$v] = arrayToString($param[$v]);
244 258
         }
259
+        // 处理日期(date)类型
260
+        $dateField = $fieldModel->getFieldByFormType('crm_visit', 'date');
261
+        if (!empty($dateField)) {
262
+            foreach ($param AS $key => $value) {
263
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
264
+            }
265
+        }
266
+
245 267
         $visitModel = new Visit();
246 268
         if ($visitModel->data($param)->allowField(true)->save()) {
247 269
             $visit_id = $visitModel->visit_id;
248 270
             updateActionLog($param['create_user_id'], 'crm_visit', $visitModel->visit_id, '', '', '创建了客户回访');
271
+            RecordActionLog($param['create_user_id'],'crm_visit','save',$param['number'],'','','新增了客户回访'.$param['number']);
249 272
             $data = [];
250 273
             $data['visit_id'] = $visit_id;
251 274
             return $data;
@@ -276,23 +299,32 @@ class VisitLogic extends Common
276 299
 
277 300
         $fieldModel = new \app\admin\model\Field();
278 301
         // 自动验证
279
-        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
302
+//        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
303
+        $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
280 304
         $validate = new Validate($validateArr['rule'], $validateArr['message']);
281 305
         $result = $validate->check($param);
282 306
         if (!$result) {
283 307
             $this->error = $validate->getError();
284 308
             return false;
285 309
         }
286
-        //处理部门、员工、附件、多选类型字段
310
+        // 处理部门、员工、附件、多选类型字段
287 311
         $arrFieldAtt = $fieldModel->getArrayField('crm_visit');
288 312
         foreach ($arrFieldAtt as $k => $v) {
289 313
             if ($v == 'visit_user_id') continue;
290
-            $param[$v] = arrayToString($param[$v]);
314
+            if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
315
+        }
316
+        // 处理日期(date)类型
317
+        $dateField = $fieldModel->getFieldByFormType('crm_visit', 'date');
318
+        if (!empty($dateField)) {
319
+            foreach ($param AS $key => $value) {
320
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
321
+            }
291 322
         }
292 323
 
293 324
         if ($Visit->update($param, ['visit_id' => $visit_id], true)) {
294 325
             //修改记录           
295 326
             updateActionLog($param['user_id'], 'crm_visit', $visit_id, $dataInfo, $param);
327
+            RecordActionLog($param['user_id'], 'crm_visit', 'update',$dataInfo['number'], $dataInfo, $param);
296 328
             $data = [];
297 329
             $data['visit_id'] = $visit_id;
298 330
             return $data;
@@ -333,6 +365,7 @@ class VisitLogic extends Common
333 365
                 $delIds[] = $v;
334 366
             }
335 367
         }
368
+        $dataInfo = $Visit->where('visit_id',['in',$delIds])->select();
336 369
         if ($delIds) {
337 370
             $data = $Visit->delDatas($delIds);
338 371
             if (!$data) {
@@ -342,7 +375,11 @@ class VisitLogic extends Common
342 375
             $fileModel->delRFileByModule('crm_visit', $delIds);
343 376
             //删除关联操作记录
344 377
             $actionRecordModel->delDataById(['types' => 'crm_visit', 'visit_id' => $delIds]);
345
-            actionLog($delIds, '', '', '');
378
+            $user=new ApiCommon();
379
+            $userInfo = $user->userInfo;
380
+            foreach ($dataInfo as $k => $v) {
381
+                RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['name'], '', '', '删除了客户回访:' . $v['name']);
382
+            }
346 383
         }
347 384
         return $errorMessage;
348 385
     }
@@ -363,7 +400,7 @@ class VisitLogic extends Common
363 400
         # 创建人
364 401
         $realname = Db::name('admin_user')->where('id', $visit['create_user_id'])->value('realname');
365 402
         return [
366
-            'create_user_name' => $realname,
403
+            'create_user_id' => $realname,
367 404
             'create_time' => date('Y-m-d H:i:s', $visit['create_time']),
368 405
             'update_time' => date('Y-m-d H:i:s', $visit['update_time'])
369 406
         ];

+ 63
- 15
application/crm/model/Business.php Zobrazit soubor

@@ -45,7 +45,7 @@ class Business extends Common
45 45
         $order_type = $request['order_type'];
46 46
         $is_excel = $request['is_excel']; //导出
47 47
         $getCount = $request['getCount'];
48
-        $businessTypeId = $request['typeId']; // 针对mobile
48
+        $businessTypeId = $request['typesId']; // 针对mobile
49 49
         $businessStatusId = $request['statusId']; // 针对mobile
50 50
         unset($request['scene_id']);
51 51
         unset($request['search']);
@@ -55,7 +55,7 @@ class Business extends Common
55 55
         unset($request['order_type']);
56 56
         unset($request['is_excel']);
57 57
         unset($request['getCount']);
58
-        unset($request['typeId']);
58
+        unset($request['typesId']);
59 59
         unset($request['statusId']);
60 60
 
61 61
         $request = $this->fmtRequest($request);
@@ -78,11 +78,21 @@ class Business extends Common
78 78
         }
79 79
         if (isset($requestMap['type_id'])) {
80 80
             $requestMap['type_id']['value'] = $requestMap['type_id']['type_id'];
81
-            if ($requestMap['type_id']['status_id']) $requestMap['status_id']['value'] = $requestMap['type_id']['status_id'];
81
+            if(in_array($requestMap['type_id']['status_id'],[1,2,3])){
82
+                $requestMap['is_end']=$requestMap['type_id']['status_id'];
83
+            }else{
84
+                if ($requestMap['type_id']['status_id']) $requestMap['status_id']['value'] = $requestMap['type_id']['status_id'];
85
+                $requestMap['is_end']=0;
86
+            }
82 87
         }
83 88
         if ($sceneMap['type_id']) {
84 89
             $requestMap['type_id']['value'] = $sceneMap['type_id']['type_id'];
85
-            if ($sceneMap['type_id']['status_id']) $requestMap['status_id']['value'] = $sceneMap['type_id']['status_id'];
90
+            if(in_array($sceneMap['type_id']['status_id'],[1,2,3])){
91
+                $sceneMap['is_end']=$sceneMap['type_id']['status_id'];
92
+            }else{
93
+                if ($sceneMap['type_id']['status_id']) $requestMap['status_id']['value'] = $sceneMap['type_id']['status_id'];
94
+                $sceneMap['is_end']=0;
95
+            }
86 96
             unset($sceneMap['type_id']);
87 97
         }
88 98
         $partMap = [];
@@ -157,10 +167,17 @@ class Business extends Common
157 167
         } else {
158 168
             $order = 'business.update_time desc';
159 169
         }
170
+    
160 171
         # 商机组和商机状态搜索
161 172
         if (!empty($businessTypeId))   $map['business.type_id']   = ['eq', $businessTypeId];
162
-        if (!empty($businessStatusId)) $map['business.status_id'] = ['eq', $businessStatusId];
163
-
173
+        if (!empty($businessStatusId)) {
174
+            if(preg_match("/^[1-9][0-9]*$/" ,$businessStatusId)){
175
+                $map['is_end']=0;
176
+                $map['business.status_id'] = ['eq', $businessStatusId];
177
+            }else{
178
+                $map['is_end']=abs($businessStatusId);
179
+            }
180
+        }
164 181
         $readAuthIds = $userModel->getUserByPer('crm', 'business', 'read');
165 182
         $updateAuthIds = $userModel->getUserByPer('crm', 'business', 'update');
166 183
         $deleteAuthIds = $userModel->getUserByPer('crm', 'business', 'delete');
@@ -279,11 +296,18 @@ class Business extends Common
279 296
             return false;
280 297
         }
281 298
 
282
-        //处理部门、员工、附件、多选类型字段
299
+        // 处理部门、员工、附件、多选类型字段
283 300
         $arrFieldAtt = $fieldModel->getArrayField('crm_business');
284 301
         foreach ($arrFieldAtt as $k => $v) {
285 302
             $param[$v] = arrayToString($param[$v]);
286 303
         }
304
+        // 处理日期(date)类型
305
+        $dateField = $fieldModel->getFieldByFormType('crm_business', 'date');
306
+        if (!empty($dateField)) {
307
+            foreach ($param AS $key => $value) {
308
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
309
+            }
310
+        }
287 311
 
288 312
         # 设置今日需联系商机
289 313
         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
292 316
         $param['discount_rate'] = $param['discount_rate'] ?: '0.00';
293 317
         if ($this->data($param)->allowField(true)->save()) {
294 318
             updateActionLog($param['create_user_id'], 'crm_business', $this->business_id, '', '', '创建了商机');
319
+            RecordActionLog($param['create_user_id'],'crm_business','save',$param['name'],'','','新增了商机'.$param['name']);
295 320
             $business_id = $this->business_id;
296 321
             if ($param['product']) {
297 322
                 //产品数据处理
@@ -356,7 +381,8 @@ class Business extends Common
356 381
 
357 382
         $fieldModel = new \app\admin\model\Field();
358 383
         // 自动验证
359
-        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
384
+//        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
385
+        $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
360 386
         $validate = new Validate($validateArr['rule'], $validateArr['message']);
361 387
 
362 388
         $result = $validate->check($param);
@@ -370,10 +396,17 @@ class Business extends Common
370 396
             $param['money'] .= '.00';
371 397
         }
372 398
 
373
-        //处理部门、员工、附件、多选类型字段
399
+        // 处理部门、员工、附件、多选类型字段
374 400
         $arrFieldAtt = $fieldModel->getArrayField('crm_business');
375 401
         foreach ($arrFieldAtt as $k => $v) {
376
-            $param[$v] = arrayToString($param[$v]);
402
+            if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
403
+        }
404
+        // 处理日期(date)类型
405
+        $dateField = $fieldModel->getFieldByFormType('crm_business', 'date');
406
+        if (!empty($dateField)) {
407
+            foreach ($param AS $key => $value) {
408
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
409
+            }
377 410
         }
378 411
 
379 412
         # 设置今日需联系商机
@@ -393,6 +426,7 @@ class Business extends Common
393 426
             $resProduct = $productModel->createObject('crm_business', $param, $business_id);
394 427
             //修改记录
395 428
             updateActionLog($param['user_id'], 'crm_business', $business_id, $dataInfo, $param);
429
+            RecordActionLog($param['user_id'], 'crm_business', 'update',$dataInfo['name'], $dataInfo, $param);
396 430
             $data = [];
397 431
             $data['business_id'] = $business_id;
398 432
             return $data;
@@ -441,10 +475,26 @@ class Business extends Common
441 475
         foreach ($datetimeField as $key => $val) {
442 476
             $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
443 477
         }
478
+        if($dataInfo['is_end']!=1){
479
+            $dataInfo['statusRemark']=db('crm_business_log')->where(['business_id'=>$id,'is_end'=>$dataInfo['is_end']])->value('remark');
480
+        }
444 481
         $dataInfo['next_time'] = !empty($dataInfo['next_time']) ? date('Y-m-d H:i:s', $dataInfo['next_time']) : null;
445 482
         $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
446 483
         $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
447 484
         $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
485
+        // 字段授权
486
+        if (!empty($userId)) {
487
+            $grantData = getFieldGrantData($userId);
488
+            $userLevel = isSuperAdministrators($userId);
489
+            foreach ($dataInfo AS $key => $value) {
490
+                if (!$userLevel && !empty($grantData['crm_business'])) {
491
+                    $status = getFieldGrantStatus($key, $grantData['crm_business']);
492
+
493
+                    # 查看权限
494
+                    if ($status['read'] == 0) unset($dataInfo[$key]);
495
+                }
496
+            }
497
+        }
448 498
         return $dataInfo;
449 499
     }
450 500
 
@@ -666,17 +716,15 @@ class Business extends Common
666 716
     public function getSystemInfo($id)
667 717
     {
668 718
         # 商机
669
-        $business = Db::name('crm_business')->field(['create_user_id', 'create_time', 'update_time'])->where('business_id', $id)->find();
719
+        $business = Db::name('crm_business')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('business_id', $id)->find();
670 720
         # 创建人
671 721
         $realname = Db::name('admin_user')->where('id', $business['create_user_id'])->value('realname');
672
-        # 跟进时间
673
-        $followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 5, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
674 722
 
675 723
         return [
676
-            'create_user_name' => $realname,
724
+            'create_user_id' => $realname,
677 725
             'create_time' => date('Y-m-d H:i:s', $business['create_time']),
678 726
             'update_time' => date('Y-m-d H:i:s', $business['update_time']),
679
-            'follow_time' => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : ''
727
+            'last_time' => !empty($business['last_time']) ? date('Y-m-d H:i:s', $business['last_time']) : ''
680 728
         ];
681 729
     }
682 730
 

+ 17
- 4
application/crm/model/BusinessStatus.php Zobrazit soubor

@@ -6,6 +6,7 @@
6 6
 // +----------------------------------------------------------------------
7 7
 namespace app\crm\model;
8 8
 
9
+use app\admin\controller\ApiCommon;
9 10
 use think\Db;
10 11
 use app\admin\model\Common;
11 12
 use think\Request;
@@ -118,7 +119,9 @@ class BusinessStatus extends Common
118 119
 	    		}
119 120
 			}
120 121
 			db('crm_business_status')->insertAll($statusData);
121
-			return true;
122
+			# 系统操作日志
123
+            SystemActionLog($param['create_user_id'], 'crm_business','customer', $type_id, 'save',$param['name'] , '', '','添加了商机组:'.$param['name']);
124
+            return true;
122 125
 		} else {
123 126
 			$this->error = '添加失败';
124 127
 			return false;
@@ -194,8 +197,12 @@ class BusinessStatus extends Common
194 197
 			//新增
195 198
 			db('crm_business_status')->insertAll($statusData);
196 199
 			// 提交事务
197
-    		Db::commit();								
198
-			return true;
200
+    		Db::commit();
201
+    		# 系统操作日志
202
+    		$user=new ApiCommon();
203
+    		$userInfo=$user->userInfo;
204
+            SystemActionLog($userInfo['id'], 'crm_business','customer', $type_id, 'update',$dataInfo['name'] , '', '','编辑了商机组:'.$dataInfo['name']);
205
+            return true;
199 206
 		} catch (\Exception $e) {
200 207
 			$this->error = '编辑失败';
201 208
 			// 回滚事务
@@ -247,7 +254,13 @@ class BusinessStatus extends Common
247 254
 //			db('crm_business_status')->where(['type_id' => $id])->delete();
248 255
 			// 提交事务
249 256
     		Db::commit();
250
-			return true;					
257
+            # 系统操作日志
258
+    		$user=new ApiCommon();
259
+    		$userInfo=$user->userInfo;
260
+            $data=db('crm_business_type')->where(['type_id' => $id])->find();
261
+            SystemActionLog($userInfo['id'], 'crm_business','customer', $id,  'update',$data['name'] , '', '','删除了商机组:'.$data['name']);
262
+            
263
+            return true;
251 264
 		} catch(\Exception $e) {
252 265
 			$this->error = '删除失败';
253 266
 			// 回滚事务

+ 41
- 12
application/crm/model/Contacts.php Zobrazit soubor

@@ -231,13 +231,22 @@ class Contacts extends Common
231 231
             $param['primary'] = 1;
232 232
         }
233 233
 
234
-		//处理部门、员工、附件、多选类型字段
234
+		// 处理部门、员工、附件、多选类型字段
235 235
 		$arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
236 236
 		foreach ($arrFieldAtt as $k=>$v) {
237 237
 			$param[$v] = arrayToString($param[$v]);
238 238
 		}
239
+        // 处理日期(date)类型
240
+        $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
241
+        if (!empty($dateField)) {
242
+            foreach ($param AS $key => $value) {
243
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
244
+            }
245
+        }
246
+
239 247
 		if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
240
-			updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');			
248
+			updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
249
+            RecordActionLog($param['create_user_id'],'crm_contacts','save',$param['name'],'','','新增了联系人'.$param['name']);
241 250
 			$data = [];
242 251
 			$data['contacts_id'] = $this->contacts_id;
243 252
 
@@ -311,7 +320,8 @@ class Contacts extends Common
311 320
 		}
312 321
 		$fieldModel = new \app\admin\model\Field();
313 322
 		// 自动验证
314
-		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
323
+//		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
324
+		$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
315 325
 		$validate = new Validate($validateArr['rule'], $validateArr['message']);
316 326
 
317 327
 		$result = $validate->check($param);
@@ -320,11 +330,18 @@ class Contacts extends Common
320 330
 			return false;
321 331
 		}
322 332
 
323
-		//处理部门、员工、附件、多选类型字段
333
+		// 处理部门、员工、附件、多选类型字段
324 334
 		$arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
325 335
 		foreach ($arrFieldAtt as $k=>$v) {
326
-			$param[$v] = arrayToString($param[$v]);
336
+            if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
327 337
 		}
338
+        // 处理日期(date)类型
339
+        $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
340
+        if (!empty($dateField)) {
341
+            foreach ($param AS $key => $value) {
342
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
343
+            }
344
+        }
328 345
 
329 346
         # 处理首要联系人
330 347
         $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
@@ -340,6 +357,7 @@ class Contacts extends Common
340 357
 		if ($this->update($param, ['contacts_id' => $contacts_id], true)) {
341 358
 			//修改记录
342 359
 			updateActionLog($param['user_id'], 'crm_contacts', $contacts_id, $dataInfo, $param);
360
+            RecordActionLog($param['user_id'], 'crm_contacts', 'update',$dataInfo['name'], $dataInfo, $param);
343 361
 			$data = [];
344 362
 			$data['contacts_id'] = $contacts_id;
345 363
 			return $data;
@@ -388,6 +406,19 @@ class Contacts extends Common
388 406
         $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
389 407
         $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
390 408
         $dataInfo['last_time']   = !empty($dataInfo['last_time'])   ? date('Y-m-d H:i:s', $dataInfo['last_time'])   : null;
409
+        // 字段授权
410
+        if (!empty($userId)) {
411
+            $grantData = getFieldGrantData($userId);
412
+            $userLevel = isSuperAdministrators($userId);
413
+            foreach ($dataInfo AS $key => $value) {
414
+                if (!$userLevel && !empty($grantData['crm_contacts'])) {
415
+                    $status = getFieldGrantStatus($key, $grantData['crm_contacts']);
416
+
417
+                    # 查看权限
418
+                    if ($status['read'] == 0) unset($dataInfo[$key]);
419
+                }
420
+            }
421
+        }
391 422
 		return $dataInfo;
392 423
    	}
393 424
 
@@ -454,17 +485,15 @@ class Contacts extends Common
454 485
     public function getSystemInfo($id)
455 486
     {
456 487
         # 联系人
457
-        $contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time'])->where('contacts_id', $id)->find();
488
+        $contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('contacts_id', $id)->find();
458 489
         # 创建人
459 490
         $realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname');
460
-        # 跟进时间
461
-        $followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 3, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
462 491
 
463 492
         return [
464
-            'create_user_name' => $realname,
465
-            'create_time'      => date('Y-m-d H:i:s', $contacts['create_time']),
466
-            'update_time'      => date('Y-m-d H:i:s', $contacts['update_time']),
467
-            'follow_time'      => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : ''
493
+            'create_user_id' => $realname,
494
+            'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),
495
+            'update_time' => date('Y-m-d H:i:s', $contacts['update_time']),
496
+            'last_time' => !empty($contacts['last_time']) ? date('Y-m-d H:i:s', $contacts['last_time']) : ''
468 497
         ];
469 498
     }
470 499
 }

+ 53
- 15
application/crm/model/Contract.php Zobrazit soubor

@@ -380,11 +380,18 @@ class Contract extends Common
380 380
         # 处理下次联系时间
381 381
         if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
382 382
 
383
-		//处理部门、员工、附件、多选类型字段
383
+		// 处理部门、员工、附件、多选类型字段
384 384
 		$arrFieldAtt = $fieldModel->getArrayField('crm_contract');
385 385
 		foreach ($arrFieldAtt as $k=>$v) {
386 386
 			$param[$v] = arrayToString($param[$v]);
387 387
 		}
388
+        // 处理日期(date)类型
389
+        $dateField = $fieldModel->getFieldByFormType('crm_contract', 'date');
390
+        if (!empty($dateField)) {
391
+            foreach ($param AS $key => $value) {
392
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
393
+            }
394
+        }
388 395
 
389 396
 		# 下单时间
390 397
         $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
420 427
 			$this->commit();
421 428
 
422 429
 			//修改记录
423
-			updateActionLog($param['create_user_id'], 'crm_contract', $this->contract_id, '', '', '创建了合同');					
424
-
430
+			updateActionLog($param['create_user_id'], 'crm_contract', $this->contract_id, '', '', '创建了合同');
431
+            RecordActionLog($param['create_user_id'],'crm_contract','save',$param['name'],'','','新增了合同'.$param['name']);
425 432
             # 添加活动记录
426 433
             Db::name('crm_activity')->insert([
427 434
                 'type'             => 2,
@@ -476,7 +483,8 @@ class Contract extends Common
476 483
 		$param['contract_id'] = $contract_id;
477 484
 		$fieldModel = new \app\admin\model\Field();
478 485
 		// 自动验证
479
-		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
486
+//		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
487
+		$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
480 488
 		$validate = new Validate($validateArr['rule'], $validateArr['message']);
481 489
 
482 490
 		$result = $validate->check($param);
@@ -492,17 +500,25 @@ class Contract extends Common
492 500
         if (empty($param['start_time'])) $param['start_time'] = null;
493 501
         if (empty($param['end_time']))   $param['end_time']   = null;
494 502
 
495
-		//处理部门、员工、附件、多选类型字段
503
+		// 处理部门、员工、附件、多选类型字段
496 504
 		$arrFieldAtt = $fieldModel->getArrayField('crm_contract');
497 505
 		foreach ($arrFieldAtt as $k=>$v) {
498
-			$param[$v] = arrayToString($param[$v]);
506
+            if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
499 507
 		}
508
+        // 处理日期(date)类型
509
+        $dateField = $fieldModel->getFieldByFormType('crm_contract', 'date');
510
+        if (!empty($dateField)) {
511
+            foreach ($param AS $key => $value) {
512
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
513
+            }
514
+        }
500 515
 
501 516
 		if ($this->update($param, ['contract_id' => $contract_id], true)) {
502 517
 			//产品数据处理
503 518
 	        $resProduct = $productModel->createObject('crm_contract', $param, $contract_id);			
504 519
 			//修改记录
505 520
 			updateActionLog($param['user_id'], 'crm_contract', $contract_id, $dataInfo, $param);
521
+            RecordActionLog($param['user_id'], 'crm_contract', 'update',$dataInfo['name'], $dataInfo, $param);
506 522
             //站内信
507 523
             $send_user_id = stringToArray($param['check_user_id']);
508 524
             if ($send_user_id && empty($param['check_status'])) {
@@ -549,7 +565,7 @@ class Contract extends Common
549 565
      * @throws \think\db\exception\ModelNotFoundException
550 566
      * @throws \think\exception\DbException
551 567
      */
552
-   	public function getDataById($id = '')
568
+   	public function getDataById($id = '', $userId = 0)
553 569
    	{   
554 570
    		$receivablesModel = new \app\crm\model\Receivables();
555 571
    		$userModel = new \app\admin\model\User();	
@@ -583,6 +599,30 @@ class Contract extends Common
583 599
         $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
584 600
         $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
585 601
         $dataInfo['last_time']   = !empty($dataInfo['last_time'])   ? date('Y-m-d H:i:s', $dataInfo['last_time'])   : null;
602
+        // 字段授权
603
+        if (!empty($userId)) {
604
+            $grantData = getFieldGrantData($userId);
605
+            $userLevel = isSuperAdministrators($userId);
606
+            foreach ($dataInfo AS $key => $value) {
607
+                if (!$userLevel && !empty($grantData['crm_contract'])) {
608
+                    $status = getFieldGrantStatus($key, $grantData['crm_contract']);
609
+
610
+                    # 查看权限
611
+                    if ($status['read'] == 0) unset($dataInfo[$key]);
612
+                }
613
+            }
614
+            if (!$userLevel && !empty($grantData['crm_contract'])) {
615
+                # 客户名称
616
+                $customerStatus = getFieldGrantStatus('customer_id', $grantData['crm_contract']);
617
+                if ($customerStatus['read'] == 0) {
618
+                    $dataInfo['customer_name'] = '';
619
+                    $dataInfo['customer_id_info'] = [];
620
+                }
621
+                # 回款金额
622
+                $doneMoneyStatus = getFieldGrantStatus('done_money', $grantData['crm_contract']);
623
+                if ($doneMoneyStatus['read'] == 0) $dataInfo['receivablesMoney'] = '';
624
+            }
625
+        }
586 626
 		return $dataInfo;
587 627
    	}
588 628
 
@@ -682,19 +722,17 @@ class Contract extends Common
682 722
         $business = Db::name('crm_contract')->where('contract_id', $id)->find();
683 723
         # 创建人
684 724
         $realname = Db::name('admin_user')->where('id', $business['create_user_id'])->value('realname');
685
-        # 跟进时间
686
-        $followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 6, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
687 725
         # 回款
688 726
         $receivablesModel = new Receivables();
689 727
         $receivables = $receivablesModel->getMoneyByContractId($id);
690 728
 
691 729
         return [
692
-            'create_user_name' => $realname,
693
-            'create_time'      => date('Y-m-d H:i:s', $business['create_time']),
694
-            'update_time'      => date('Y-m-d H:i:s', $business['update_time']),
695
-            'follow_time'      => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : '',
696
-            'done_money'       => $receivables['doneMoney'],
697
-            'un_money'         => $receivables['unMoney']
730
+            'create_user_id' => $realname,
731
+            'create_time' => date('Y-m-d H:i:s', $business['create_time']),
732
+            'update_time' => date('Y-m-d H:i:s', $business['update_time']),
733
+            'last_time' => !empty($business['last_time']) ? date('Y-m-d H:i:s', $business['last_time']) : '',
734
+            'done_money' => $receivables['doneMoney'],
735
+            'un_money' => $receivables['unMoney']
698 736
         ];
699 737
     }
700 738
 

+ 736
- 386
application/crm/model/Customer.php
Diff nebyl zobrazen, protože je příliš veliký
Zobrazit soubor


+ 113
- 48
application/crm/model/CustomerConfig.php Zobrazit soubor

@@ -6,6 +6,7 @@
6 6
 // +----------------------------------------------------------------------
7 7
 namespace app\crm\model;
8 8
 
9
+use app\admin\controller\ApiCommon;
9 10
 use think\Db;
10 11
 use app\admin\model\Common;
11 12
 use think\Request;
@@ -79,13 +80,23 @@ class CustomerConfig extends Common
79 80
             $this->error = '有员工或部门包含在其他的规则里!';
80 81
             return false;
81 82
         }
82
-
83 83
 		$param['types']         = !empty($param['types'])         ? $param['types']                        : 1;  # 1拥有客户上限2锁定客户上限
84 84
 		$param['user_ids']      = !empty($param['user_ids'])      ? arrayToString($param['user_ids'])      : ''; # 处理user_id
85 85
 		$param['structure_ids'] = !empty($param['structure_ids']) ? arrayToString($param['structure_ids']) : ''; # 处理structure_id
86 86
         if ($this->allowField(true)->isUpdate(empty($id) ? false : true)->save($param, !empty($id) ? ['id' => $id] : [])) {
87 87
 			$data['id'] = $this->id;
88
-			return $data;
88
+            # 系统操作日志
89
+            if(!empty($param['id'])){
90
+                $content='编辑员工拥有、锁定客户限制';
91
+                $action='update';
92
+            }else{
93
+                $content='添加员工拥有、锁定客户限制';
94
+                $action='update';
95
+            }
96
+            $user=new ApiCommon();
97
+            $userInfo=$user->userInfo;
98
+            SystemActionLog($userInfo['id'], 'crm_customer','customer', $this->id,  $action,$content , '', '',$content);
99
+            return $data;
89 100
 		} else {
90 101
 			$this->error = '创建失败';
91 102
 			return false;
@@ -139,54 +150,108 @@ class CustomerConfig extends Common
139 150
    	}
140 151
 
141 152
     /**
142
-     * 验证相关信息
153
+     * 验证是否可以持有或锁定客户
143 154
      *
144
-     * @param $user_id
145
-     * @param $types
146
-     * @param string $is_update
147
-     * @return bool
148
-     * @throws \think\db\exception\DataNotFoundException
149
-     * @throws \think\db\exception\ModelNotFoundException
150
-     * @throws \think\exception\DbException
155
+     * @param int $userId 用户id
156
+     * @param int $types 类型:类型:1 拥有客户数,2 锁定客户数
157
+     * @param int $isUpdate 是否是更新
158
+     * @param int $addCount 多公海分配或领取使用的参数,代表要领取或分配的客户数量
159
+     * @return bool|int|mixed
151 160
      */
152
-   	public function checkData($user_id, $types, $is_update = '')
153
-   	{   
154
-   		$userModel = new \app\admin\model\User();
155
-   		$customerModel = new \app\crm\model\Customer();
156
-   		$userInfo = $userModel->getUserById($user_id);
157
-   		$dataInfo = $this->where(['types' => $types,'user_ids' => ['like','%,'.$user_id.',%']])->order('update_time desc')->find();
158
-		if (!$dataInfo) {
159
-			$dataInfo = $this->where(['types' => $types,'structure_ids' => ['like','%,'.$userInfo['structure_id'].',%']])->find();
160
-		}
161
-		switch ($types) {
162
-			case '1' : $types_title = '拥有的客户数量'; break;
163
-			case '2' : $types_title = '锁定的客户数量'; break;
164
-		}
165
-		if ($dataInfo) {
166
-			$is_deal = $dataInfo['is_deal'] ? : 0;
167
-			if (!$dataInfo['value']) {
168
-				$this->error = $types_title.'超出限制:'.$dataInfo['value'].'个';
169
-				return false;
170
-			}
171
-			//拥有数、锁定数
172
-			$count = $customerModel->getCountByHave($user_id,$is_deal,$types);
173
-			$error = false;
174
-			if ($count >= $dataInfo['value']) {
175
-				$error = true;			
176
-			}		
177
-			if ($is_update == 1 && $types == 1 && $dataInfo['is_deal'] == 1) {
178
-				//更改成交状态
179
-				if ($count = $dataInfo['value']) {
180
-					$error = false;			
181
-				}						
182
-			}			
183
-			if ($error == true) {
184
-				$this->error = $userInfo['realname'].','.$types_title.'超出限制:'.$dataInfo['value'].'个';
185
-				return false;	
186
-			}
187
-		}
188
-		return true;
189
-   	}
161
+    public function checkData($userId, $types, $isUpdate = 0, $addCount = 0)
162
+    {
163
+        # 用户信息
164
+        $userinfo = db('admin_user')->field(['realname', 'structure_id'])->where('id', $userId)->find();
165
+        $username = $userinfo['realname'];
166
+        $structureId = $userinfo['structure_id'];
167
+
168
+        # 查询客户配置(拥有,锁定),以用户配置优先
169
+        $customerConfig = db('crm_customer_config')->field(['value', 'is_deal'])->where(['types' => $types, 'user_ids' => ['like', '%,' . $userId . ',%']])->find();
170
+        if (!$customerConfig) $customerConfig = db('crm_customer_config')->field(['value', 'is_deal'])->where(['types' => $types, 'structure_ids' => ['like', '%,' . $structureId . ',%']])->find();
171
+
172
+        # 提示标题
173
+        $title = '';
174
+        if ($types == 1) $title = '拥有的客户数量';
175
+        if ($types == 2) $title = '锁定的客户数量';
176
+
177
+        if ($customerConfig) {
178
+            if (empty($customerConfig['value'])) {
179
+                $this->error = $title . '超出限制,最大:' . $customerConfig['value'] . ' 个';
180
+
181
+                return false;
182
+            }
183
+
184
+            # 成交用户是否暂用数量
185
+            $isDeal = !empty($customerConfig['is_deal']) ? 1 : 0;
186
+
187
+            # 获取目前拥有或锁定的客户数量
188
+            $customerModel = new Customer();
189
+            $count = $customerModel->getCountByHave($userId, $isDeal, $types);
190
+
191
+            $error = false;
192
+            if (empty($addCount)) {
193
+                # 多公海以外的地方调用
194
+                if ($count >= $customerConfig['value']) {
195
+                    $error = true;
196
+                }
197
+                if ($isUpdate == 1 && $types == 1 && $customerConfig['is_deal'] == 1) {
198
+                    //更改成交状态
199
+                    if ($count = $customerConfig['value']) {
200
+                        $error = false;
201
+                    }
202
+                }
203
+                if ($error == true) {
204
+                    $this->error = $username.','.$title.'超出限制:'.$customerConfig['value'].'个';
205
+                    return false;
206
+                }
207
+            } else {
208
+                # 多公海中的领取、分配调用,返回超出的个数
209
+                if ($count + $addCount > $customerConfig['value']) {
210
+                    return ($count + $addCount) - $customerConfig['value'];
211
+                }
212
+            }
213
+        }
214
+
215
+        return true;
216
+    }
217
+//   	public function checkData($user_id, $types, $is_update = '')
218
+//   	{
219
+//   		$userModel = new \app\admin\model\User();
220
+//   		$customerModel = new \app\crm\model\Customer();
221
+//   		$userInfo = $userModel->getUserById($user_id);
222
+//   		$dataInfo = $this->where(['types' => $types,'user_ids' => ['like','%,'.$user_id.',%']])->order('update_time desc')->find();
223
+//		if (!$dataInfo) {
224
+//			$dataInfo = $this->where(['types' => $types,'structure_ids' => ['like','%,'.$userInfo['structure_id'].',%']])->find();
225
+//		}
226
+//		switch ($types) {
227
+//			case '1' : $types_title = '拥有的客户数量'; break;
228
+//			case '2' : $types_title = '锁定的客户数量'; break;
229
+//		}
230
+//		if ($dataInfo) {
231
+//			$is_deal = $dataInfo['is_deal'] ? : 0;
232
+//			if (!$dataInfo['value']) {
233
+//				$this->error = $types_title.'超出限制:'.$dataInfo['value'].'个';
234
+//				return false;
235
+//			}
236
+//			//拥有数、锁定数
237
+//			$count = $customerModel->getCountByHave($user_id,$is_deal,$types);
238
+//			$error = false;
239
+//			if ($count >= $dataInfo['value']) {
240
+//				$error = true;
241
+//			}
242
+//			if ($is_update == 1 && $types == 1 && $dataInfo['is_deal'] == 1) {
243
+//				//更改成交状态
244
+//				if ($count = $dataInfo['value']) {
245
+//					$error = false;
246
+//				}
247
+//			}
248
+//			if ($error == true) {
249
+//				$this->error = $userInfo['realname'].','.$types_title.'超出限制:'.$dataInfo['value'].'个';
250
+//				return false;
251
+//			}
252
+//		}
253
+//		return true;
254
+//   	}
190 255
 
191 256
     /**
192 257
      * 验证拥有/锁定客户数中的员工或部门是否重复添加

+ 37
- 9
application/crm/model/Leads.php Zobrazit soubor

@@ -212,11 +212,18 @@ class Leads extends Common
212 212
             return false;
213 213
         }
214 214
 
215
-        //处理部门、员工、附件、多选类型字段
215
+        // 处理部门、员工、附件、多选类型字段
216 216
         $arrFieldAtt = $fieldModel->getArrayField('crm_leads');
217 217
         foreach ($arrFieldAtt as $k => $v) {
218 218
             $param[$v] = arrayToString($param[$v]);
219 219
         }
220
+        // 处理日期(date)类型
221
+        $dateField = $fieldModel->getFieldByFormType('crm_leads', 'date');
222
+        if (!empty($dateField)) {
223
+            foreach ($param AS $key => $value) {
224
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
225
+            }
226
+        }
220 227
 
221 228
         # 设置今日需联系线索
222 229
         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
224 231
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
225 232
             //修改记录
226 233
             updateActionLog($param['create_user_id'], 'crm_leads', $this->leads_id, '', '', '创建了线索');
234
+            RecordActionLog($param['create_user_id'],'crm_leads','save',$param['name'],'','','新增了线索'.$param['name']);
227 235
             # 添加活动记录
228 236
             Db::name('crm_activity')->insert([
229 237
                 'type'             => 2,
@@ -276,7 +284,8 @@ class Leads extends Common
276 284
 
277 285
         $fieldModel = new \app\admin\model\Field();
278 286
         // 自动验证
279
-        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
287
+//        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
288
+        $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
280 289
         $validate = new Validate($validateArr['rule'], $validateArr['message']);
281 290
         $result = $validate->check($param);
282 291
         if (!$result) {
@@ -284,10 +293,17 @@ class Leads extends Common
284 293
             return false;
285 294
         }
286 295
 
287
-        //处理部门、员工、附件、多选类型字段
296
+        // 处理部门、员工、附件、多选类型字段
288 297
         $arrFieldAtt = $fieldModel->getArrayField('crm_leads');
289 298
         foreach ($arrFieldAtt as $k => $v) {
290
-            $param[$v] = arrayToString($param[$v]);
299
+            if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
300
+        }
301
+        // 处理日期(date)类型
302
+        $dateField = $fieldModel->getFieldByFormType('crm_leads', 'date');
303
+        if (!empty($dateField)) {
304
+            foreach ($param AS $key => $value) {
305
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
306
+            }
291 307
         }
292 308
 
293 309
         # 设置今日需联系线索
@@ -296,6 +312,7 @@ class Leads extends Common
296 312
         if ($this->update($param, ['leads_id' => $leads_id], true)) {
297 313
             //修改记录
298 314
             updateActionLog($param['user_id'], 'crm_leads', $leads_id, $dataInfo, $param);
315
+            RecordActionLog($param['user_id'], 'crm_leads','update', $dataInfo['name'], $dataInfo, $param);
299 316
             $data = [];
300 317
             $data['leads_id'] = $leads_id;
301 318
             return $data;
@@ -339,6 +356,19 @@ class Leads extends Common
339 356
         $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
340 357
         $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
341 358
         $dataInfo['last_time']   = !empty($dataInfo['last_time'])   ? date('Y-m-d H:i:s', $dataInfo['last_time'])   : null;
359
+        // 字段授权
360
+        if (!empty($userId)) {
361
+            $grantData = getFieldGrantData($userId);
362
+            $userLevel = isSuperAdministrators($userId);
363
+            foreach ($dataInfo AS $key => $value) {
364
+                if (!$userLevel && !empty($grantData['crm_leads'])) {
365
+                    $status = getFieldGrantStatus($key, $grantData['crm_leads']);
366
+
367
+                    # 查看权限
368
+                    if ($status['read'] == 0) unset($dataInfo[$key]);
369
+                }
370
+            }
371
+        }
342 372
         return $dataInfo;
343 373
     }
344 374
 
@@ -355,17 +385,15 @@ class Leads extends Common
355 385
     function getSystemInfo($id)
356 386
     {
357 387
         # 线索
358
-        $leads = Db::name('crm_leads')->field(['create_user_id', 'create_time', 'update_time'])->where('leads_id', $id)->find();
388
+        $leads = Db::name('crm_leads')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('leads_id', $id)->find();
359 389
         # 创建人
360 390
         $realname = Db::name('admin_user')->where('id', $leads['create_user_id'])->value('realname');
361
-        # 最后跟进时间
362
-        $followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 1, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
363 391
 
364 392
         return [
365
-            'create_user_name' => $realname,
393
+            'create_user_id' => $realname,
366 394
             'create_time' => date('Y-m-d H:i:s', $leads['create_time']),
367 395
             'update_time' => date('Y-m-d H:i:s', $leads['update_time']),
368
-            'follow_time' => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : ''
396
+            'last_time' => !empty($leads['last_time']) ? date('Y-m-d H:i:s', $leads['last_time']) : ''
369 397
         ];
370 398
     }
371 399
 }

+ 14
- 0
application/crm/model/Market.php Zobrazit soubor

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

+ 567
- 371
application/crm/model/Product.php
Diff nebyl zobrazen, protože je příliš veliký
Zobrazit soubor


+ 18
- 4
application/crm/model/ProductCategory.php Zobrazit soubor

@@ -6,6 +6,7 @@
6 6
 // +----------------------------------------------------------------------
7 7
 namespace app\crm\model;
8 8
 
9
+use app\admin\controller\ApiCommon;
9 10
 use think\Db;
10 11
 use app\admin\model\Common;
11 12
 use think\Request;
@@ -60,7 +61,11 @@ class ProductCategory extends Common
60 61
 		if ($this->data($param)->allowField(true)->save()) {
61 62
 			$data = [];
62 63
 			$data['id'] = $this->category_id;
63
-			return $data;
64
+            # 系统操作日志
65
+            $user=new ApiCommon();
66
+            $userInfo=$user->userInfo;
67
+            SystemActionLog($userInfo['id'], 'crm_product','customer', $this->category_id, 'save',$param['name'] , '', '','添加了产品分类:'.$param['name']);
68
+            return $data;
64 69
 		} else {
65 70
 			$this->error = '添加失败';
66 71
 			return false;
@@ -90,7 +95,11 @@ class ProductCategory extends Common
90 95
 		}
91 96
 
92 97
 		if ($this->allowField(true)->save($param, ['category_id' => $category_id])) {
93
-			return true;
98
+            # 系统操作日志
99
+            $user=new ApiCommon();
100
+            $userInfo=$user->userInfo;
101
+            SystemActionLog($userInfo['id'], 'crm_product','customer', $category_id,  'update',$dataInfo['name'] , '', '','编辑了产品分类:'.$dataInfo['name']);
102
+            return true;
94 103
 		} else {
95 104
 			$this->error = '编辑失败';
96 105
 			return false;
@@ -126,6 +135,7 @@ class ProductCategory extends Common
126 135
 			$this->error = '请先移除该类型及子类下的相关产品';
127 136
 			return false;			
128 137
 		}
138
+        $data=db('crm_product_category')->where('category_id' , $id)->find();
129 139
 		//提交事务
130 140
 		$this->startTrans();
131 141
 		try {
@@ -137,8 +147,12 @@ class ProductCategory extends Common
137 147
 					$this->where('category_id', 'in', $childIds)->delete();
138 148
 				}
139 149
 			}
140
-			$this->commit();
141
-			return true;					
150
+            # 系统操作日志
151
+            $user=new ApiCommon();
152
+            $userInfo=$user->userInfo;
153
+            SystemActionLog($userInfo['id'], 'crm_product','customer', $id,  'update',$data['name'] , '', '','删除了产品分类:'.$data['name']);
154
+            $this->commit();
155
+			return true;
142 156
 		} catch(\Exception $e) {
143 157
 			$this->error = '删除失败';
144 158
 			$this->rollback();

+ 55
- 10
application/crm/model/Receivables.php Zobrazit soubor

@@ -269,11 +269,19 @@ class Receivables extends Common
269 269
             return false;
270 270
         }
271 271
 
272
-		//处理部门、员工、附件、多选类型字段
272
+		// 处理部门、员工、附件、多选类型字段
273 273
 		$arrFieldAtt = $fieldModel->getArrayField('crm_receivables');
274 274
 		foreach ($arrFieldAtt as $k=>$v) {
275 275
 			$param[$v] = arrayToString($param[$v]);
276 276
 		}
277
+        // 处理日期(date)类型
278
+        $dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date');
279
+        if (!empty($dateField)) {
280
+            foreach ($param AS $key => $value) {
281
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
282
+            }
283
+        }
284
+
277 285
 		if ($this->data($param)->allowField(true)->save()) {
278 286
             //站内信
279 287
             $send_user_id = stringToArray($param['check_user_id']);
@@ -291,7 +299,8 @@ class Receivables extends Common
291 299
 			$data['receivables_id'] = $this->receivables_id;
292 300
 
293 301
 			//修改记录
294
-			updateActionLog($param['create_user_id'], 'crm_receivables', $this->receivables_id, '', '', '创建了回款');			
302
+			updateActionLog($param['create_user_id'], 'crm_receivables', $this->receivables_id, '', '', '创建了回款');
303
+            RecordActionLog($param['create_user_id'],'crm_receivables','save',$param['number'],'','','新增了回款'.$param['number']);
295 304
 
296 305
             # 添加活动记录
297 306
             Db::name('crm_activity')->insert([
@@ -375,7 +384,8 @@ class Receivables extends Common
375 384
 		
376 385
 		$fieldModel = new \app\admin\model\Field();
377 386
 		// 自动验证
378
-		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
387
+//		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
388
+		$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
379 389
 		$validate = new Validate($validateArr['rule'], $validateArr['message']);
380 390
 
381 391
 		$result = $validate->check($param);
@@ -384,15 +394,23 @@ class Receivables extends Common
384 394
 			return false;
385 395
 		}
386 396
 
387
-		//处理部门、员工、附件、多选类型字段
397
+		// 处理部门、员工、附件、多选类型字段
388 398
 		$arrFieldAtt = $fieldModel->getArrayField('crm_receivables');
389 399
 		foreach ($arrFieldAtt as $k=>$v) {
390
-			$param[$v] = arrayToString($param[$v]);
400
+            if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
391 401
 		}
402
+        // 处理日期(date)类型
403
+        $dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date');
404
+        if (!empty($dateField)) {
405
+            foreach ($param AS $key => $value) {
406
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
407
+            }
408
+        }
392 409
 
393 410
 		if ($this->update($param, ['receivables_id' => $receivables_id], true)) {
394 411
 			//修改记录
395 412
 			updateActionLog($param['user_id'], 'crm_receivables', $receivables_id, $dataInfo, $param);
413
+            RecordActionLog($param['user_id'], 'crm_receivables', 'update',$dataInfo['number'], $dataInfo, $param);
396 414
 			//站内信
397 415
 			$send_user_id = stringToArray($param['check_user_id']);
398 416
             if ($send_user_id && empty($param['check_status'])) {
@@ -440,7 +458,7 @@ class Receivables extends Common
440 458
      * @throws \think\db\exception\ModelNotFoundException
441 459
      * @throws \think\exception\DbException
442 460
      */
443
-   	public function getDataById($id = '')
461
+   	public function getDataById($id = '', $userId = 0)
444 462
    	{   		
445 463
    		$map['receivables_id'] = $id;
446 464
 		$dataInfo = db('crm_receivables')->where($map)->find();
@@ -464,6 +482,33 @@ class Receivables extends Common
464 482
         }
465 483
         $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
466 484
         $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
485
+        // 字段授权
486
+        if (!empty($userId)) {
487
+            $grantData = getFieldGrantData($userId);
488
+            $userLevel = isSuperAdministrators($userId);
489
+            foreach ($dataInfo AS $key => $value) {
490
+                if (!$userLevel && !empty($grantData['crm_receivables'])) {
491
+                    $status = getFieldGrantStatus($key, $grantData['crm_receivables']);
492
+
493
+                    # 查看权限
494
+                    if ($status['read'] == 0) unset($dataInfo[$key]);
495
+                }
496
+            }
497
+            if (!$userLevel && !empty($grantData['crm_receivables'])) {
498
+                # 客户名称
499
+                $customerStatus = getFieldGrantStatus('customer_id', $grantData['crm_receivables']);
500
+                if ($customerStatus['read'] == 0) {
501
+                    $dataInfo['customer_name'] = '';
502
+                    $dataInfo['customer_id_info'] = [];
503
+                }
504
+                # 合同金额
505
+                $contractMoneyStatus = getFieldGrantStatus('contract_money', $grantData['crm_receivables']);
506
+                if ($contractMoneyStatus['read'] == 0) $dataInfo['contract_id_info']['money'] = '';
507
+                # 合同名称
508
+                $contractMoneyStatus = getFieldGrantStatus('contract_money', $grantData['crm_receivables']);
509
+                if ($contractMoneyStatus['read'] == 0) $dataInfo['contract_id_info']['money'] = '';
510
+            }
511
+        }
467 512
 		return $dataInfo;
468 513
    	}
469 514
 	
@@ -651,7 +696,7 @@ class Receivables extends Common
651 696
 		$contractMoney = db('crm_contract')->where(['contract_id' => $contract_id])->value('money');
652 697
 		$unMoney = $contractMoney-$doneMoney;
653 698
 		$data['doneMoney'] = $doneMoney ? : '0.00';
654
-		$data['unMoney'] = $unMoney ? : '0.00';
699
+		$data['unMoney'] = (int)$unMoney>0 ? (int)$unMoney : '0.00';
655 700
 		$data['contractMoney'] = $contractMoney ? : '0.00';
656 701
 		return $data;
657 702
 	}
@@ -673,9 +718,9 @@ class Receivables extends Common
673 718
         $realname = Db::name('admin_user')->where('id', $receivables['create_user_id'])->value('realname');
674 719
 
675 720
         return [
676
-            'create_user_name' => $realname,
677
-            'create_time'      => date('Y-m-d H:i:s', $receivables['create_time']),
678
-            'update_time'      => date('Y-m-d H:i:s', $receivables['update_time'])
721
+            'create_user_id' => $realname,
722
+            'create_time' => date('Y-m-d H:i:s', $receivables['create_time']),
723
+            'update_time' => date('Y-m-d H:i:s', $receivables['update_time'])
679 724
         ];
680 725
     }
681 726
 }

+ 8
- 2
application/crm/model/Setting.php Zobrazit soubor

@@ -98,7 +98,10 @@ class Setting extends Common
98 98
                 ]);
99 99
             }
100 100
         }
101
-
101
+        # 系统操作日志
102
+        $user=new ApiCommon();
103
+        $userInfo=$user->userInfo;
104
+        SystemActionLog($userInfo['id'], 'crm_config','customer', 1, 'update','客户回访提醒' , '', '','设置了客户回访提醒');
102 105
         return true;
103 106
     }
104 107
 
@@ -172,7 +175,10 @@ class Setting extends Common
172 175
             }
173 176
 
174 177
             Db::commit();
175
-
178
+            # 系统操作日志
179
+            $user=new ApiCommon();
180
+            $userInfo=$user->userInfo;
181
+            SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1, 'update','编号规则设置' , '', '','设置了编号规则');
176 182
             return true;
177 183
         } catch (Exception $e) {
178 184
             Db::rollback();

+ 10
- 0
application/crm/view/preview/preview.html Zobrazit soubor

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

+ 4
- 0
application/oa/controller/Event.php Zobrazit soubor

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

+ 55
- 9
application/oa/controller/Examine.php Zobrazit soubor

@@ -27,7 +27,7 @@ class Examine extends ApiCommon
27 27
     {
28 28
         $action = [
29 29
             'permission'=>[''],
30
-            'allow'=>['index','save','read','update','delete','categorylist','check','revokecheck','category','categorysave','categoryupdate','categorydelete','categoryenables','excelexport','myexamine']
30
+            'allow'=>['index','save','read','update','delete','categorylist','check','revokecheck','category','categorysave','categoryupdate','categorydelete','categoryenables','excelexport','myexamine','examinesort']
31 31
         ];
32 32
         Hook::listen('check_auth',$action);
33 33
         $request = Request::instance();
@@ -37,7 +37,7 @@ class Examine extends ApiCommon
37 37
         }
38 38
         //权限判断
39 39
 //        $unAction = ['index','save','read','update','delete','categorylist','check','revokecheck','excelexport',];
40
-        $unAction = ['index','save','read','update','delete','categorylist','check','revokecheck','category','categorysave','categoryupdate','categorydelete','categoryenables','excelexport','myexamine'];
40
+        $unAction = ['index','save','read','update','delete','categorylist','check','revokecheck','category','categorysave','categoryupdate','categorydelete','categoryenables','excelexport','myexamine','examinesort'];
41 41
         if (!in_array($a, $unAction) && !checkPerByAction('admin', 'oa', 'examine')) {
42 42
             header('Content-Type:application/json; charset=utf-8');
43 43
             exit(json_encode(['code'=>102,'error'=>'无权操作']));
@@ -287,6 +287,10 @@ class Examine extends ApiCommon
287 287
 
288 288
         $res = $categoryModel->createData($param);
289 289
         if ($res) {
290
+            #添加系统操作日志
291
+            $userInfo=$this->userInfo;
292
+            SystemActionLog($userInfo['id'], 'admin_examine','approval', $res['category_id'],  'save', $param['title'], '', '','添加了办公审批流:'.$param['title']);
293
+    
290 294
             return resultArray(['data' => $res]);
291 295
         } else {
292 296
             return resultArray(['error' => $categoryModel->getError()]);
@@ -322,7 +326,7 @@ class Examine extends ApiCommon
322 326
         $param['structure_ids'] = arrayToString($param['structure_ids']);
323 327
         $param['update_user_id'] = $userInfo['id'];
324 328
         $param['create_time'] = time();
325
-        $param['update_time'] = time();
329
+//        $param['update_time'] = time();
326 330
         $param['status'] = 1;
327 331
         $resUpdate = $examineFlowModel->createData($param);
328 332
 
@@ -350,6 +354,10 @@ class Examine extends ApiCommon
350 354
             if (!$res) {
351 355
                 return resultArray(['error' => $categoryModel->getError()]);
352 356
             }
357
+            # 系统操作记录
358
+            $userInfo=$this->userInfo;
359
+            SystemActionLog($userInfo['id'], 'oa_examine','approval', $category_id, 'save', '办公审批' , '', '编辑了办公审批流:办公审批');
360
+    
353 361
             return resultArray(['data' => '编辑成功']);
354 362
         } else {
355 363
             return resultArray(['error' => $examineFlowModel->getError()]);
@@ -391,6 +399,14 @@ class Examine extends ApiCommon
391 399
         if (!$data) {
392 400
             return resultArray(['error' => $categoryModel->getError()]);
393 401
         }
402
+        $info=db('oa_examine_category')->where('category_id',$param['id'])->find();
403
+        # 系统操作记录
404
+        if($param['status']==0){
405
+            $content='停用了:'.$info['title'];
406
+        }else{
407
+            $content='启用了:'.$info['title'];
408
+        }
409
+        SystemActionLog($userInfo['id'], 'oa_examine','approval', $param['id'],  'delete',$info['title'] , '', '',$content);
394 410
         return resultArray(['data' => '操作成功']);
395 411
     }
396 412
 
@@ -404,17 +420,31 @@ class Examine extends ApiCommon
404 420
         $param = $this->param;
405 421
         $userInfo = $this->userInfo;
406 422
         $where = [];
407
-        $where['is_deleted'] = ['neq',1];
408
-        $where['status'] = ['eq',1];
423
+        $where['c.is_deleted'] = ['neq',1];
424
+        $where['c.status'] = ['eq',1];
425
+        $examineCategory=db('oa_examine_order')->where('user_id',$userInfo['id'])->column('work_id');
426
+        $category_id=db('oa_examine_category')->where(['create_user_id'=>$userInfo['id'],'is_deleted'=>['neq',1],'status'=>1])->column('category_id');
427
+        if($examineCategory && count($examineCategory)==count($category_id)){
428
+            $orderField = 'o.order';
429
+            $orderSort = 'asc';
430
+            $join=[['__OA_EXAMINE_ORDER__ o','o.work_id=c.category_id','LEFT']];
431
+            $where['o.user_id'] = ['eq',$userInfo['id']];
432
+        }else{
433
+            $orderField = 'c.category_id';
434
+            $orderSort = 'asc';
435
+            $join='';
436
+        }
409 437
         $list = db('oa_examine_category')
438
+            ->alias('c')
439
+            ->join($join)
410 440
                 ->where($where)
411 441
                 ->where(function ($query) use ($userInfo){
412
-                    $query->where('`user_ids` = "" AND `structure_ids` = ""')
442
+                    $query->where('c.`user_ids` = "" AND c.`structure_ids` = ""')
413 443
                     ->whereOr(function($query) use ($userInfo){
414
-                        $query->where('structure_ids','like','%,'.$userInfo['structure_id'].',%')
415
-                              ->whereOr('user_ids','like','%,'.$userInfo['id'].',%');
444
+                        $query->where('c.structure_ids','like','%,'.$userInfo['structure_id'].',%')
445
+                              ->whereOr('c.user_ids','like','%,'.$userInfo['id'].',%');
416 446
                     });
417
-                })->select();
447
+                })->order($orderField,$orderSort)->select();
418 448
         return resultArray(['data' => $list]);
419 449
     }
420 450
 
@@ -615,4 +645,20 @@ class Examine extends ApiCommon
615 645
         $data = $ExamineLogic->myExamine($param);
616 646
          return resultArray(['data' => $data]);
617 647
     }
648
+    
649
+    /**
650
+     * 办公审批类型排序
651
+     *
652
+     * @author      alvin guogaobo
653
+     * @version     1.0 版本号
654
+     * @since       2021/4/16 0016 14:02
655
+     */
656
+    public function examineSort(){
657
+        $examineIds  = $this->param['examineIds'];
658
+        $userInfo = $this->userInfo;
659
+        $examineCategory=new ExamineLogic();
660
+        $examineCategory->setWorkOrder($examineIds, $userInfo['id']);
661
+
662
+        return resultArray(['data' => '操作成功!']);
663
+    }
618 664
 }

+ 10
- 1
application/oa/controller/Log.php Zobrazit soubor

@@ -61,7 +61,7 @@ class Log extends ApiCommon
61 61
         }
62 62
     }
63 63
 
64
-    /**
64
+    /**commentSave
65 65
      * 日志列表
66 66
      * @return
67 67
      * @author Michael_xu
@@ -293,6 +293,15 @@ class Log extends ApiCommon
293 293
         $log_id = $param['log_id'];
294 294
         $param['user_id']=$userInfo['id'];
295 295
         $logModel = model('Log');
296
+        if(!empty($param['is_relation'])){
297
+            $indexLogic = new LogLogic();
298
+            $save = $indexLogic->oneBulletin($param);
299
+            $param['save_customer'] = $save['data']['customerNum'];
300
+            $param['save_business'] = $save['data']['businessNum'];
301
+            $param['save_contract'] = $save['data']['contractNum'];
302
+            $param['save_receivables'] = $save['data']['receivablesMoneyNum'];
303
+            $param['save_activity'] = $save['data']['recordNum'];
304
+        }
296 305
         if ($log_id) {
297 306
             $dataInfo = db('oa_log')->where(['log_id' => $log_id])->find();
298 307
             //权限判断

+ 4
- 2
application/oa/controller/Task.php Zobrazit soubor

@@ -132,9 +132,11 @@ class Task extends ApiCommon
132 132
         }
133 133
         //状态
134 134
         $status = $param['status'] ?: '';
135
-        if ($status) {
135
+        if ($status==1) {
136 136
             $where['t.status'] = $status;
137
-        } else {
137
+        } elseif($status==6) {
138
+            $where['t.status'] = 5;
139
+        }else{
138 140
             $where['t.status'] = [['=', 1], ['=', 5], 'OR'];
139 141
         }
140 142
         if ($param['main_user_id']) {

+ 27
- 0
application/oa/logic/ExamineLogic.php Zobrazit soubor

@@ -469,4 +469,31 @@ class ExamineLogic extends Common
469 469
         return $data;
470 470
     }
471 471
     
472
+    /**
473
+     * @param $workIds
474
+     * @param $userId
475
+     *
476
+     * @author      alvin guogaobo
477
+     * @version     1.0 版本号
478
+     * @since       2021/4/16 0016 14:00
479
+     */
480
+    public function setWorkOrder($examineIds, $userId)
481
+    {
482
+        $data = [];
483
+        
484
+        foreach ($examineIds AS $key => $value) {
485
+            $data[] = [
486
+                'work_id' => $value,
487
+                'user_id' => $userId,
488
+                'order'   => $key + 1
489
+            ];
490
+        }
491
+        if (!empty($data)) {
492
+            if (db('oa_examine_order')->where('user_id', $userId)->delete() === false) return false;
493
+            if (db('oa_examine_order')->insertAll($data) === false) return false;
494
+        }
495
+        
496
+        return true;
497
+    }
498
+    
472 499
 }

+ 58
- 13
application/oa/logic/LogLogic.php Zobrazit soubor

@@ -56,9 +56,6 @@ class LogLogic extends Common
56 56
         if ($request['category_id']) {
57 57
             $map['log.category_id'] = $request['category_id'];
58 58
         }
59
-        if ($request['create_user_id']) {
60
-            $map['log.create_user_id'] = $request['create_user_id'];
61
-        }
62 59
         if ($request['type']) {
63 60
             $timeAry = ByDateTime($request['type']);
64 61
             $between_time = [$timeAry[0], $timeAry[1]];
@@ -77,8 +74,8 @@ class LogLogic extends Common
77 74
         $dataWhere['structure_id'] = $request['structure_id'];
78 75
         $dataWhere['auth_user_ids'] = $auth_user_ids;
79 76
         $logMap = '';
80
-        if ($request['send_user_id'] != '') {
81
-            $map['log.create_user_id'] = ['in', trim(arrayToString($request['send_user_id']), ',')];
77
+        if ($request['create_user_id'] != '') {
78
+            $map['log.create_user_id'] = ['in', trim(arrayToString($request['create_user_id']), ',')];
82 79
         }
83 80
         switch ($by) {
84 81
             case 'me' :
@@ -242,17 +239,22 @@ class LogLogic extends Common
242 239
         $between_time = [$start_time['start_time'], $start_time['end_time']];
243 240
         $map['owner_user_id'] = $user_id;
244 241
         $map['create_time'] = array('between', $between_time);
245
-        $map1['update_time'] = array('between', $between_time);
242
+        $logMap=function ($query) use ($between_time) {
243
+            $query->where('create_time', array('between', $between_time))
244
+                ->whereOr('obtain_time', array('between', $between_time));
245
+        };
246 246
         $customerNum = Db::name('CrmCustomer')
247
-            ->where($map1)
247
+            ->where($logMap)
248 248
             ->count();
249 249
         $businessNum = Db::name('CrmBusiness')
250 250
             ->where($map)
251 251
             ->count();
252 252
         $contractNum = Db::name('CrmContract')
253
+            ->where('check_status',2)
253 254
             ->where($map)
254 255
             ->count();
255 256
         $receivablesMoneyNum = Db::name('CrmReceivables')
257
+            ->where('check_status',2)
256 258
             ->where($map)
257 259
             ->sum('money');
258 260
         unset($map['owner_user_id']);
@@ -308,17 +310,22 @@ class LogLogic extends Common
308 310
         switch ($type) {
309 311
             case '1':
310 312
                 if ($search) $map['customer.name'] = array('like', '%' . $search . '%');
311
-                $map['customer.update_time'] = array('between', $between_time);
313
+                $map['customer.create_time'] = array('between', $between_time);
314
+                $logMap['obtain_time'] = array('between', $between_time);
312 315
                 $activityData = Db::name('CrmCustomer')
313 316
                     ->alias('customer')
314 317
                     ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
315 318
                     ->where($map)
316 319
                     ->where($map1)
317 320
                     ->where($customerMap)
321
+                    ->whereOr($logMap)
318 322
                     ->order('customer.customer_id desc')
319
-                    ->field('customer.customer_id,customer.name,customer.deal_status,customer.create_time,user.realname as owner_user_name,customer.last_time')
323
+                    ->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')
320 324
                     ->page($param['page'],$param['limit'])
321 325
                     ->select();
326
+                foreach ($activityData as $k => $v){
327
+                    $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;
328
+                }
322 329
                 $dataCount = Db::name('CrmCustomer')
323 330
                     ->alias('customer')
324 331
                     ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
@@ -338,8 +345,24 @@ class LogLogic extends Common
338 345
                     ->where($map2)
339 346
                     ->order('business.business_id desc')
340 347
                     ->page($param['page'],$param['limit'])
341
-                    ->field('business.business_id,business.name,status.name as status_name,business.create_time,user.realname as owner_user_name,business.last_time')
348
+                    ->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')
342 349
                     ->select();
350
+                $endStatus = ['1' => '赢单', '2' => '输单', '3' => '无效'];
351
+                foreach ($activityData as $k=>$v){
352
+                    $statusInfo = [];
353
+                    $status_count = 0;
354
+                    if (!$v['is_end']) {
355
+                        $statusInfo = db('crm_business_status')->where('status_id', $v['status_id'])->find();
356
+                        if ($statusInfo['order_id'] < 99) {
357
+                            $status_count = db('crm_business_status')->where('type_id', ['eq', $v['type_id']])->count();
358
+                        }
359
+                        //进度
360
+                        $activityData[$k]['status_progress'] = [$statusInfo['order_id'], $status_count + 1];
361
+                    } else {
362
+                        $statusInfo['name'] = $endStatus[$v['is_end']];
363
+                    }
364
+                    $activityData[$k]['status_id_info'] = $statusInfo['name'];//销售阶段
365
+                }
343 366
                 $dataCount = Db::name('CrmBusiness')
344 367
                     ->alias('business')
345 368
                     ->join('__CRM_BUSINESS_STATUS__ status', 'status.status_id=business.status_id')
@@ -351,15 +374,32 @@ class LogLogic extends Common
351 374
             case '3':
352 375
                 $map['contract.name'] = array('like', '%' . $search . '%');
353 376
                 $map['contract.create_time'] = array('between', $between_time);
377
+                $map['contract.check_status'] = 2;
354 378
                 $activityData = Db::name('CrmContract')
355 379
                     ->alias('contract')
356 380
                     ->join('__ADMIN_USER__ u', 'u.id = contract.owner_user_id', 'LEFT')
381
+                    ->join('CrmReceivables receivables','receivables.contract_id = contract.contract_id AND receivables.check_status = 2','LEFT')
357 382
                     ->where($map)
358 383
                     ->where($map3)
359 384
                     ->order('contract.contract_id desc')
360 385
                     ->page($param['page'],$param['limit'])
361
-                    ->field('contract.contract_id,contract.name,contract.create_time,contract.check_status,u.realname as order_user_name')
386
+                    ->field(['contract.contract_id',
387
+                        'contract.name',
388
+                        'contract.create_time',
389
+                        'contract.check_status',
390
+                        'contract.order_date',
391
+                        'contract.money',
392
+                        'u.realname as order_user_name',
393
+                        'ifnull(SUM(receivables.money), 0)' => 'done_money',
394
+                        '(contract.money - ifnull(SUM(receivables.money), 0))' => 'un_money'])
362 395
                     ->select();
396
+                foreach ($activityData as $k => $v){
397
+                    if(!empty($v['contract_id'])){
398
+                        $activityData[$k]['order_date'] = ($v['order_date']!='0000-00-00') ? $v['order_date'] : null;
399
+                    }else{
400
+                        $activityData=[];
401
+                    }
402
+                }
363 403
                 $dataCount = Db::name('CrmContract')
364 404
                     ->alias('contract')
365 405
                     ->join('__ADMIN_USER__ u', 'u.id = contract.owner_user_id', 'LEFT')
@@ -370,10 +410,11 @@ class LogLogic extends Common
370 410
             case '4':
371 411
                 $map['receivables.number'] = array('like', '%' . $search . '%');
372 412
                 $map['receivables.create_time'] = array('between', $between_time);
413
+                $map['receivables.check_status'] = 2;
373 414
                 $activityData = Db::name('CrmReceivables')
374 415
                     ->alias('receivables')
375 416
                     ->join('__ADMIN_USER__ user', 'user.id = receivables.owner_user_id', 'LEFT')
376
-                    ->field('receivables.receivables_id,receivables.number,receivables.return_time,user.realname as owner_user_name')
417
+                    ->field('receivables.receivables_id,receivables.number,receivables.return_time,receivables.money,user.realname as owner_user_name')
377 418
                     ->where($map)
378 419
                     ->where($map4)
379 420
                     ->page($param['page'],$param['limit'])
@@ -690,7 +731,7 @@ class LogLogic extends Common
690 731
     }
691 732
 
692 733
     /**
693
-     *
734
+     * 跟进记录列表
694 735
      * @param $param
695 736
      * @return array
696 737
      * @throws \think\Exception
@@ -966,6 +1007,10 @@ class LogLogic extends Common
966 1007
         } else {
967 1008
             $item['bulletin'] = 0;
968 1009
         }
1010
+        # 发送人信息
1011
+        $sendUserList = !empty($item['send_user_ids']) ? db('admin_user')->field(['id', 'realname'])->whereIn('id', stringToArray($item['send_user_ids']))->select() : [];
1012
+        $item['sendUserList'] = $sendUserList;
1013
+
969 1014
         $data = [];
970 1015
         $data['list'] = $item;
971 1016
         return $data;

+ 0
- 0
application/oa/logic/TaskLogic.php Zobrazit soubor


Některé soubory nejsou zobrazny, neboť je v této revizi změněno mnoho souborů