Michael_xu преди 5 години
родител
ревизия
ce8c8fa3eb
променени са 84 файла, в които са добавени 3346 реда и са изтрити 2216 реда
  1. 2
    2
      application/admin/common.php
  2. 8
    5
      application/admin/controller/ApiCommon.php
  3. 2
    1
      application/admin/controller/Base.php
  4. 25
    15
      application/admin/controller/ExamineFlow.php
  5. 16
    1
      application/admin/controller/Index.php
  6. 22
    2
      application/admin/controller/Install.php
  7. 3
    0
      application/admin/controller/Users.php
  8. 54
    0
      application/admin/logic/InitializeLogic.php
  9. 5
    5
      application/admin/logic/MessageLogic.php
  10. 3
    0
      application/admin/model/ActionRecord.php
  11. 5
    5
      application/admin/model/Admin.php
  12. 20
    15
      application/admin/model/Common.php
  13. 24
    2
      application/admin/model/ExamineRecord.php
  14. 28
    6
      application/admin/model/ExamineStep.php
  15. 120
    143
      application/admin/model/Excel.php
  16. 227
    161
      application/admin/model/Field.php
  17. 13
    0
      application/admin/model/File.php
  18. 3
    1
      application/admin/model/Group.php
  19. 14
    40
      application/admin/model/User.php
  20. 1
    1
      application/admin/view/install/step2.html
  21. 1
    1
      application/admin/view/install/step5.html
  22. 97
    0
      application/admin/view/install/step6.html
  23. 151
    156
      application/bi/controller/Achievement.php
  24. 48
    39
      application/bi/controller/Business.php
  25. 3
    3
      application/bi/controller/Contract.php
  26. 95
    48
      application/bi/controller/Customer.php
  27. 0
    1
      application/bi/controller/Log.php
  28. 10
    12
      application/bi/controller/Product.php
  29. 61
    51
      application/bi/controller/Ranking.php
  30. 20
    6
      application/bi/logic/BiCustomerLogic.php
  31. 53
    32
      application/bi/logic/ExcelLogic.php
  32. 4
    8
      application/bi/model/Business.php
  33. 2
    3
      application/bi/model/Examine.php
  34. 11
    6
      application/common.php
  35. 4
    3
      application/common/behavior/AuthenticateBehavior.php
  36. 3
    2
      application/common/controller/Common.php
  37. 16
    12
      application/crm/controller/Achievement.php
  38. 32
    12
      application/crm/controller/Business.php
  39. 16
    8
      application/crm/controller/Contacts.php
  40. 14
    5
      application/crm/controller/Contract.php
  41. 272
    252
      application/crm/controller/Customer.php
  42. 34
    42
      application/crm/controller/Index.php
  43. 42
    6
      application/crm/controller/Invoice.php
  44. 5
    1
      application/crm/controller/Leads.php
  45. 119
    62
      application/crm/controller/Message.php
  46. 1
    1
      application/crm/controller/Product.php
  47. 1
    3
      application/crm/controller/Receivables.php
  48. 3
    1
      application/crm/controller/Visit.php
  49. 46
    89
      application/crm/logic/ActivityLogic.php
  50. 8
    28
      application/crm/logic/CommonLogic.php
  51. 79
    40
      application/crm/logic/IndexLogic.php
  52. 21
    8
      application/crm/logic/InvoiceLogic.php
  53. 9
    5
      application/crm/logic/VisitLogic.php
  54. 8
    4
      application/crm/model/Achievement.php
  55. 40
    19
      application/crm/model/Business.php
  56. 7
    2
      application/crm/model/BusinessStatus.php
  57. 10
    8
      application/crm/model/Contacts.php
  58. 122
    45
      application/crm/model/Contract.php
  59. 44
    34
      application/crm/model/Customer.php
  60. 187
    183
      application/crm/model/Index.php
  61. 15
    5
      application/crm/model/Leads.php
  62. 9
    5
      application/crm/model/Product.php
  63. 65
    17
      application/crm/model/Receivables.php
  64. 19
    9
      application/crm/model/ReceivablesPlan.php
  65. 25
    1
      application/crm/traits/AutoNumberTrait.php
  66. 153
    0
      application/crm/traits/SearchConditionTrait.php
  67. 19
    0
      application/oa/controller/Task.php
  68. 18
    2
      application/oa/logic/LogLogic.php
  69. 75
    34
      application/oa/logic/TaskLogic.php
  70. 1
    0
      application/oa/model/Announcement.php
  71. 1
    0
      application/oa/model/Event.php
  72. 20
    14
      application/oa/model/Examine.php
  73. 10
    10
      application/oa/model/Log.php
  74. 377
    277
      application/work/controller/Task.php
  75. 16
    18
      application/work/controller/Work.php
  76. 96
    122
      application/work/logic/WorkLogic.php
  77. 18
    15
      application/work/model/Task.php
  78. 12
    11
      config/config.php
  79. 5
    1
      config/route_admin.php
  80. 4
    2
      config/route_work.php
  81. 2
    2
      config/version.php
  82. 47
    17
      public/sql/5kcrm.sql
  83. 31
    0
      public/sql/update_sql_20210316.sql
  84. 14
    8
      public/static/js/step2.js

+ 2
- 2
application/admin/common.php Целия файл

173
 
173
 
174
 /**
174
 /**
175
  * 验证序列号
175
  * 验证序列号
176
- * @param
176
+ * @param 
177
  * @return
177
  * @return
178
- */
178
+ */        
179
 function checkWkCode($wkcode) {
179
 function checkWkCode($wkcode) {
180
     $pub = formatPubKey(config('public_key'));
180
     $pub = formatPubKey(config('public_key'));
181
     $openssl_pub = openssl_pkey_get_public($pub);
181
     $openssl_pub = openssl_pkey_get_public($pub);

+ 8
- 5
application/admin/controller/ApiCommon.php Целия файл

7
 
7
 
8
 namespace app\admin\controller;
8
 namespace app\admin\controller;
9
 
9
 
10
+use think\Cache;
10
 use think\Request;
11
 use think\Request;
11
 use think\Db;
12
 use think\Db;
12
 use app\common\adapter\AuthAdapter;
13
 use app\common\adapter\AuthAdapter;
22
         $header = Request::instance()->header();
23
         $header = Request::instance()->header();
23
         $request = Request::instance();
24
         $request = Request::instance();
24
         
25
         
25
-        $authKey = $header['authkey'];
26
-        $sessionId = $header['sessionid'];
26
+        $authKey = trim($header['authkey']);
27
+        $sessionId = trim($header['sessionid']);
27
         $paramArr = $request->param();
28
         $paramArr = $request->param();
28
         $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
29
         $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
29
-        $cache = cache('Auth_'.$authKey.$platform);         
30
+        $cache = Cache::get('Auth_'.$authKey.$platform);
31
+//        $cache = cache('Auth_'.$authKey.$platform);
30
 
32
 
31
         // 校验sessionid和authKey
33
         // 校验sessionid和authKey
32
         if (empty($sessionId) || empty($authKey) || empty($cache)) {
34
         if (empty($sessionId) || empty($authKey) || empty($cache)) {
36
         }
38
         }
37
         //登录有效时间
39
         //登录有效时间
38
         $cacheConfig = config('cache');
40
         $cacheConfig = config('cache');
39
-        $loginExpire = $cacheConfig['expire'] ? : 86400*3;
41
+        $loginExpire = !empty($cacheConfig['expire']) ? $cacheConfig['expire'] : 86400 * 30;
40
 
42
 
41
         // 检查账号有效性
43
         // 检查账号有效性
42
         $userInfo = $cache['userInfo'];
44
         $userInfo = $cache['userInfo'];
49
         }
51
         }
50
         session('user_id', $userInfo['id']);
52
         session('user_id', $userInfo['id']);
51
         // 更新缓存
53
         // 更新缓存
52
-        cache('Auth_'.$authKey, $cache, $loginExpire);           
54
+        Cache::set('Auth_'.$authKey, $cache, $loginExpire);
55
+//        cache('Auth_'.$authKey, $cache, $loginExpire, 'UserToken');
53
         // $GLOBALS['userInfo'] = $userInfo;
56
         // $GLOBALS['userInfo'] = $userInfo;
54
     }
57
     }
55
 }
58
 }

+ 2
- 1
application/admin/controller/Base.php Целия файл

9
 
9
 
10
 use com\verify\HonrayVerify;
10
 use com\verify\HonrayVerify;
11
 use app\common\controller\Common;
11
 use app\common\controller\Common;
12
+use think\Cache;
12
 use think\Request;
13
 use think\Request;
13
 use think\Session;
14
 use think\Session;
14
 
15
 
41
         $request = Request::instance();
42
         $request = Request::instance();
42
         $paramArr = $request->param();
43
         $paramArr = $request->param();
43
         $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
44
         $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
44
-        $cache = cache('Auth_'.$authKey.$platform,null);
45
+        $cache = Cache::set('Auth_'.trim($header['authkey']).$platform,null);
45
         cookie(null, '72crm_');
46
         cookie(null, '72crm_');
46
         cookie(null, '5kcrm_');
47
         cookie(null, '5kcrm_');
47
         session('user_id','null');
48
         session('user_id','null');

+ 25
- 15
application/admin/controller/ExamineFlow.php Целия файл

258
     {
258
     {
259
         $param = $this->param;
259
         $param = $this->param;
260
         $userInfo = $this->userInfo;
260
         $userInfo = $this->userInfo;
261
+       $data= $this->checkFlow($param,$userInfo);
262
+        return resultArray(['data' => $data]);
263
+    }
264
+    
265
+    /**
266
+     * 固定审批流审批流程人员数据
267
+     * @param $param
268
+     * @param $userInfo
269
+     *
270
+     * @author      alvin guogaobo
271
+     * @version     1.0 版本号
272
+     * @since       2021/3/15 0015 13:37
273
+     */
274
+    public function checkFlow($param,$userInfo){
261
         $examineStepModel = model('ExamineStep');
275
         $examineStepModel = model('ExamineStep');
262
         $examineFlowModel = model('ExamineFlow');
276
         $examineFlowModel = model('ExamineFlow');
263
-
264
         $check_user_id = $userInfo['id'];
277
         $check_user_id = $userInfo['id'];
265
         $flow_id = $param['flow_id'];
278
         $flow_id = $param['flow_id'];
266
         $types = $param['types'];
279
         $types = $param['types'];
269
         if (!$types || !in_array($types, $typesArr)) {
282
         if (!$types || !in_array($types, $typesArr)) {
270
             return resultArray(['error' => '参数错误']);
283
             return resultArray(['error' => '参数错误']);
271
         }
284
         }
272
-        
285
+    
273
         if ($flow_id) {
286
         if ($flow_id) {
274
             $examineFlowData = $examineFlowModel->getDataById($param['flow_id']);
287
             $examineFlowData = $examineFlowModel->getDataById($param['flow_id']);
275
             if (!$examineFlowData) {
288
             if (!$examineFlowData) {
281
                 $user_id = $typesInfo['dataInfo']['create_user_id'];
294
                 $user_id = $typesInfo['dataInfo']['create_user_id'];
282
             }
295
             }
283
             if (!$user_id) {
296
             if (!$user_id) {
284
-                return resultArray(['error' => '参数错误']);    
285
-            }      
297
+                return resultArray(['error' => '参数错误']);
298
+            }
286
         } else {
299
         } else {
287
             $user_id = $check_user_id;
300
             $user_id = $check_user_id;
288
             // 获取符合条件的审批流
301
             // 获取符合条件的审批流
292
                 if (in_array($types, ['crm_contract', 'crm_receivables', 'crm_invoice'])) {
305
                 if (in_array($types, ['crm_contract', 'crm_receivables', 'crm_invoice'])) {
293
                     return resultArray(['data' => ['examineStatus' => false]]);
306
                     return resultArray(['data' => ['examineStatus' => false]]);
294
                 }
307
                 }
295
-
308
+            
296
                 return resultArray(['error' => '无可用审批流,请联系管理员']);
309
                 return resultArray(['error' => '无可用审批流,请联系管理员']);
297
-            } 
298
-            $flow_id = $examineFlowData['flow_id'];         
310
+            }
311
+            $flow_id = $examineFlowData['flow_id'];
299
         }
312
         }
300
         if ($types == 'oa_examine') {
313
         if ($types == 'oa_examine') {
301
             $category_id = db('oa_examine')->where(['examine_id' => $types_id])->value('category_id');
314
             $category_id = db('oa_examine')->where(['examine_id' => $types_id])->value('category_id');
320
         }
333
         }
321
         $data = [];
334
         $data = [];
322
         $data['config'] = (int) $examineFlowData['config']; //1固定,0自选
335
         $data['config'] = (int) $examineFlowData['config']; //1固定,0自选
323
-        $data['stepList'] = $stepList ? : []; 
336
+        $data['stepList'] = $stepList ? : [];
324
         $data['examine_user'] = $list ? : [];
337
         $data['examine_user'] = $list ? : [];
325
         $data['is_check'] = $stepInfo['is_check'] ? : 0;
338
         $data['is_check'] = $stepInfo['is_check'] ? : 0;
326
         $data['is_recheck'] = $stepInfo['is_recheck'] ? : 0;
339
         $data['is_recheck'] = $stepInfo['is_recheck'] ? : 0;
327
         $data['examineStatus'] = true;
340
         $data['examineStatus'] = true;
328
-        return resultArray(['data' => $data]);
341
+        return $data;
329
     }
342
     }
330
-
331
     /**
343
     /**
332
      * 自选审批人列表(授权审批类型)
344
      * 自选审批人列表(授权审批类型)
333
      * @author Michael_xu
345
      * @author Michael_xu
360
      */
372
      */
361
     public function recordList()
373
     public function recordList()
362
     {
374
     {
363
-        $param = $this->param;
364
-        $userInfo = $this->userInfo;
365
         $examineRecordModel = model('ExamineRecord');
375
         $examineRecordModel = model('ExamineRecord');
366
-        $list = $examineRecordModel->getDataList($param) ? : [];
367
-        return resultArray(['data' => $list]);
368
-    }        
376
+        $data = $examineRecordModel->getDataList($this->param);
377
+        return resultArray(['data' => $data]);
378
+    }
369
 }
379
 }

+ 16
- 1
application/admin/controller/Index.php Целия файл

24
         $action = [
24
         $action = [
25
             'permission' => [],
25
             'permission' => [],
26
             'allow' => ['fields', 'fieldrecord', 'authlist','sort','updatesort',
26
             'allow' => ['fields', 'fieldrecord', 'authlist','sort','updatesort',
27
-            'importnum','importinfo','importlist'],
27
+            'importnum','importinfo','importlist','readnotice'],
28
         ];
28
         ];
29
         Hook::listen('check_auth', $action);
29
         Hook::listen('check_auth', $action);
30
         $request = Request::instance();
30
         $request = Request::instance();
152
         $data = $excelModel->importList($param);
152
         $data = $excelModel->importList($param);
153
         return resultArray(['data'=>$data]);
153
         return resultArray(['data'=>$data]);
154
     }
154
     }
155
+
156
+    /**
157
+     * 升级公告
158
+     * @author fanqi
159
+     * @date 2021-03-15
160
+     * @return \think\response\Json
161
+     */
162
+    public function readNotice()
163
+    {
164
+        $userInfo = $this->userInfo;
165
+
166
+        if (!empty($userInfo['id'])) db('admin_user')->where('id', $userInfo['id'])->update(['is_read_notice' => 1]);
167
+
168
+        return resultArray(['data' => '']);
169
+    }
155
 }
170
 }

+ 22
- 2
application/admin/controller/Install.php Целия файл

110
         $db_config['database'] = $param['databaseName'];
110
         $db_config['database'] = $param['databaseName'];
111
         $db_config['username'] = $param['databaseUser'];
111
         $db_config['username'] = $param['databaseUser'];
112
         $db_config['password'] = $param['databasePwd'];        
112
         $db_config['password'] = $param['databasePwd'];        
113
-        $db_config['prefix'] = $param['databaseTable'];
114
-        
113
+        $db_config['prefix'] = '5kcrm_';
114
+//        $db_config['prefix'] = $param['databaseTable'];
115
+
115
         $username = $param['root'];
116
         $username = $param['root'];
116
         $password = $param['pwd'];
117
         $password = $param['pwd'];
117
         $wkcode = $param['wkcode'];
118
         $wkcode = $param['wkcode'];
202
         return resultArray(['data'=>'安装成功']);
203
         return resultArray(['data'=>'安装成功']);
203
     }
204
     }
204
 
205
 
206
+    /**
207
+     * 安装成功界面
208
+     *
209
+     * @author fnqi
210
+     * @date 2021-03-11
211
+     * @return mixed
212
+     */
205
     public function step5()
213
     public function step5()
214
+    {
215
+        return $this->fetch();
216
+    }
217
+
218
+    /**
219
+     * 安装超时界面
220
+     *
221
+     * @author fanqi
222
+     * @date 2021-03-11
223
+     * @return mixed
224
+     */
225
+    public function step6()
206
     {
226
     {
207
         return $this->fetch();
227
         return $this->fetch();
208
     }
228
     }

+ 3
- 0
application/admin/controller/Users.php Целия файл

305
         $param = $this->param;
305
         $param = $this->param;
306
         $userInfo = $this->userInfo;
306
         $userInfo = $this->userInfo;
307
         $userModel = model('User');
307
         $userModel = model('User');
308
+
309
+        if (empty($param['new_pwd']) || empty($param['old_pwd'])) return resultArray(['error' => '密码不能为空!']);
310
+
308
         if ($param['id'] && (int)$param['id'] !== $userInfo['id']) {
311
         if ($param['id'] && (int)$param['id'] !== $userInfo['id']) {
309
             //权限判断
312
             //权限判断
310
             if (!checkPerByAction('admin', 'users', 'update')) {
313
             if (!checkPerByAction('admin', 'users', 'update')) {

+ 54
- 0
application/admin/logic/InitializeLogic.php Целия файл

80
             # 查询产品文件数据
80
             # 查询产品文件数据
81
             $productFileInfo = $this->getFileList($productFileIds);
81
             $productFileInfo = $this->getFileList($productFileIds);
82
 
82
 
83
+            # 获取产品图和产品详情图附件ID
84
+            $productDetailsIds  = [];
85
+            $productDetailFiles = Db::name('crm_product')->field(['cover_images', 'details_images'])->select();
86
+            foreach ($productDetailFiles AS $key => $value) {
87
+                if (!empty($value['cover_images'])) $productDetailsIds = array_merge($productDetailsIds, explode(',', $value['cover_images']));
88
+                if (!empty($value['details_images'])) $productDetailsIds = array_merge($productDetailsIds, explode(',', $value['details_images']));
89
+            }
90
+
91
+            # 合并附件ID数据
92
+            $productFileIds = array_merge($productFileIds, $productDetailsIds);
93
+
94
+            # 获取产品图和产品详情图文件数据
95
+            $productDetailsFiles = $this->getFileList($productDetailsIds);
96
+
83
             # 合并附件数据
97
             # 合并附件数据
98
+            $files = array_merge($files, $productDetailsFiles);
84
             $files = array_merge($files, $productFileInfo);
99
             $files = array_merge($files, $productFileInfo);
85
 
100
 
86
             # 删除产品分类表
101
             # 删除产品分类表
385
             # ------ 清除跟客户模块有关的管理数据表 END ------ #
400
             # ------ 清除跟客户模块有关的管理数据表 END ------ #
386
 
401
 
387
 
402
 
403
+            # ------ 清除自动编号数据 START ------ #
404
+            $time = time();
405
+            Db::query("TRUNCATE TABLE ".$prefix."crm_number_sequence");
406
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (1, 1, 1, 'HT', null, null, null, null, ".$time.", 1, null, 0, 1)");
407
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (2, 2, 2, 'yyyyMMdd', null, null, null, null, ".$time.", 1, null, 0, 1)");
408
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (3, 3, 3, 1, 1, 1, 1, ".$time.", ".$time.", 1, null, 0, 1)");
409
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (4, 1, 1, 'HK', null, null, null, null, ".$time.", 1, null, 0, 2)");
410
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (5, 2, 2, 'yyyyMMdd', null, null, null, null, ".$time.", 1, null, 0, 2)");
411
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (6, 3, 3, 1, 1, 1, 1, ".$time.", ".$time.", 1, null, 0, 2)");
412
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (7, 1, 1, 'HF', null, null, null, null, ".$time.", 1, null, 0, 3)");
413
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (8, 2, 2, 'yyyyMMdd', null, null, null, null, ".$time.", 1, null, 0, 3)");
414
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (9, 3, 3, 1, 1, 1, 1, ".$time.", ".$time.", 1, null, 0, 3)");
415
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (10, 1, 2, 'yyyyMMdd', null, null, null, null, ".$time.", 1, null, 0, 4)");
416
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (11, 2, 1, 'FP', null, null, null, null, ".$time.", 1, null, 0, 4)");
417
+            Db::query("INSERT INTO `".$prefix."crm_number_sequence` VALUES (12, 3, 3, 1, 1, 1, 1, ".$time.", ".$time.", 1, null, 0, 4)");
418
+            # ------ 清除自动编号数据 END ------ #
419
+
420
+
421
+            # ------ 设置跟进记录常用语 START ------ #
422
+            $phrase = ['电话无人接听', '客户无意向', '客户意向度适中,后续继续跟进', '客户意向度较强,成交几率较大'];
423
+            $phraseId = db('crm_config')->where('name', 'activity_phrase')->value('id');
424
+            if (!empty($phraseId)) {
425
+                db('crm_config')->where('id', $phraseId)->update([
426
+                    'value' => serialize($phrase)
427
+                ]);
428
+            } else {
429
+                db('crm_config')->insert([
430
+                    'name' => 'activity_phrase',
431
+                    'value' => serialize($phrase),
432
+                    'description' => '跟进记录常用语'
433
+                ]);
434
+            }
435
+            # ------ 设置跟进记录常用语 END ------ #
436
+
437
+
388
             # ------ 删除审批记录 START ------ #
438
             # ------ 删除审批记录 START ------ #
389
             Db::name('admin_examine_record')->whereLike('types', 'crm%')->delete();
439
             Db::name('admin_examine_record')->whereLike('types', 'crm%')->delete();
390
             Db::query("ALTER TABLE ".$prefix."admin_examine_record AUTO_INCREMENT = 1");
440
             Db::query("ALTER TABLE ".$prefix."admin_examine_record AUTO_INCREMENT = 1");
833
             # ------ 清除评论和消息数据 END ------ #
883
             # ------ 清除评论和消息数据 END ------ #
834
 
884
 
835
 
885
 
886
+            # 清除任务关联客户模块表并重置字段ID
887
+            Db::query("TRUNCATE TABLE ".$prefix."task_relation");
888
+
889
+
836
             # ------ 重置附件表自增ID START ------ #
890
             # ------ 重置附件表自增ID START ------ #
837
             Db::query("ALTER TABLE ".$prefix."admin_file AUTO_INCREMENT = 1");
891
             Db::query("ALTER TABLE ".$prefix."admin_file AUTO_INCREMENT = 1");
838
             # ------ 重置附件表自增ID END ------ #
892
             # ------ 重置附件表自增ID END ------ #

+ 5
- 5
application/admin/logic/MessageLogic.php Целия файл

12
         switch ($label) {
12
         switch ($label) {
13
             
13
             
14
             case '1':  //任务
14
             case '1':  //任务
15
-                $where = array('in', [1, 2, 3]);//
15
+                $where = array('in', [1, 2, 3,27]);//
16
                 break;
16
                 break;
17
             case '2':  //日志
17
             case '2':  //日志
18
                 $where = array('in', [4, 5]);//27项目导入
18
                 $where = array('in', [4, 5]);//27项目导入
27
                 $where = 10;
27
                 $where = 10;
28
                 break;
28
                 break;
29
             case '6' :  //客户管理
29
             case '6' :  //客户管理
30
-                $where = array('in', [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 16, 27, 28, 29, 30]);
30
+                $where = array('in', [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30]);
31
                 break;
31
                 break;
32
             case '4' :
32
             case '4' :
33
                 break;
33
                 break;
34
             default:
34
             default:
35
-                $where = array('in', [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 16, 27, 28, 29, 30]);//17181920
35
+                $where = array('in', [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]);//17181920
36
         }
36
         }
37
         return $where;
37
         return $where;
38
     }
38
     }
97
                         ])
97
                         ])
98
                     ->select();
98
                     ->select();
99
                 $list[$k]['content'] = $content[$k]['content'];
99
                 $list[$k]['content'] = $content[$k]['content'];
100
-            } elseif (in_array($v['type'], ['7','12', '15',25])) {
101
-                $content = db('admin_examine_record')->where(['types_id' => $v['action_id'], 'types' => ['like', '%' . $v['controller_name' . '%']], 'check_user_id' => $v['from_user_id']])->field('content')->find();
100
+            } elseif (in_array($v['type'], [7,12, 15,25])) {
101
+                $content = db('admin_examine_record')->where(['types_id' => $v['action_id'], 'types' => ['like', '%' . $v['controller_name'] . '%'], 'check_user_id' => $v['from_user_id']])->field('content')->find();
102
                 if ($content['content']) {
102
                 if ($content['content']) {
103
                     $list[$k]['content'] = $content['content'];
103
                     $list[$k]['content'] = $content['content'];
104
                 }
104
                 }

+ 3
- 0
application/admin/model/ActionRecord.php Целия файл

36
 			if($leads_id){
36
 			if($leads_id){
37
 				$leads_dataList = db('admin_action_record')->where(['types' => 'crm_leads','action_id' => $leads_id])->order('id','desc')->select();
37
 				$leads_dataList = db('admin_action_record')->where(['types' => 'crm_leads','action_id' => $leads_id])->order('id','desc')->select();
38
 				$dataList = array_merge($leads_dataList, $dataList);
38
 				$dataList = array_merge($leads_dataList, $dataList);
39
+                # 对线索和客户的合并数据进行排序
40
+                $sortData = array_column($dataList, 'create_time');
41
+                array_multisort($sortData,SORT_DESC , $dataList);
39
 			}
42
 			}
40
 		}
43
 		}
41
 		$userModel = model('User');
44
 		$userModel = model('User');

+ 5
- 5
application/admin/model/Admin.php Целия файл

28
         $structure_id = $apiCommon->userInfo['structure_id'];
28
         $structure_id = $apiCommon->userInfo['structure_id'];
29
         //员工IDS
29
         //员工IDS
30
         $user_ids = [];
30
         $user_ids = [];
31
-        if ($param['userId']) {
32
-            $user_ids = array($param['userId']);
31
+        if ($param['user_id']) {
32
+            $user_ids = array($param['user_id']);
33
         }
33
         }
34
-        if ($param['deptId']) {
35
-            $userModel->getSubUserByStr($param['deptId'], 2);
34
+        if ($param['structure_id']) {
35
+            $userModel->getSubUserByStr($param['structure_id'], 2);
36
         }        
36
         }        
37
         if ($param['dataType']) {
37
         if ($param['dataType']) {
38
             switch ($param['dataType']) {
38
             switch ($param['dataType']) {
65
                     }
65
                     }
66
                 }
66
                 }
67
             }
67
             }
68
-            if (!$user_ids) $user_ids = getSubUserId(true);            
69
         }
68
         }
69
+        if (!$user_ids) $user_ids = getSubUserId(true,0, $apiCommon->userInfo['id']);
70
         $perUserIds = $perUserIds ? : getSubUserId(); //权限范围内userIds
70
         $perUserIds = $perUserIds ? : getSubUserId(); //权限范围内userIds
71
         $userIds = [];
71
         $userIds = [];
72
         if ($user_ids) {
72
         if ($user_ids) {

+ 20
- 15
application/admin/model/Common.php Целия файл

295
 	 */
295
 	 */
296
 	public function exportHandle($list, $field_list, $type = '')
296
 	public function exportHandle($list, $field_list, $type = '')
297
 	{
297
 	{
298
-	 
298
+	
299
 		foreach ($list as &$val) {
299
 		foreach ($list as &$val) {
300
 			foreach ($field_list as $field) {
300
 			foreach ($field_list as $field) {
301
 				switch ($field['form_type']) {
301
 				switch ($field['form_type']) {
302
 					case 'user':
302
 					case 'user':
303
-						if (isset($val[$field['field'] . '_info']['realname'])) {
304
-							$val[$field['field']] = $val[$field['field'] . '_info']['realname'];
305
-						} else {
306
-							$val[$field['field']] = implode(',', array_column($val[$field['field'] . '_info'], 'realname'));
303
+						if (isset($val[$field['field'] . 'name'])) {
304
+							$val[$field['field']] = $val[$field['field'] . 'name'];
307
 						}
305
 						}
306
+//						else {
307
+//							$val[$field['field']] = implode(',', array_column($val[$field['field'] . '_info'], 'realname'));
308
+//						}
308
 						break;
309
 						break;
309
 					case 'structure':
310
 					case 'structure':
310
-						$temp = array_map(function ($val) { return $val->toarray(); }, $val[$field['field'] . '_info']);
311
-						$val[$field['field']] = implode(',', array_column($temp, 'name'));
311
+//						$temp = array_map(function ($val) { return $val->toarray(); }, $val[$field['field'] . '_name']);
312
+//						$val[$field['field']] = implode(',', array_column($temp, 'name'));
313
+//						$val[$field['field']] = implode(',', array_column($temp, 'name'));
312
 						break;
314
 						break;
313
 					case 'datetime':
315
 					case 'datetime':
314
 						$val[$field['field']] = strtotime($val[$field['field']]) ? $val[$field['field']] : '';
316
 						$val[$field['field']] = strtotime($val[$field['field']]) ? $val[$field['field']] : '';
315
 						break;
317
 						break;
316
-					case 'customer':
317
-					case 'business':
318
-					case 'contacts':
318
+					case 'customer':break;
319
+					case 'business':break;
320
+					case 'contacts':break;
319
 						$val[$field['field']] = $val[$field['field'] . '_info']['name'];
321
 						$val[$field['field']] = $val[$field['field'] . '_info']['name'];
320
 						break;
322
 						break;
321
-                    case 'contacts':
322
-                        $val[$field['field']] = $val[$field['field'] . '_info']['name'];
323
-                        break;
324
 					default :
323
 					default :
325
 						switch ($field['field']) {
324
 						switch ($field['field']) {
326
 							// 商机销售阶段、商机状态组
325
 							// 商机销售阶段、商机状态组
327
 							case 'status_id':
326
 							case 'status_id':
328
-							case 'type_id':
329
-								$val[$field['field']] = $val[$field['field'] . '_info'];
327
+							    if($val['is_end']!=0){
328
+                                    $val[$field['field']]= $val['is_end'];
329
+                                }
330
+							    break;
331
+							case 'type_id':break;
332
+//								$val[$field['field']] = $val[$field['field'] . '_info'];
333
+                            case 'check_status' :
334
+                                $val[$field['field']] = $val[$field['field'] . '_info'];
330
 								break;
335
 								break;
331
 						}
336
 						}
332
 				}
337
 				}

+ 24
- 2
application/admin/model/ExamineRecord.php Целия файл

56
 
56
 
57
         $result = [];
57
         $result = [];
58
 
58
 
59
-        # 获取创建者信息
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']);
63
+
64
+            $result[] = [
65
+                'check_date'         => date('Y-m-d H:i:s', $info['create_time']),
66
+                'check_time'         => $info['create_time'],
67
+                'check_user_id'      => $info['create_user_id'],
68
+                'check_user_id_info' => $userInfo,
69
+                'content'            => '',
70
+                'flow_id'            => 0,
71
+                'is_end'             => 0,
72
+                'order_id'           => 1,
73
+                'record_id'          => 0,
74
+                'status'             => 3,
75
+                'types'              => $param['types'],
76
+                'types_id'           => $param['types_id']
77
+            ];
78
+        }
79
+
80
+        # 获取创建者信息(业务审批)
60
         if (in_array($param['types'], ['crm_contract', 'crm_receivables', 'crm_invoice']) && !empty($param['is_record'])) {
81
         if (in_array($param['types'], ['crm_contract', 'crm_receivables', 'crm_invoice']) && !empty($param['is_record'])) {
61
             $model      = db($param['types']);
82
             $model      = db($param['types']);
62
             $primaryKey = null;
83
             $primaryKey = null;
75
                 'content'            => '',
96
                 'content'            => '',
76
                 'flow_id'            => 0,
97
                 'flow_id'            => 0,
77
                 'is_end'             => 0,
98
                 'is_end'             => 0,
78
-                'order_id'           => 0,
99
+                'order_id'           => 1,
79
                 'record_id'          => 0,
100
                 'record_id'          => 0,
80
                 'status'             => 3,
101
                 'status'             => 3,
81
                 'types'              => $param['types'],
102
                 'types'              => $param['types'],
88
         foreach ($list as $k=>$v) {
109
         foreach ($list as $k=>$v) {
89
             $list[$k]['check_user_id_info'] = $userModel->getUserById($v['check_user_id']);
110
             $list[$k]['check_user_id_info'] = $userModel->getUserById($v['check_user_id']);
90
             $list[$k]['check_date'] = date('Y-m-d H:i:s', $v['check_time']);
111
             $list[$k]['check_date'] = date('Y-m-d H:i:s', $v['check_time']);
112
+            $list[$k]['order_id'] = $k + 2;
91
 
113
 
92
             $result[] = $list[$k];
114
             $result[] = $list[$k];
93
         }
115
         }

+ 28
- 6
application/admin/model/ExamineStep.php Целия файл

332
 
332
 
333
             $createUserInfo = $userModel->getUserById($dataInfo['create_user_id']);
333
             $createUserInfo = $userModel->getUserById($dataInfo['create_user_id']);
334
             $createUserInfo['check_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
334
             $createUserInfo['check_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
335
-            if ($dataInfo['check_status'] == 4) {
335
+            if ($dataInfo['check_status'] == 4 && $dataInfo['create_user_id']!=trim( $dataInfo['check_status'], ',')) {
336
                 $createUserInfo['check_type'] = 2;
336
                 $createUserInfo['check_type'] = 2;
337
-                $newlist[0]['type'] = '2'; //撤销
337
+                $newlist[1]['type'] = '2'; //撤销
338
+                $newlist[1]['status'] = '5'; //创建,前端要求给创建人加一个status字段,定义为5
339
+                $createUserInfo['check_type'] = 3;
340
+                $newlist[0]['type'] = '3'; //创建
341
+                $newlist[0]['status'] = '5'; //创建,前端要求给创建人加一个status字段,定义为5
342
+                $newlist[0]['user_id_info'] = array($createUserInfo);
343
+                $newlist[0]['time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
344
+                $newlist[1]['user_id_info'] = array($createUserInfo);
345
+                $newlist[1]['time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
346
+            } elseif ($dataInfo['check_status'] == 4 && $dataInfo['create_user_id']==trim( $dataInfo['check_status'], ',')){
347
+                $createUserInfo['check_type'] = 3;
348
+                $newlist[0]['type'] = '3'; //创建
349
+                $newlist[0]['status'] = '5'; //创建,前端要求给创建人加一个status字段,定义为5
350
+                $createUserInfo['check_type'] = 2;
351
+                $newlist[1]['type'] = '2'; //撤销
352
+                $newlist[1]['status'] = '5'; //创建,前端要求给创建人加一个status字段,定义为5
353
+                $newlist[0]['user_id_info'] = array($createUserInfo);
354
+                $newlist[0]['time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
355
+                $newlist[1]['user_id_info'] = array($createUserInfo);
356
+                $newlist[1]['time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
338
             } else {
357
             } else {
339
-
340
                 $createUserInfo['check_type'] = 3;
358
                 $createUserInfo['check_type'] = 3;
341
                 $newlist[0]['type'] = '3'; //创建
359
                 $newlist[0]['type'] = '3'; //创建
342
                 $newlist[0]['status'] = '5'; //创建,前端要求给创建人加一个status字段,定义为5
360
                 $newlist[0]['status'] = '5'; //创建,前端要求给创建人加一个status字段,定义为5
361
+                $newlist[0]['user_id_info'] = array($createUserInfo);
362
+                $newlist[0]['time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
343
             }
363
             }
344
-            $newlist[0]['user_id_info'] = array($createUserInfo);
345
-            $newlist[0]['time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
346
         }
364
         }
347
         $stepList = [];
365
         $stepList = [];
348
         if ($dataInfo['check_status'] !== 4 || $action !== 'view') {
366
         if ($dataInfo['check_status'] !== 4 || $action !== 'view') {
368
                             $check_type = 1;
386
                             $check_type = 1;
369
                             $type = !empty($dataInfo['check_user_id']) ? 4 : 1;
387
                             $type = !empty($dataInfo['check_user_id']) ? 4 : 1;
370
                         }
388
                         }
389
+                        if(in_array($val, $check_user_ids) && $dataInfo['check_status'] == 2){
390
+                            $check_type = 1;
391
+                            $type = 1;
392
+                        }
371
                         $re_check_user_ids = $this->getUserByCheck($types, $types_id, $v['order_id'], 2); //撤销人员
393
                         $re_check_user_ids = $this->getUserByCheck($types, $types_id, $v['order_id'], 2); //撤销人员
372
                         if ($dataInfo['check_status'] == 4) {
394
                         if ($dataInfo['check_status'] == 4) {
373
                             if ($re_check_user_ids) {
395
                             if ($re_check_user_ids) {
484
                 $is_recheck = 1;
506
                 $is_recheck = 1;
485
             }
507
             }
486
         }
508
         }
487
-        if (in_array($check_user_id, stringToArray($dataInfo['check_user_id'])) && !in_array($dataInfo['check_status'],['2','3','5'])) {
509
+        if (in_array($check_user_id, stringToArray($dataInfo['check_user_id'])) && !in_array($dataInfo['check_status'],['2','3','4','5'])) {
488
             $is_check = 1;
510
             $is_check = 1;
489
         }
511
         }
490
 
512
 

+ 120
- 143
application/admin/model/Excel.php Целия файл

85
         $objProps->setCategory("5kcrm"); //种类
85
         $objProps->setCategory("5kcrm"); //种类
86
         $objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet
86
         $objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet
87
         $objActSheet = $objPHPExcel->getActiveSheet();
87
         $objActSheet = $objPHPExcel->getActiveSheet();
88
-        $objActSheet->setTitle('悟空软件导入模板' . date('Y-m-d', time())); //设置sheet的标题
88
+        $objActSheet->setTitle('导入模板' . date('Y-m-d', time())); //设置sheet的标题
89
         
89
         
90
         //存储Excel数据源到其他工作薄
90
         //存储Excel数据源到其他工作薄
91
         $objPHPExcel->createSheet();
91
         $objPHPExcel->createSheet();
237
                 $types_name = '员工信息';
237
                 $types_name = '员工信息';
238
                 $type_name = 'user';
238
                 $type_name = 'user';
239
                 break;
239
                 break;
240
+            case 'work_task' :
241
+                $types_name = '任务信息';
242
+                $type_name = 'task';
243
+                break;
240
             default :
244
             default :
241
                 $types_name = '悟空软件';
245
                 $types_name = '悟空软件';
242
                 $type_name = 'WuKong';
246
                 $type_name = 'WuKong';
250
             $objWriter->save($save_path);
254
             $objWriter->save($save_path);
251
         } else {
255
         } else {
252
             header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
256
             header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
253
-            header("Content-Disposition:attachment;filename=" . $type_name .'_'. date('Y-m-d') . ".xls");
257
+            header("Content-Disposition:attachment;filename=" . $type_name . '_' . date('Y-m-d') . ".xls");
254
             header("Pragma:no-cache");
258
             header("Pragma:no-cache");
255
             header("Expires:0");
259
             header("Expires:0");
256
             $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xls');
260
             $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xls');
297
         fputcsv($fp, $title_cell);
301
         fputcsv($fp, $title_cell);
298
         // $export_data = $callback(0);
302
         // $export_data = $callback(0);
299
         $round = round(1000, 9999);
303
         $round = round(1000, 9999);
300
-        cache($file_name . $round, $callback['list']);
304
+        Cache::set($file_name . $round, $callback['list'], config('export_cache_time'));
301
         $sheetContent = cache($file_name . $round);
305
         $sheetContent = cache($file_name . $round);
302
         $sheetCount = $callback['dataCount'];
306
         $sheetCount = $callback['dataCount'];
303
         $forCount = 1000; //每次取出1000个
307
         $forCount = 1000; //每次取出1000个
422
             $data = $callback($i + ($page - 1) * ($response_size / $page_size), $page_size);
426
             $data = $callback($i + ($page - 1) * ($response_size / $page_size), $page_size);
423
             $total = $data['dataCount'];
427
             $total = $data['dataCount'];
424
             foreach ($data['list'] as $val) {
428
             foreach ($data['list'] as $val) {
425
-                $val['create_time']=strtotime($val['create_time']);
426
-                $val['update_time']=strtotime($val['update_time']);
427
-                $val['last_time']=strtotime($val['last_time']);
428
-                $val['next_time']=strtotime($val['next_time']);
429
                 $rows = [];
429
                 $rows = [];
430
                 foreach ($field_list as $rule) {
430
                 foreach ($field_list as $rule) {
431
                     if ($rule['form_type'] == 'customer_address') {
431
                     if ($rule['form_type'] == 'customer_address') {
432
                         $address_arr = explode(chr(10), $val['address']);
432
                         $address_arr = explode(chr(10), $val['address']);
433
+                        
433
                         $rows[] = $address_arr[0] ?: '';
434
                         $rows[] = $address_arr[0] ?: '';
434
                         $rows[] = $address_arr[1] ?: '';
435
                         $rows[] = $address_arr[1] ?: '';
435
                         $rows[] = $address_arr[2] ?: '';
436
                         $rows[] = $address_arr[2] ?: '';
488
         $user_id = $param['owner_user_id'];
489
         $user_id = $param['owner_user_id'];
489
         
490
         
490
         // 采用伪队列  允许三人同时导入数据
491
         // 采用伪队列  允许三人同时导入数据
491
-        $queue = new Queue(self::IMPORT_QUEUE, 5);
492
+        $queue = new Queue(self::IMPORT_QUEUE, 50000000);
492
         $import_queue_index = input('import_queue_index');
493
         $import_queue_index = input('import_queue_index');
493
         
494
         
494
         // 队列任务ID
495
         // 队列任务ID
718
             if ($end_row > $max_row) {
719
             if ($end_row > $max_row) {
719
                 $end_row = $max_row;
720
                 $end_row = $max_row;
720
             }
721
             }
721
-    
722
+            
722
             // 读取数据
723
             // 读取数据
723
             $dataList = $sheet->rangeToArray("A{$start_row}:{$max_col}{$end_row}");
724
             $dataList = $sheet->rangeToArray("A{$start_row}:{$max_col}{$end_row}");
724
             // 数据重复时的处理方式 0跳过  1覆盖
725
             // 数据重复时的处理方式 0跳过  1覆盖
725
-            $config = $param['config'] ? : 0;
726
-    
726
+            $config = $param['config'] ?: 0;
727
             // 默认数据
727
             // 默认数据
728
+            
728
             $default_data = [
729
             $default_data = [
729
                 'create_user_id' => $param['create_user_id'],
730
                 'create_user_id' => $param['create_user_id'],
730
                 'owner_user_id' => $param['owner_user_id'],
731
                 'owner_user_id' => $param['owner_user_id'],
731
                 'create_time' => time(),
732
                 'create_time' => time(),
732
                 'update_time' => time(),
733
                 'update_time' => time(),
733
             ];
734
             ];
735
+            
734
             if ($temp !== count($field_list)) {
736
             if ($temp !== count($field_list)) {
735
 //                $this->error = '请使用最新导入模板';
737
 //                $this->error = '请使用最新导入模板';
736
                 @unlink($save_path);
738
                 @unlink($save_path);
737
                 $queue->dequeue();
739
                 $queue->dequeue();
738
                 foreach ($dataList as $val) {
740
                 foreach ($dataList as $val) {
739
-                    $error_data_func($val,'请使用最新导入模板');
741
+                    $error_data_func($val, '请使用最新导入模板');
740
                 }
742
                 }
741
-                // 错误数据文件保存
742
                 $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
743
                 $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
743
                 $objWriter->save($error_path);
744
                 $objWriter->save($error_path);
744
                 $error = [
745
                 $error = [
750
                     'cover' => 0,
751
                     'cover' => 0,
751
                     // 错误数据写入行号
752
                     // 错误数据写入行号
752
                     'error' => $total,
753
                     'error' => $total,
753
-                    'error_file_path' =>'temp/' . $error_data_file_name
754
+                    'error_file_path' => 'temp/' . $error_data_file_name
754
                 ];
755
                 ];
755
                 $queue->cache('last_import_cache', [
756
                 $queue->cache('last_import_cache', [
756
                     'total' => $total,
757
                     'total' => $total,
765
                     'cover' => 0,
766
                     'cover' => 0,
766
                     'error' => $total,
767
                     'error' => $total,
767
                     'user_id' => $user_id,
768
                     'user_id' => $user_id,
768
-                    'error_data_file_path' =>'temp/' . $error_data_file_name
769
+                    'error_data_file_path' => 'temp/' . $error_data_file_name
769
                 ]);
770
                 ]);
770
                 Cache::rm('item');
771
                 Cache::rm('item');
771
                 Cache::rm('excel_item');
772
                 Cache::rm('excel_item');
772
-                Cache::set('item', 1);
773
-                Cache::set('excel_item', serialize($error));
773
+                Cache::set('item', 1, config('import_cache_time'));
774
+                Cache::set('excel_item', serialize($error), config('import_cache_time'));
774
                 return true;
775
                 return true;
775
-            }else{
776
+            } else {
777
+                
776
                 // 开始导入数据
778
                 // 开始导入数据
777
                 foreach ($dataList as $val) {
779
                 foreach ($dataList as $val) {
778
                     $data = [];
780
                     $data = [];
793
                         } else {
795
                         } else {
794
                             $temp_value = trim($val[$fk]);
796
                             $temp_value = trim($val[$fk]);
795
                         }
797
                         }
796
-            
797
-            
798
+                        
799
+                        
798
                         if ($field['field'] == 'category_id' && $types == 'crm_product') {
800
                         if ($field['field'] == 'category_id' && $types == 'crm_product') {
799
-                            $data['category_id'] = $productCategoryArr[$temp_value] ? : 0;
801
+                            $data['category_id'] = $productCategoryArr[$temp_value] ?: 0;
800
                             $data['category_str'] = $dataModel->getPidStr($productCategoryArr[$temp_value], '', 1);
802
                             $data['category_str'] = $dataModel->getPidStr($productCategoryArr[$temp_value], '', 1);
801
                         }
803
                         }
802
-            
804
+                        
803
                         // 特殊字段特殊处理
805
                         // 特殊字段特殊处理
804
                         $temp_value = $this->handleData($temp_value, $field);
806
                         $temp_value = $this->handleData($temp_value, $field);
805
                         $data[$field['field']] = $temp_value;
807
                         $data[$field['field']] = $temp_value;
825
                     }
827
                     }
826
                     $old_data_id_list = [];
828
                     $old_data_id_list = [];
827
                     if ($unique_where) {
829
                     if ($unique_where) {
828
-                        if($types == 'crm_product'){
829
-                            $old_data_id_list = $model->whereOr($unique_where)->where('delete_user_id',0)->column($db_id);
830
-                        }else{
830
+                        if ($types == 'crm_product') {
831
+                            $old_data_id_list = $model->whereOr($unique_where)->where('delete_user_id', 0)->column($db_id);
832
+                        } else {
831
                             $old_data_id_list = $dataModel->whereOr($unique_where)->column($db_id);
833
                             $old_data_id_list = $dataModel->whereOr($unique_where)->column($db_id);
832
                         }
834
                         }
833
                     }
835
                     }
839
                             $data['user_id'] = $param['create_user_id'];
841
                             $data['user_id'] = $param['create_user_id'];
840
                             $data['update_time'] = time();
842
                             $data['update_time'] = time();
841
                             $data['update_time'] = time();
843
                             $data['update_time'] = time();
842
-                            if(isset($data['next_time'])){
843
-                                $data['next_time']=$data['next_time']?date('Y-m-d H:i:s', $data['next_time']):'';
844
-                            }
845
                             $dataModel->startTrans();
844
                             $dataModel->startTrans();
846
                             try {
845
                             try {
847
                                 $up_success_count = 0;
846
                                 $up_success_count = 0;
848
                                 foreach ($old_data_id_list as $id) {
847
                                 foreach ($old_data_id_list as $id) {
849
-                                    if($types=='crm_customer'){
848
+                                    if ($types == 'crm_customer') {
850
                                         $owner = db('crm_customer')->where(['name' => $data['name']])->find();
849
                                         $owner = db('crm_customer')->where(['name' => $data['name']])->find();
851
                                         if (!empty($owner) && $owner['owner_user_id'] == 0) {
850
                                         if (!empty($owner) && $owner['owner_user_id'] == 0) {
852
-                                            $temp_error = $owner['name'] .' '. '公海数据,无覆盖权限';
851
+                                            $temp_error = $owner['name'] . ' ' . '公海数据,无覆盖权限';
853
                                             $error_data_func($val, $temp_error);
852
                                             $error_data_func($val, $temp_error);
854
                                             break;
853
                                             break;
855
                                         }
854
                                         }
889
                         }
888
                         }
890
                     } else {
889
                     } else {
891
                         $data = array_merge($data, $default_data);
890
                         $data = array_merge($data, $default_data);
892
-                        if(isset($data['next_time'])){
893
-                            $data['next_time']=$data['next_time']?date('Y-m-d H:i:s', $data['next_time']):'';
894
-                        }
895
                         if (!$resData = $dataModel->createData($data)) {
891
                         if (!$resData = $dataModel->createData($data)) {
896
                             $error_data_func($val, $dataModel->getError());
892
                             $error_data_func($val, $dataModel->getError());
897
                         }
893
                         }
898
                     }
894
                     }
899
                 }
895
                 }
900
-    
896
+                
901
                 // 完成数(已导入数)
897
                 // 完成数(已导入数)
902
                 $done = ($page - 1) * $page_size + count($dataList);
898
                 $done = ($page - 1) * $page_size + count($dataList);
903
                 if ($page == $max_page) {
899
                 if ($page == $max_page) {
904
                     $done = $total;
900
                     $done = $total;
905
                 }
901
                 }
906
-    
902
+                
907
                 // 错误数
903
                 // 错误数
908
                 $error = $error_row - 3;
904
                 $error = $error_row - 3;
909
-    
905
+                
910
                 // 错误数据文件保存
906
                 // 错误数据文件保存
911
                 $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
907
                 $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
912
                 $objWriter->save($error_path);
908
                 $objWriter->save($error_path);
913
-    
909
+                
914
                 $this->error = [
910
                 $this->error = [
915
                     // 数据导入文件临时路径
911
                     // 数据导入文件临时路径
916
                     'temp_file' => $save_name,
912
                     'temp_file' => $save_name,
929
                     // 导入任务ID
925
                     // 导入任务ID
930
                     'import_queue_index' => $import_queue_index
926
                     'import_queue_index' => $import_queue_index
931
                 ];
927
                 ];
932
-    
928
+                
933
                 $queue->cache('last_import_cache', [
929
                 $queue->cache('last_import_cache', [
934
                     'total' => $total,
930
                     'total' => $total,
935
                     'done' => $done,
931
                     'done' => $done,
944
                     $this->error['error_file_path'] = 'temp/' . $error_data_file_name;
940
                     $this->error['error_file_path'] = 'temp/' . $error_data_file_name;
945
                     // 删除导入文件
941
                     // 删除导入文件
946
                     @unlink($save_path);
942
                     @unlink($save_path);
947
-        
943
+                    
948
                     // 没有错误数据时,删除错误文件
944
                     // 没有错误数据时,删除错误文件
949
                     if ($error == 0) {
945
                     if ($error == 0) {
950
                         @unlink($error_path);
946
                         @unlink($error_path);
951
                     }
947
                     }
952
-        
948
+                    
953
                     (new ImportRecord())->createData([
949
                     (new ImportRecord())->createData([
954
                         'type' => $types,
950
                         'type' => $types,
955
                         'total' => $total,
951
                         'total' => $total,
959
                         'user_id' => $user_id,
955
                         'user_id' => $user_id,
960
                         'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
956
                         'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
961
                     ]);
957
                     ]);
962
-                    Cache::set('item', 1);
963
-                    Cache::set('excel_item', serialize($this->error));
964
-                }else{
965
-                    $excelData['cover']=$cover;
966
-                    $excelData['page']=$page+1;
967
-                    $excelData['types']=$types;
968
-                    $excelData['temp_file']=$save_name;
969
-                    $excelData['error_file']=$error_data_file_name;
970
-                    $excelData['create_user_id']=$param['create_user_id'];
971
-                    $excelData['import_queue_index']=$import_queue_index;
972
-                    $excelData['config']=$config;
973
-                    $excelData['owner_user_id']=$user_id;
974
-                    $excelData['base']='batchImportData';
975
-                    Cache::set('item', 0);
976
-                    Cache::set('excel', $excelData);
958
+                    Cache::set('item', 1, config('import_cache_time'));
959
+                    Cache::set('excel_item', serialize($this->error), config('import_cache_time'));
960
+                } else {
961
+                    $queue->dequeue();
962
+                    $excelData['cover'] = $cover;
963
+                    $excelData['page'] = $page + 1;
964
+                    $excelData['types'] = $types;
965
+                    $excelData['temp_file'] = $save_name;
966
+                    $excelData['error_file'] = $error_data_file_name;
967
+                    $excelData['create_user_id'] = $param['create_user_id'];
968
+                    $excelData['import_queue_index'] = $import_queue_index;
969
+                    $excelData['config'] = $config;
970
+                    $excelData['owner_user_id'] = $user_id;
971
+                    $excelData['base'] = 'batchImportData';
972
+                    Cache::set('item', 0, config('import_cache_time'));
973
+                    Cache::set('excel', $excelData, config('import_cache_time'));
977
                 }
974
                 }
978
                 return true;
975
                 return true;
979
             }
976
             }
980
-          
981
         } else {
977
         } else {
982
             $this->error = '请选择导入文件';
978
             $this->error = '请选择导入文件';
983
             $queue->dequeue();
979
             $queue->dequeue();
1436
                 $queue->dequeue();
1432
                 $queue->dequeue();
1437
                 $this->error['error_file_path'] = 'temp/' . $error_data_file_name;
1433
                 $this->error['error_file_path'] = 'temp/' . $error_data_file_name;
1438
                 
1434
                 
1439
-                Cache::set('item', 1);
1440
-                Cache::set('excel_item', serialize($this->error));
1435
+                Cache::set('item', 1, config('import_cache_time'));
1436
+                Cache::set('excel_item', serialize($this->error), config('import_cache_time'));
1441
             } else {
1437
             } else {
1442
-                $excelData['page']=$page+1;
1443
-                $excelData['types']=$types;
1444
-                $excelData['temp_file']=$save_name;
1445
-                $excelData['error_file']=$error_data_file_name;
1446
-                $excelData['create_user_id']=$param['create_user_id'];
1447
-                $excelData['import_queue_index']=$import_queue_index;
1448
-                $excelData['config']=$config;
1449
-                $excelData['owner_user_id']=$user_id;
1450
-                $excelData['base']='importExcel';
1451
-                Cache::set('item', 0);
1452
-                Cache::set('excel', $excelData);
1438
+                $excelData['page'] = $page + 1;
1439
+                $excelData['types'] = $types;
1440
+                $excelData['temp_file'] = $save_name;
1441
+                $excelData['error_file'] = $error_data_file_name;
1442
+                $excelData['create_user_id'] = $param['create_user_id'];
1443
+                $excelData['import_queue_index'] = $import_queue_index;
1444
+                $excelData['config'] = $config;
1445
+                $excelData['owner_user_id'] = $user_id;
1446
+                $excelData['base'] = 'importExcel';
1447
+                Cache::set('item', 0, config('import_cache_time'));
1448
+                Cache::set('excel', $excelData, config('import_cache_time'));
1453
             }
1449
             }
1454
             return true;
1450
             return true;
1455
         } else {
1451
         } else {
1705
         }
1701
         }
1706
         // 将标题名称通过fputcsv写到文件句柄
1702
         // 将标题名称通过fputcsv写到文件句柄
1707
         fputcsv($fp, $title_cell);
1703
         fputcsv($fp, $title_cell);
1708
-//        $export_data = $callback(0);
1709
-        foreach ($callback as $item) {
1704
+        $export_data = $callback(0);
1705
+        foreach ($export_data as $item) {
1710
             $rows = [];
1706
             $rows = [];
1711
             foreach ($field_list as $rule) {
1707
             foreach ($field_list as $rule) {
1712
                 $rows[] = $item[$rule['field']];
1708
                 $rows[] = $item[$rule['field']];
1731
      *
1727
      *
1732
      * @author Ymob
1728
      * @author Ymob
1733
      */
1729
      */
1734
-    public function batchTaskImportData($file, $param, $controller = null)
1730
+    public function batchTaskImportData($file,$field_list, $param, $controller = null)
1735
     {
1731
     {
1736
         // 导入模块
1732
         // 导入模块
1737
         $types = $param['types'];
1733
         $types = $param['types'];
1742
         }
1738
         }
1743
         $user_id = $param['owner_user_id'];
1739
         $user_id = $param['owner_user_id'];
1744
         // 采用伪队列  允许三人同时导入数据
1740
         // 采用伪队列  允许三人同时导入数据
1745
-        $queue = new Queue(self::IMPORT_QUEUE, 3);
1741
+        $queue = new Queue(self::IMPORT_QUEUE, 30000);
1746
         $import_queue_index = input('import_queue_index');
1742
         $import_queue_index = input('import_queue_index');
1747
         
1743
         
1748
         // 队列任务ID
1744
         // 队列任务ID
1865
                 $error_row++;
1861
                 $error_row++;
1866
             };
1862
             };
1867
             
1863
             
1868
-            $field_list = [
1869
-                '0' => ['name' => '任务名称', 'field' => 'name'],
1870
-                '1' => ['name' => '任务描述', 'field' => 'description'],
1871
-                '2' => ['name' => '开始时间', 'field' => 'start_time'],
1872
-                '3' => ['name' => '结束时间', 'field' => 'stop_time'],
1873
-                '4' => ['name' => '负责人', 'field' => 'create_user_id'],
1874
-                '5' => ['name' => '参与人', 'field' => 'owner_user_id'],
1875
-                '6' => ['name' => '所属任务列表', 'field' => 'class_id'],
1876
-            ];
1877
-            $field_key_name_list = array_column($field_list, 'name');
1878
-            
1879
             // 加载导入数据文件
1864
             // 加载导入数据文件
1880
             $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
1865
             $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
1881
             $objRender->setReadDataOnly(true);
1866
             $objRender->setReadDataOnly(true);
1889
             $max_col_num += 3 * array_count_values(array_column($field_list, 'form_type'))['map_address'];
1874
             $max_col_num += 3 * array_count_values(array_column($field_list, 'form_type'))['map_address'];
1890
             $max_col = \PHPExcel_Cell::stringFromColumnIndex($max_col_num);
1875
             $max_col = \PHPExcel_Cell::stringFromColumnIndex($max_col_num);
1891
             
1876
             
1892
-            // 检测导入文件是否使用最新模板
1893
-            $header = $sheet->rangeToArray("A2:{$max_col}2")[0];
1894
-            $temp = 0;
1895
-            for ($i = 0; $i < count($field_list); $i++) {
1896
-                if (
1897
-                    $header[$i] == $field_list[$i]['name']
1898
-                    || $header[$i] == $field_list[$i]['name'] . '(*)'
1899
-                ) {
1900
-                    $temp++;
1901
-                    // 字段为地址时,占四列
1902
-                } elseif ($field_list[$i]['form_type'] == 'map_address') {
1903
-                    if (
1904
-                        $header[$i] == $this->map_address[0]
1905
-                        && $header[$i + 1] == $this->map_address[1]
1906
-                        && $header[$i + 2] == $this->map_address[2]
1907
-                        && $header[$i + 3] == $this->map_address[3]
1908
-                    ) {
1909
-                        $temp++;
1910
-                    }
1911
-                }
1912
-            }
1913
-            if ($temp !== count($field_list)) {
1914
-                $this->error = '请使用最新导入模板';
1915
-                @unlink($save_path);
1916
-                $queue->dequeue();
1917
-                return false;
1918
-            }
1919
-            
1920
             // 每次导入条数
1877
             // 每次导入条数
1921
             $page_size = 100;
1878
             $page_size = 100;
1922
             
1879
             
1951
                 'create_user_id' => $param['create_user_id'],
1908
                 'create_user_id' => $param['create_user_id'],
1952
                 'create_time' => time(),
1909
                 'create_time' => time(),
1953
                 'update_time' => time(),
1910
                 'update_time' => time(),
1911
+                'work_id' => $param['work_id'],
1954
             ];
1912
             ];
1955
             // 开始导入数据
1913
             // 开始导入数据
1956
             foreach ($dataList as $val) {
1914
             foreach ($dataList as $val) {
1915
+                foreach ($field_list as $field) {
1916
+                    $temp_value = trim($val[$fk]);
1917
+                    // 特殊字段特殊处理
1918
+                    $temp_value = $this->handleData($temp_value, $field);
1919
+                    $data[$field['field']] = $temp_value;
1920
+                    if ($temp_value == '') {
1921
+                        if ($field['is_null']) {
1922
+                            $not_null_field[] = $field['name'];
1923
+                        }
1924
+                        $empty_count++;
1925
+                    }
1926
+                    $fk++;
1927
+                }
1928
+                if (!empty($not_null_field)) {
1929
+                    $error_data_func($val, implode(', ', $not_null_field) . '不能为空');
1930
+                    continue;
1931
+                }
1932
+                if ($empty_count == count($field_list)) {
1933
+                    $error_data_func($val, '空行');
1934
+                    continue;
1935
+                }
1957
                 $data = [];
1936
                 $data = [];
1958
                 $fk = 0;
1937
                 $fk = 0;
1959
                 $classData = db('work_task_class')->where(['name' => $val[6], 'work_id' => $param['work_id']])->order('class_id', 'asc')->select();
1938
                 $classData = db('work_task_class')->where(['name' => $val[6], 'work_id' => $param['work_id']])->order('class_id', 'asc')->select();
1972
                     $data['class_id'] = db('work_task_class')->insertGetId($item);
1951
                     $data['class_id'] = db('work_task_class')->insertGetId($item);
1973
                 }
1952
                 }
1974
                 $dataModel = new \app\work\model\Task();
1953
                 $dataModel = new \app\work\model\Task();
1975
-                foreach ($field_list as $field) {
1976
-                    $temp_value = trim($val[$fk]);
1977
-                    // 特殊字段特殊处理
1978
-                    $temp_value = $this->handleData($temp_value, $field);
1979
-                    $data[$field['field']] = $temp_value;
1980
-                    
1981
-                    $fk++;
1982
-                }
1983
-                // 数据重复时
1954
+                
1984
                 $data = array_merge($data, $default_data);
1955
                 $data = array_merge($data, $default_data);
1985
                 if (!$resData = $dataModel->createTask($data)) {
1956
                 if (!$resData = $dataModel->createTask($data)) {
1986
                     $error_data_func($val, $dataModel->getError());
1957
                     $error_data_func($val, $dataModel->getError());
2047
                     'user_id' => $user_id,
2018
                     'user_id' => $user_id,
2048
                     'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
2019
                     'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
2049
                 ]);
2020
                 ]);
2050
-                Cache::set('item', 1);
2051
-                Cache::set('excel_item', serialize($this->error));
2021
+                Cache::set('item', 1, config('import_cache_time'));
2022
+                Cache::set('excel_item', serialize($this->error), config('import_cache_time'));
2052
             } else {
2023
             } else {
2053
-                $excelData['cover']=$cover;
2054
-                $excelData['page']=$page+1;
2055
-                $excelData['types']=$types;
2056
-                $excelData['temp_file']=$save_name;
2057
-                $excelData['error_file']=$error_data_file_name;
2058
-                $excelData['create_user_id']=$param['create_user_id'];
2059
-                $excelData['import_queue_index']=$import_queue_index;
2060
-                $excelData['owner_user_id']=$user_id;
2061
-                $excelData['base']='batchTaskImportData';
2062
-                Cache::set('item', 0);
2063
-                Cache::set('excel', $excelData);
2024
+                $excelData['cover'] = $cover;
2025
+                $excelData['page'] = $page + 1;
2026
+                $excelData['types'] = $types;
2027
+                $excelData['temp_file'] = $save_name;
2028
+                $excelData['error_file'] = $error_data_file_name;
2029
+                $excelData['create_user_id'] = $param['create_user_id'];
2030
+                $excelData['import_queue_index'] = $import_queue_index;
2031
+                $excelData['owner_user_id'] = $user_id;
2032
+                $excelData['total'] = $total;
2033
+                $excelData['done'] = $done;
2034
+                $excelData['error'] = $error;
2035
+                $excelData['base'] = 'batchTaskImportData';
2036
+                Cache::set('item', 0, config('import_cache_time'));
2037
+                Cache::set('excel', $excelData, config('import_cache_time'));
2064
             }
2038
             }
2065
             return true;
2039
             return true;
2066
         } else {
2040
         } else {
2325
         $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel5为xls格式,excel2007为xlsx格式
2299
         $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel5为xls格式,excel2007为xlsx格式
2326
         $objWriter->save('php://output');
2300
         $objWriter->save('php://output');
2327
     }
2301
     }
2328
-    
2329
     /**
2302
     /**
2330
      * 运行中
2303
      * 运行中
2331
      * @param $param
2304
      * @param $param
2333
      */
2306
      */
2334
     public function importNum()
2307
     public function importNum()
2335
     {
2308
     {
2336
-        $param = Cache::get('item');
2337
-        $excelData=Cache::get('excel');
2338
-        $base=$excelData['base'];
2309
+        $param = Cache::pull('item');
2310
+        $excelData = Cache::pull('excel');
2311
+        $base = $excelData['base'];
2339
         if ($param == 0) {
2312
         if ($param == 0) {
2340
-            $this->$base('',$excelData);
2313
+            if($base=='batchTaskImportData'){
2314
+                $this->batchTaskImportData('', $excelData);
2315
+            }else{
2316
+                $this->batchImportData('', $excelData);
2317
+            }
2341
             $data = 0;
2318
             $data = 0;
2342
         } elseif ($param == 1) {
2319
         } elseif ($param == 1) {
2343
             $data = '';
2320
             $data = '';
2353
      */
2330
      */
2354
     public function importInfo()
2331
     public function importInfo()
2355
     {
2332
     {
2356
-        $param = Cache::get('excel_item');
2333
+        $param = Cache::pull('excel_item');
2357
         $param = unserialize($param);
2334
         $param = unserialize($param);
2358
         return $param;
2335
         return $param;
2359
     }
2336
     }
2367
     {
2344
     {
2368
         $list = db('admin_import_record')->alias('i')
2345
         $list = db('admin_import_record')->alias('i')
2369
             ->join('admin_user user', 'i.user_id=user.id')
2346
             ->join('admin_user user', 'i.user_id=user.id')
2370
-            ->where(['i.type'=>$param['type'],'i.user_id'=>$param['user_id']])->page($param['page'], $param['limit'])
2347
+            ->where(['i.type' => $param['type'], 'i.user_id' => $param['user_id']])->page($param['page'], $param['limit'])
2371
             ->field('i.*,user.realname as user_name')->order('create_time desc')->select();
2348
             ->field('i.*,user.realname as user_name')->order('create_time desc')->select();
2372
         $dataCount = db('admin_import_record')->where('type', $param['type'])->count();
2349
         $dataCount = db('admin_import_record')->where('type', $param['type'])->count();
2373
         $week = strtotime(date("Y-m-d H:i:s", strtotime("+7 day")));
2350
         $week = strtotime(date("Y-m-d H:i:s", strtotime("+7 day")));
2374
         $time = time();
2351
         $time = time();
2375
         foreach ($list as $k => $v) {
2352
         foreach ($list as $k => $v) {
2376
-            $week = strtotime("+7 day",$v['create_time']);
2353
+            $week = strtotime("+7 day", $v['create_time']);
2377
             if ($time > (int)$week) {
2354
             if ($time > (int)$week) {
2378
                 $list[$k]['valid'] = 0;
2355
                 $list[$k]['valid'] = 0;
2379
             } else {
2356
             } else {
2380
                 $list[$k]['valid'] = 1;
2357
                 $list[$k]['valid'] = 1;
2381
             }
2358
             }
2382
-            if($v['error_data_file_path']==''){
2359
+            if ($v['error_data_file_path'] == '') {
2383
                 $list[$k]['valid'] = -1;
2360
                 $list[$k]['valid'] = -1;
2384
             }
2361
             }
2385
             $list[$k]['create_time'] = date('Y-m-d', $v['create_time']);
2362
             $list[$k]['create_time'] = date('Y-m-d', $v['create_time']);

+ 227
- 161
application/admin/model/Field.php Целия файл

681
                     'value' => []
681
                     'value' => []
682
                 ];
682
                 ];
683
             }
683
             }
684
+            # 产品基本信息增加负责人信息
685
+            if ($param['action'] == 'read' && $param['types'] == 'crm_product') {
686
+                $new_field_list[] = db('admin_field')->where(['types_id' => 0, 'field' => 'owner_user_id'])->find();
687
+            }
684
             if ($new_field_list) $field_list = array_merge(collection($field_list)->toArray(), $new_field_list);
688
             if ($new_field_list) $field_list = array_merge(collection($field_list)->toArray(), $new_field_list);
685
             foreach ($field_list as $k => $v) {
689
             foreach ($field_list as $k => $v) {
686
                 # 处理字段授权
690
                 # 处理字段授权
698
                     $field_list[$k]['writeStatus'] = $status['write'];
702
                     $field_list[$k]['writeStatus'] = $status['write'];
699
                 }
703
                 }
700
 
704
 
705
+                # (联系人,商机,合同,回款,回访)关联其他模块的字段在详情页面不允许修改;创建人、负责人不允许修改
706
+                if ($param['action'] == 'read' && in_array($v['field'], ['customer_id', 'business_id', 'contacts_id', 'contract_id', 'create_user_id', 'owner_user_id'])) {
707
+                    $field_list[$k]['writeStatus'] = 0;
708
+                }
709
+
701
                 //处理setting内容
710
                 //处理setting内容
702
                 $setting = [];
711
                 $setting = [];
703
                 $default_value = $v['default_value'];
712
                 $default_value = $v['default_value'];
915
                 ]
924
                 ]
916
             ];
925
             ];
917
         }
926
         }
927
+        if ($param['types'] == 'crm_customer') {
928
+            $field_arr[] = [
929
+                'field' => 'detail_address',
930
+                'name' => '详细地址',
931
+                'form_type' => 'text',
932
+                'setting' => []
933
+            ];
934
+        }
918
         if ($field_arr) $field_list = array_merge($field_list, $field_arr);
935
         if ($field_arr) $field_list = array_merge($field_list, $field_arr);
919
         foreach ($field_list as $k => $v) {
936
         foreach ($field_list as $k => $v) {
920
             //处理setting内容
937
             //处理setting内容
947
                 $businessStatusModel = new \app\crm\model\BusinessStatus();
964
                 $businessStatusModel = new \app\crm\model\BusinessStatus();
948
                 $userInfo = $userModel->getUserById($user_id);
965
                 $userInfo = $userModel->getUserById($user_id);
949
                 $setting = db('crm_business_type')
966
                 $setting = db('crm_business_type')
950
-                    ->where(['structure_id' => $userInfo['structure_id'], 'status' => 1])
967
+                    ->where(['structure_id' => ['like', ',%' . $userInfo['structure_id'] . '%,'], 'status' => 1])
951
                     ->whereOr('structure_id', '')
968
                     ->whereOr('structure_id', '')
952
                     ->select();
969
                     ->select();
953
                 foreach ($setting as $key => $val) {
970
                 foreach ($setting as $key => $val) {
1387
         $userModel = new \app\admin\model\User();
1404
         $userModel = new \app\admin\model\User();
1388
         $structureModel = new \app\admin\model\Structure();
1405
         $structureModel = new \app\admin\model\Structure();
1389
         switch ($form_type) {
1406
         switch ($form_type) {
1390
-            case 'datetime' :
1391
-                $val = $val > 0 ? date('Y-m-d H:i:s', $val) : '';
1392
-                break;
1407
+//            case 'datetime' :
1408
+//                $val = $val > 0 ? date('Y-m-d H:i:s', $val) : '';
1409
+//                break;
1393
             case 'user' :
1410
             case 'user' :
1394
-                $val = count($userModel->getUserNameByArr($val)) > 1 ? ArrayToString($userModel->getUserNameByArr($val)) : implode(',', $userModel->getUserNameByArr($val));
1411
+                $val = count($userModel->getUserNameByArr($val)) > 1 ? ArrayToString($userModel->getUserNameByArr($val)) : implode(',', $userModel->getUserNameByArr(stringToArray($val)));
1395
                 break;
1412
                 break;
1396
             case 'userStr' :
1413
             case 'userStr' :
1397
                 $val = explode(',', $val);
1414
                 $val = explode(',', $val);
1398
                 $val = count($userModel->getUserNameByArr($val)) > 1 ? ArrayToString($userModel->getUserNameByArr($val)) : implode(',', $userModel->getUserNameByArr($val));
1415
                 $val = count($userModel->getUserNameByArr($val)) > 1 ? ArrayToString($userModel->getUserNameByArr($val)) : implode(',', $userModel->getUserNameByArr($val));
1399
                 break;
1416
                 break;
1400
             case 'structure' :
1417
             case 'structure' :
1401
-                $val = ArrayToString($structureModel->getStructureNameByArr($val));
1418
+                $val = implode(',', $structureModel->getStructureNameByArr(stringToArray($val)));
1402
                 break;
1419
                 break;
1403
             case 'customer' :
1420
             case 'customer' :
1404
                 $val = db('crm_customer')->where(['customer_id' => $val])->value('name');
1421
                 $val = db('crm_customer')->where(['customer_id' => $val])->value('name');
1405
                 break;
1422
                 break;
1423
+            case 'contract' :
1424
+                $val = db('crm_contract')->where(['customer_id' => $val])->value('num');
1425
+                break;
1406
             case 'business' :
1426
             case 'business' :
1407
                 $val = db('crm_business')->where(['business_id' => $val])->value('name');
1427
                 $val = db('crm_business')->where(['business_id' => $val])->value('name');
1408
                 break;
1428
                 break;
1530
 
1550
 
1531
     public function resetField($types, $data)
1551
     public function resetField($types, $data)
1532
     {
1552
     {
1533
-        # 线索
1534
-        if ($types == 'crm_leads') {
1535
-            foreach ($data as $key => $value) {
1536
-                switch ($value['field']) {
1537
-                    case 'create_user_id' :
1538
-                        $data[$key]['fieldName'] = 'create_user_name';
1539
-                        break;
1540
-                    case 'owner_user_id' :
1541
-                        $data[$key]['fieldName'] = 'owner_user_name';
1542
-                        break;
1543
-                    default :
1544
-                        $data[$key]['fieldName'] = $value['field'];
1545
-                }
1553
+        foreach ($data AS $key => $value) {
1554
+            switch ($value['field']) {
1555
+                case 'create_user_id' :
1556
+                    $data[$key]['fieldName'] = 'create_user_name';
1557
+                    break;
1558
+                case 'owner_user_id' :
1559
+                    $data[$key]['fieldName'] = 'owner_user_name';
1560
+                    break;
1561
+                case 'customer_id' :
1562
+                    $data[$key]['fieldName'] = 'customer_name';
1563
+                    break;
1564
+                case 'type_id' :
1565
+                    $data[$key]['fieldName'] = 'type_id_info';
1566
+                    break;
1567
+                case 'status_id' :
1568
+                    $data[$key]['fieldName'] = 'status_id_info';
1569
+                    break;
1570
+                case 'business_id' :
1571
+                    $data[$key]['fieldName'] = 'business_name';
1572
+                    break;
1573
+                case 'contacts_id' :
1574
+                    $data[$key]['fieldName'] = 'contacts_name';
1575
+                    break;
1576
+                case 'order_user_id' :
1577
+                    $data[$key]['fieldName'] = 'order_user_name';
1578
+                    break;
1579
+                case 'contract_id' :
1580
+                    $data[$key]['fieldName'] = 'contract_num';
1581
+                    break;
1582
+                case 'plan_id' :
1583
+                    $data[$key]['fieldName'] = 'plan_id_info';
1584
+                    break;
1585
+                case 'category_id' :
1586
+                    $data[$key]['fieldName'] = 'category_name';
1587
+                    break;
1588
+                default :
1589
+                    $data[$key]['fieldName'] = $value['field'];
1546
             }
1590
             }
1547
-        }
1548
 
1591
 
1549
-        # 客户
1550
-        if ($types == 'crm_customer') {
1551
-            foreach ($data as $key => $value) {
1552
-                switch ($value['field']) {
1553
-                    case 'create_user_id' :
1554
-                        $data[$key]['fieldName'] = 'create_user_name';
1555
-                        break;
1556
-                    case 'owner_user_id' :
1557
-                        $data[$key]['fieldName'] = 'owner_user_name';
1558
-                        break;
1559
-                    default :
1560
-                        $data[$key]['fieldName'] = $value['field'];
1561
-                }
1592
+            if (in_array($value['form_type'], ['user', 'structure']) && !in_array($value['field'], ['create_user_id', 'owner_user_id'])) {
1593
+                $data[$key]['fieldName'] = $value['field'] . '_name';
1562
             }
1594
             }
1563
         }
1595
         }
1564
 
1596
 
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
+
1565
         # 联系人
1629
         # 联系人
1566
-        if ($types == 'crm_contacts') {
1567
-            foreach ($data as $key => $value) {
1568
-                switch ($value['field']) {
1569
-                    case 'customer_id' :
1570
-                        $data[$key]['fieldName'] = 'customer_name';
1571
-                        break;
1572
-                    case 'create_user_id' :
1573
-                        $data[$key]['fieldName'] = 'create_user_name';
1574
-                        break;
1575
-                    case 'owner_user_id' :
1576
-                        $data[$key]['fieldName'] = 'owner_user_name';
1577
-                        break;
1578
-                    default :
1579
-                        $data[$key]['fieldName'] = $value['field'];
1580
-                }
1581
-            }
1582
-        }
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
+//        }
1583
 
1647
 
1584
         # 商机
1648
         # 商机
1585
-        if ($types == 'crm_business') {
1586
-            foreach ($data as $key => $value) {
1587
-                switch ($value['field']) {
1588
-                    case 'customer_id' :
1589
-                        $data[$key]['fieldName'] = 'customer_name';
1590
-                        break;
1591
-                    case 'type_id' :
1592
-                        $data[$key]['fieldName'] = 'type_id_info';
1593
-                        break;
1594
-                    case 'status_id' :
1595
-                        $data[$key]['fieldName'] = 'status_id_info';
1596
-                        break;
1597
-                    case 'create_user_id' :
1598
-                        $data[$key]['fieldName'] = 'create_user_name';
1599
-                        break;
1600
-                    case 'owner_user_id' :
1601
-                        $data[$key]['fieldName'] = 'owner_user_name';
1602
-                        break;
1603
-                    default :
1604
-                        $data[$key]['fieldName'] = $value['field'];
1605
-                }
1606
-            }
1607
-        }
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
+//        }
1608
 
1672
 
1609
         # 合同
1673
         # 合同
1610
-        if ($types == 'crm_contract') {
1611
-            foreach ($data as $key => $value) {
1612
-                switch ($value['field']) {
1613
-                    case 'customer_id' :
1614
-                        $data[$key]['fieldName'] = 'customer_name';
1615
-                        break;
1616
-                    case 'business_id' :
1617
-                        $data[$key]['fieldName'] = 'business_name';
1618
-                        break;
1619
-                    case 'contacts_id' :
1620
-                        $data[$key]['fieldName'] = 'contacts_name';
1621
-                        break;
1622
-                    case 'order_user_id' :
1623
-                        $data[$key]['fieldName'] = 'order_user_name';
1624
-                        break;
1625
-                    case 'create_user_id' :
1626
-                        $data[$key]['fieldName'] = 'create_user_name';
1627
-                        break;
1628
-                    case 'owner_user_id' :
1629
-                        $data[$key]['fieldName'] = 'owner_user_name';
1630
-                        break;
1631
-                }
1632
-            }
1633
-        }
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
+//        }
1634
 
1700
 
1635
         # 回款
1701
         # 回款
1636
-        if ($types == 'crm_receivables') {
1637
-            foreach ($data as $key => $value) {
1638
-                switch ($value['field']) {
1639
-                    case 'customer_id' :
1640
-                        $data[$key]['fieldName'] = 'customer_name';
1641
-                        break;
1642
-                    case 'contract_id' :
1643
-                        $data[$key]['fieldName'] = 'contract_num';
1644
-                        break;
1645
-                    case 'create_user_id' :
1646
-                        $data[$key]['fieldName'] = 'create_user_name';
1647
-                        break;
1648
-                    case 'owner_user_id' :
1649
-                        $data[$key]['fieldName'] = 'owner_user_name';
1650
-                        break;
1651
-                    case 'plan_id' :
1652
-                        $data[$key]['fieldName'] = 'plan_id_info';
1653
-                        break;
1654
-                    default :
1655
-                        $data[$key]['fieldName'] = $value['field'];
1656
-                }
1657
-            }
1658
-        }
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
+//        }
1659
 
1725
 
1660
         # 回访
1726
         # 回访
1661
-        if ($types == 'crm_visit') {
1662
-            foreach ($data as $key => $value) {
1663
-                switch ($value['field']) {
1664
-                    case 'customer_id' :
1665
-                        $data[$key]['fieldName'] = 'customer_name';
1666
-                        break;
1667
-                    case 'owner_user_id' :
1668
-                        $data[$key]['fieldName'] = 'owner_user_name';
1669
-                        $data[$key]['name'] = '回访人';
1670
-                        break;
1671
-                    case 'contacts_id' :
1672
-                        $data[$key]['fieldName'] = 'contacts_name';
1673
-                        break;
1674
-                    case 'contract_id' :
1675
-                        $data[$key]['fieldName'] = 'contract_number';
1676
-                        break;
1677
-                    case 'create_user_id' :
1678
-                        $data[$key]['fieldName'] = 'create_user_name';
1679
-                        break;
1680
-                    default :
1681
-                        $data[$key]['fieldName'] = $value['field'];
1682
-                }
1683
-            }
1684
-        }
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
+//        }
1685
 
1751
 
1686
         # 产品
1752
         # 产品
1687
-        if ($types == 'crm_product') {
1688
-            foreach ($data as $key => $value) {
1689
-                switch ($value['field']) {
1690
-                    case 'category_id' :
1691
-                        $data[$key]['fieldName'] = 'category_name';
1692
-                        break;
1693
-                    case 'create_user_id' :
1694
-                        $data[$key]['fieldName'] = 'create_user_name';
1695
-                        break;
1696
-                    case 'owner_user_id' :
1697
-                        $data[$key]['fieldName'] = 'owner_user_name';
1698
-                        break;
1699
-                    default :
1700
-                        $data[$key]['fieldName'] = $value['field'];
1701
-                }
1702
-            }
1703
-        }
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
+//        }
1704
 
1770
 
1705
         return $data;
1771
         return $data;
1706
     }
1772
     }

+ 13
- 0
application/admin/model/File.php Целия файл

272
 		if (!is_array($request['module_id'])) {
272
 		if (!is_array($request['module_id'])) {
273
 			$module_ids = array($request['module_id']);
273
 			$module_ids = array($request['module_id']);
274
 		}
274
 		}
275
+		$moduleName = $request['module'];
275
 
276
 
276
 		switch ($request['module']) {
277
 		switch ($request['module']) {
277
 			case 'crm_leads' : $r = db('crm_leads_file'); $module = db('crm_leads'); break;
278
 			case 'crm_leads' : $r = db('crm_leads_file'); $module = db('crm_leads'); break;
302
 		unset($request['module_id']);
303
 		unset($request['module_id']);
303
 		unset($request['by']);
304
 		unset($request['by']);
304
 
305
 
306
+        # 查询活动附件,用于判断是否可以删除附件(活动添加的附件只能在活动中删除)
307
+        $activityFileIds = [];
308
+        $activityType = ['crm_leads' => 1, 'crm_customer' => 2, 'crm_contacts' => 3, 'crm_business' => 5, 'crm_contract' => 6];
309
+        if (!empty($activityType[$moduleName])) {
310
+            $activityFileIds = db('crm_activity')->alias('activity')
311
+                ->join('__CRM_ACTIVITY_FILE__ file', 'file.activity_id = activity.activity_id', 'LEFT')
312
+                ->where(['type' => 1, 'activity_type' => $activityType[$moduleName], 'activity_type_id' => ['in', $module_ids]])
313
+                ->column('file.file_id');
314
+            $activityFileIds = array_filter($activityFileIds);
315
+        }
316
+
305
 		$userModel = new \app\admin\model\User();
317
 		$userModel = new \app\admin\model\User();
306
 		$request = $this->fmtRequest( $request );
318
 		$request = $this->fmtRequest( $request );
307
         $map = $request['map'];
319
         $map = $request['map'];
321
         	$list[$k]['ext'] = getExtension($v['save_name']);
333
         	$list[$k]['ext'] = getExtension($v['save_name']);
322
         	$list[$k]['file_path'] = getFullPath($v['file_path']);
334
         	$list[$k]['file_path'] = getFullPath($v['file_path']);
323
         	$list[$k]['file_path_thumb'] = getFullPath($v['file_path_thumb']);
335
         	$list[$k]['file_path_thumb'] = getFullPath($v['file_path_thumb']);
336
+        	$list[$k]['readOnly'] = !empty($activityType[$moduleName]) && in_array($v['file_id'], $activityFileIds) ? 1 : 0; # 活动中上次的附件,只能在活动中删除
324
         }
337
         }
325
         $data = [];
338
         $data = [];
326
         $data['list'] = $list ? : [];
339
         $data['list'] = $list ? : [];

+ 3
- 1
application/admin/model/Group.php Целия файл

117
             }
117
             }
118
             $param['rules'] = arrayToString(array_unique($rulesParam));
118
             $param['rules'] = arrayToString(array_unique($rulesParam));
119
         }
119
         }
120
-
120
+        if($param['title']){
121
+        	unset($param['rules']);
122
+        }
121
 		$flag = $this->where('id = '.$group_id)->update($param);
123
 		$flag = $this->where('id = '.$group_id)->update($param);
122
 		if ($flag) {
124
 		if ($flag) {
123
 			return true;
125
 			return true;

+ 14
- 40
application/admin/model/User.php Целия файл

185
 			$list[$k]['img'] = $v['img'] ? getFullPath($v['img']) : '';
185
 			$list[$k]['img'] = $v['img'] ? getFullPath($v['img']) : '';
186
 			$list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
186
 			$list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
187
 			$list[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
187
 			$list[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
188
+			$list[$k]['s_name'] = !empty($v['s_name']) ? $v['s_name'] : '';
189
+			$list[$k]['structure_id'] = !empty($v['structure_id']) ? $v['structure_id'] : '';
188
 		}															
190
 		}															
189
 		$data = [];			
191
 		$data = [];			
190
 		$data['list'] = $list;				
192
 		$data['list'] = $list;				
516
 
518
 
517
 		//登录有效时间
519
 		//登录有效时间
518
         $cacheConfig = config('cache');
520
         $cacheConfig = config('cache');
519
-        $loginExpire = $cacheConfig['expire'] ? : 86400*3;        
521
+        $loginExpire = !empty($cacheConfig['expire']) ? $cacheConfig['expire'] : 86400 * 30;
520
 
522
 
521
         // 保存缓存
523
         // 保存缓存
522
         session_start();
524
         session_start();
528
         
530
         
529
     	$platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
531
     	$platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
530
 		//删除旧缓存
532
 		//删除旧缓存
531
-        if (cache('Auth_'.$userInfo['authkey'].$platform)) {
532
-       		cache('Auth_'.$userInfo['authkey'].$platform, NULL);
533
+        if (Cache::get('Auth_'.$userInfo['authkey'].$platform)) {
534
+            Cache::rm('Auth_'.$userInfo['authkey'].$platform);
533
         }
535
         }
534
-        cache('Auth_'.$authKey.$platform, $info, $loginExpire, 'UserToken');
536
+        Cache::set('Auth_'.$authKey.$platform, $info, $loginExpire);
535
         unset($userInfo['authkey']);
537
         unset($userInfo['authkey']);
536
 		
538
 		
537
         // 返回信息
539
         // 返回信息
574
 
576
 
575
 		//登录有效时间
577
 		//登录有效时间
576
         $cacheConfig = config('cache');
578
         $cacheConfig = config('cache');
577
-        $loginExpire = $cacheConfig['expire'] ? : '86400*3';         
579
+        $loginExpire = $cacheConfig['expire'] ? : 86400 * 3;
578
 
580
 
579
         $password = $this->where('id', $userInfo['id'])->value('password');
581
         $password = $this->where('id', $userInfo['id'])->value('password');
580
         if (user_md5($old_pwd, $userInfo['salt'], $userInfo['username']) != $password) {
582
         if (user_md5($old_pwd, $userInfo['salt'], $userInfo['username']) != $password) {
598
             session_start();
600
             session_start();
599
             $cache['userInfo'] = $userInfo;
601
             $cache['userInfo'] = $userInfo;
600
             $cache['authKey'] = user_md5($userInfo['username'].$userInfo['password'].session_id(), $userInfo['salt']);
602
             $cache['authKey'] = user_md5($userInfo['username'].$userInfo['password'].session_id(), $userInfo['salt']);
601
-            cache('Auth_'.$auth_key, null);
603
+            cache('Auth_'.$cache['authKey'], null);
602
             cache('Auth_'.$cache['authKey'], $cache, $loginExpire);
604
             cache('Auth_'.$cache['authKey'], $cache, $loginExpire);
603
             return $cache['authKey'];//把auth_key传回给前端
605
             return $cache['authKey'];//把auth_key传回给前端
604
         }
606
         }
713
             unset($authList['bi']);
715
             unset($authList['bi']);
714
         }
716
         }
715
         # 任务审批
717
         # 任务审批
716
-        if (in_array('taskExamine', $adminConfig) && !$authList['oa']) {
717
-            $oaAuth = ['announcement' => ['read' => true]];
718
-            $authList['oa'] = $oaAuth;
719
-            $authList['oa']['taskExamine'] = (Object)[];
720
-        } else {
721
-            $authList['oa'] = $authList['oa'];
718
+        if (in_array('taskExamine', $adminConfig) ) {
722
             $authList['oa']['taskExamine'] = (Object)[];
719
             $authList['oa']['taskExamine'] = (Object)[];
723
         }
720
         }
724
         # 项目
721
         # 项目
725
-        if (in_array('work', $adminConfig) && !$authList['work']) {
726
-            $oaAuth = ['work' => 'read'];
727
-            $authList['work'] = $oaAuth;
728
-        } else {
729
-            $authList['work'] = $authList['work'];
722
+        if (in_array('work', $adminConfig)) {
723
+            $authList['project']['projectLabelManage']['projectLabelAdd']    = !empty($authList['work']['work']['save']);
724
+            $authList['project']['projectLabelManage']['projectLabelDelete'] = !empty($authList['work']['work']['save']);
725
+            $authList['project']['projectLabelManage']['projectLabelUpdate'] = !empty($authList['work']['work']['save']);
726
+            $authList['project']['projectManage']['save']                    = !empty($authList['work']['work']['save']);
730
         }
727
         }
731
         # 日志
728
         # 日志
732
         if (in_array('log', $adminConfig)) {
729
         if (in_array('log', $adminConfig)) {
789
         if (!empty($authList['crm']['invoice']['index'])) {
786
         if (!empty($authList['crm']['invoice']['index'])) {
790
             $authList['crm']['invoiceTitle']['index'] = true;
787
             $authList['crm']['invoiceTitle']['index'] = true;
791
         }
788
         }
792
-//        else {
793
-//            $authList['crm']['invoice']['updateInvoiceStatus'] = false;
794
-//        }
795
-        # project
796
-        if (!empty($authList['work']['work']['update']) || !empty($authList['work']['work']['save'])) {
797
-            $authList['project']['projectLabelManage']['projectLabelAdd']    = true;
798
-            $authList['project']['projectLabelManage']['projectLabelDelete'] = true;
799
-            $authList['project']['projectLabelManage']['projectLabelUpdate'] = true;
800
-            $authList['project']['projectManage']['save']                    = true;
801
-        }
802
-//        else {
803
-//            $authList['project']['projectLabelManage']['projectLabelAdd']    = false;
804
-//            $authList['project']['projectLabelManage']['projectLabelDelete'] = false;
805
-//            $authList['project']['projectLabelManage']['projectLabelUpdate'] = false;
806
-//            $authList['project']['projectManage']['save']                    = false;
807
-//        }
808
-        # 项目
809
-        $projectRules = Db::name('admin_rule')->where(['types' => 3, 'level' => 4, 'status' => 0])->column('name');
810
-        if (!empty($authList['project']['projectManage']['save'])) {
811
-            foreach ($projectRules AS $key => $value) $authList['work']['project'][$value] = true;
812
-        } else {
813
-            $authList['work'] = [];
814
-        }
815
         unset($authList['work']['work']);
789
         unset($authList['work']['work']);
816
         unset($authList['work']['task']);
790
         unset($authList['work']['task']);
817
         unset($authList['work']['taskclass']);
791
         unset($authList['work']['taskclass']);

+ 1
- 1
application/admin/view/install/step2.html Целия файл

79
                     </div>
79
                     </div>
80
                     <div class="form-item">
80
                     <div class="form-item">
81
                         <div class="form-label">表前缀:</div>
81
                         <div class="form-label">表前缀:</div>
82
-                        <input type="text" class="wkform" name="databaseTable" placeholder="默认我5kcrm-">
82
+                        <input type="text" class="wkform" name="databaseTable" placeholder="默认我5kcrm-" disabled>
83
                         <!-- <div class="remind">默认为5kcrm_</div> -->
83
                         <!-- <div class="remind">默认为5kcrm_</div> -->
84
                     </div>
84
                     </div>
85
                     <div class="form-item">
85
                     <div class="form-item">

+ 1
- 1
application/admin/view/install/step5.html Целия файл

44
         </div>
44
         </div>
45
          <h1 style="text-align:center">恭喜您,已成功安装悟空CRM</h1>
45
          <h1 style="text-align:center">恭喜您,已成功安装悟空CRM</h1>
46
         <div class="desc" style="color:#acacac; font-weight: 600; margin-top: 50px; line-height:30px">
46
         <div class="desc" style="color:#acacac; font-weight: 600; margin-top: 50px; line-height:30px">
47
-            <p>您已经成功安装开源PHP悟空CRM,您可以尽情享用悟空CRM开源版有功能及服务.</p>
47
+            <p>您已经成功安装开源PHP悟空CRM,您可以尽情享用悟空CRM开源版有功能及服务.</p>
48
             <p>使用管理员账号即可登录</p>
48
             <p>使用管理员账号即可登录</p>
49
         </div>
49
         </div>
50
         <div class="control">
50
         <div class="control">

+ 97
- 0
application/admin/view/install/step6.html Целия файл

1
+<!DOCTYPE html>
2
+<html lang="zh-CN">
3
+<head>
4
+    <meta charset="UTF-8">
5
+    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
6
+    <title>悟空CRM安装向导</title>
7
+    <link rel="shortcut icon" href="__STATIC__/icon/favicon.ico">
8
+    <link rel="stylesheet" href="__STATIC__/style/base.css">
9
+    <link rel="stylesheet" href="__STATIC__/style/step3.css">
10
+    <script src="__STATIC__/js/jquery-3.3.1.min.js"></script>
11
+</head>
12
+<body>
13
+<div class="header-wrapper">
14
+    {include file="public/header"}
15
+</div>
16
+<div class="top">
17
+    <div class="step-group">
18
+        <div class="step active">
19
+            <div class="sort">
20
+                <img class="pic" style="width:100%; height: 100%;" src="__STATIC__/icon/success.png" alt="">
21
+            </div>
22
+            <div class="desc">检查安装环境</div>
23
+        </div>
24
+        <div class="step active line"></div>
25
+        <div class="step active">
26
+            <div class="sort">
27
+                <img class="pic" style="width:100%; height: 100%;" src="__STATIC__/icon/success.png" alt="">
28
+            </div>
29
+            <div class="desc">创建数据库</div>
30
+        </div>
31
+        <div class="step line active"></div>
32
+        <div class="step">
33
+            <div class="sort">
34
+                <img class="pic" style="width:100%; height: 100%;" src="__STATIC__/icon/success.png" alt="">
35
+            </div>
36
+            <div class="desc">安装失败</div>
37
+        </div>
38
+    </div>
39
+</div>
40
+<div class="container">
41
+    <div class="result">
42
+        <h1 style="text-align:center;padding-top: 20px;">安装悟空CRM数据库超时,请手动导入SQL文件!</h1>
43
+        <div class="desc" style="overflow:scroll;overflow-x:hidden;height:500px;color:#666666;font-weight: 600; margin-top: 50px; line-height:30px; text-align: left;padding-left: 20px;">
44
+            <p>1、SQL文件位置:public/sql/5kcrm.sql、public/sql/install.sql</p>
45
+            <p>2、在config目录下创建database.php文件</p>
46
+            <p>3、database.php文件内容:</p>
47
+            <p>return [</p>
48
+            <p>// 数据库类型</p>
49
+            <p>'type' => 'mysql',</p>
50
+            <p>// 服务器地址</p>
51
+            <p>'hostname' => '127.0.0.1',</p>
52
+            <p>// 数据库名</p>
53
+            <p>'database' => '',</p>
54
+            <p>// 用户名</p>
55
+            <p>'username' => '',</p>
56
+            <p>// 密码</p>
57
+            <p>'password' => '',</p>
58
+            <p>// 端口</p>
59
+            <p>'hostport' => '3306',</p>
60
+            <p>// 连接dsn</p>
61
+            <p>'dsn' => '',</p>
62
+            <p>// 数据库连接参数</p>
63
+            <p>'params' => [],</p>
64
+            <p>// 数据库编码默认采用utf8</p>
65
+            <p>'charset' => 'utf8',</p>
66
+            <p>// 数据库表前缀</p>
67
+            <p>'prefix' => '5kcrm_',</p>
68
+            <p>// 数据库调试模式</p>
69
+            <p>'debug' => true,</p>
70
+            <p>// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)</p>
71
+            <p>'deploy' => 0,</p>
72
+            <p>// 数据库读写是否分离 主从式有效</p>
73
+            <p>'rw_separate' => false,</p>
74
+            <p>// 读写分离后 主服务器数量</p>
75
+            <p>'master_num' => 1,</p>
76
+            <p>// 指定从服务器序号</p>
77
+            <p>'slave_no' => '',</p>
78
+            <p>// 自动读取主库数据</p>
79
+            <p>'read_master' => false,</p>
80
+            <p>// 是否严格检查字段是否存在</p>
81
+            <p>'fields_strict' => true,</p>
82
+            <p>// 数据集返回类型</p>
83
+            <p>'resultset_type' => 'array',</p>
84
+            <p>];</p>
85
+        </div>
86
+    </div>
87
+</div>
88
+<div class="footer-wrapper">
89
+    {include file="public/footer"}
90
+</div>
91
+</body>
92
+<script>
93
+    $('.login').click(function () {
94
+        window.location = '../../../index.html'
95
+    })
96
+</script>
97
+</html>

+ 151
- 156
application/bi/controller/Achievement.php Целия файл

38
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
38
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
39
         }
39
         }
40
     }
40
     }
41
-
41
+    
42
     /**
42
     /**
43
      * 业绩目标完成情况
43
      * 业绩目标完成情况
44
      *
44
      *
49
      */
49
      */
50
     public function statistics($param = '')
50
     public function statistics($param = '')
51
     {
51
     {
52
-        if($param['excel_type']!=1){
52
+        if ($param['excel_type'] != 1) {
53
             $param = $this->param;
53
             $param = $this->param;
54
         }
54
         }
55
-//        $achievementModel = new \app\crm\model\Achievement();
56
-//        $list = $achievementModel->getList($param) ? : [];
55
+
57
         $list = $this->getAchievementStatistics($param) ?: [];
56
         $list = $this->getAchievementStatistics($param) ?: [];
58
         //导出使用
57
         //导出使用
59
         if (!empty($param['excel_type'])) {
58
         if (!empty($param['excel_type'])) {
60
             $list = $this->excelStatistics($param) ?: [];
59
             $list = $this->excelStatistics($param) ?: [];
61
             return $list;
60
             return $list;
62
         }
61
         }
63
-
62
+        
64
         return resultArray(['data' => $list]);
63
         return resultArray(['data' => $list]);
65
     }
64
     }
66
-
65
+    
67
     /**
66
     /**
68
      * 业绩目标完成情况列表
67
      * 业绩目标完成情况列表
69
      *
68
      *
77
     {
76
     {
78
         # 结果数据
77
         # 结果数据
79
         $result = [];
78
         $result = [];
80
-
79
+        
81
         # 参数
80
         # 参数
82
-        $status      = !empty($param['status'])       ? $param['status']       : 1; # 类型:1合同目标;2回款目标;
83
-        $year        = !empty($param['year'])         ? $param['year']         : 0; # 年份
81
+        $status = !empty($param['status']) ? $param['status'] : 1; # 类型:1合同目标;2回款目标;
82
+        $year = !empty($param['year']) ? $param['year'] : 0; # 年份
84
         $structureId = !empty($param['structure_id']) ? $param['structure_id'] : 0; # 部门
83
         $structureId = !empty($param['structure_id']) ? $param['structure_id'] : 0; # 部门
85
-        $userId      = !empty($param['user_id'])      ? $param['user_id']      : 0; # 员工
86
-        $type        = !empty($param['type'])         ? $param['type']         : 1; # 类型:1部门;2员工
87
-
84
+        $userId = !empty($param['user_id']) ? $param['user_id'] : 0; # 员工
85
+        $type = !empty($param['type']) ? $param['type'] : 1; # 类型:1部门;2员工
86
+        
88
         # 设置业绩目标条件
87
         # 设置业绩目标条件
89
         $achievementWhere['year'] = $year;
88
         $achievementWhere['year'] = $year;
90
         $achievementWhere['status'] = $status;
89
         $achievementWhere['status'] = $status;
91
         $achievementWhere['type'] = !empty($type) && $type == 1 ? 2 : 3;
90
         $achievementWhere['type'] = !empty($type) && $type == 1 ? 2 : 3;
92
         if (!empty($userId)) $achievementWhere['obj_id'] = $userId;
91
         if (!empty($userId)) $achievementWhere['obj_id'] = $userId;
93
         if (!empty($structureId)) $achievementWhere['obj_id'] = $structureId;
92
         if (!empty($structureId)) $achievementWhere['obj_id'] = $structureId;
94
-
93
+        
95
         # 查询业绩目标数据
94
         # 查询业绩目标数据
96
         $achievementList = Db::name('crm_achievement')->where($achievementWhere)->select();
95
         $achievementList = Db::name('crm_achievement')->where($achievementWhere)->select();
97
-
96
+        
98
         if (empty($achievementList)) return [];
97
         if (empty($achievementList)) return [];
99
-
98
+        
100
         # 部门
99
         # 部门
101
         if ($type == 1) {
100
         if ($type == 1) {
102
             foreach ($achievementList as $key => $value) {
101
             foreach ($achievementList as $key => $value) {
118
                         '12' => ['achievement' => (int)$value['december'], 'money' => 0, 'rate' => 0, 'month' => '十二月']
117
                         '12' => ['achievement' => (int)$value['december'], 'money' => 0, 'rate' => 0, 'month' => '十二月']
119
                     ]
118
                     ]
120
                 ];
119
                 ];
121
-
120
+                
122
                 # 获取部门下的员工ID
121
                 # 获取部门下的员工ID
123
                 $userIds = Db::name('admin_user')->where('structure_id', $value['obj_id'])->column('id');
122
                 $userIds = Db::name('admin_user')->where('structure_id', $value['obj_id'])->column('id');
124
-
123
+                
125
                 # 业绩完成字段
124
                 # 业绩完成字段
126
                 $finishField = ["DATE_FORMAT(FROM_UNIXTIME(`create_time`,'%Y-%m-%d'),'%m') AS time", 'sum(money) AS money'];
125
                 $finishField = ["DATE_FORMAT(FROM_UNIXTIME(`create_time`,'%Y-%m-%d'),'%m') AS time", 'sum(money) AS money'];
127
-
126
+                
128
                 # 业绩完成条件
127
                 # 业绩完成条件
129
                 $finishWhere['check_status'] = 2;
128
                 $finishWhere['check_status'] = 2;
130
                 $finishWhere['owner_user_id'] = ['in', $userIds];
129
                 $finishWhere['owner_user_id'] = ['in', $userIds];
131
-
130
+                
132
                 # 合同
131
                 # 合同
133
                 if ($status == 1) {
132
                 if ($status == 1) {
134
                     $finishArray = Db::name('crm_contract')->field($finishField)->where($finishWhere)->group('time')->select();
133
                     $finishArray = Db::name('crm_contract')->field($finishField)->where($finishWhere)->group('time')->select();
135
                 }
134
                 }
136
-
135
+                
137
                 # 回款
136
                 # 回款
138
                 if ($status == 2) {
137
                 if ($status == 2) {
139
                     $finishArray = Db::name('crm_receivables')->field($finishField)->where($finishWhere)->group('time')->select();
138
                     $finishArray = Db::name('crm_receivables')->field($finishField)->where($finishWhere)->group('time')->select();
140
                 }
139
                 }
141
-
140
+                
142
                 # 计算完成情况
141
                 # 计算完成情况
143
                 foreach ($finishArray as $k => $v) {
142
                 foreach ($finishArray as $k => $v) {
144
                     if (!empty($result[$value['obj_id']]['list'][$v['time']])) {
143
                     if (!empty($result[$value['obj_id']]['list'][$v['time']])) {
145
                         $achievement = $result[$value['obj_id']]['list'][$v['time']]['achievement'];
144
                         $achievement = $result[$value['obj_id']]['list'][$v['time']]['achievement'];
146
-
145
+                        
147
                         $result[$value['obj_id']]['list'][$v['time']]['money'] = (int)$v['money'];
146
                         $result[$value['obj_id']]['list'][$v['time']]['money'] = (int)$v['money'];
148
                         $result[$value['obj_id']]['list'][$v['time']]['rate'] = (int)(($v['money'] / $achievement) * 100);
147
                         $result[$value['obj_id']]['list'][$v['time']]['rate'] = (int)(($v['money'] / $achievement) * 100);
149
-
148
+                        
150
                     }
149
                     }
151
                 }
150
                 }
152
-
151
+                
153
                 $result[$value['obj_id']]['list'] = array_values($result[$value['obj_id']]['list']);
152
                 $result[$value['obj_id']]['list'] = array_values($result[$value['obj_id']]['list']);
154
             }
153
             }
155
         }
154
         }
156
-
155
+        
157
         # 员工
156
         # 员工
158
         if ($type == 2) {
157
         if ($type == 2) {
159
             $userData = [];
158
             $userData = [];
160
             $userList = db('admin_user')->field(['id', 'realname'])->select();
159
             $userList = db('admin_user')->field(['id', 'realname'])->select();
161
-            foreach ($userList AS $key => $value) {
160
+            foreach ($userList as $key => $value) {
162
                 $userData[$value['id']] = $value['realname'];
161
                 $userData[$value['id']] = $value['realname'];
163
             }
162
             }
164
-
163
+            
165
             foreach ($achievementList as $key => $value) {
164
             foreach ($achievementList as $key => $value) {
166
                 # 组装结果数据
165
                 # 组装结果数据
167
                 $result[$value['obj_id']] = [
166
                 $result[$value['obj_id']] = [
181
                         '12' => ['achievement' => (int)$value['december'], 'money' => 0, 'rate' => 0, 'month' => '十二月']
180
                         '12' => ['achievement' => (int)$value['december'], 'money' => 0, 'rate' => 0, 'month' => '十二月']
182
                     ]
181
                     ]
183
                 ];
182
                 ];
184
-
185
                 # 业绩完成字段
183
                 # 业绩完成字段
186
                 $finishField = ["DATE_FORMAT(FROM_UNIXTIME(`create_time`,'%Y-%m-%d'),'%m') AS time", 'sum(money) AS money'];
184
                 $finishField = ["DATE_FORMAT(FROM_UNIXTIME(`create_time`,'%Y-%m-%d'),'%m') AS time", 'sum(money) AS money'];
187
-
185
+                
188
                 # 业绩完成条件
186
                 # 业绩完成条件
189
                 $finishWhere = ['check_status' => 2, 'owner_user_id' => $value['obj_id']];
187
                 $finishWhere = ['check_status' => 2, 'owner_user_id' => $value['obj_id']];
190
-
188
+                
191
                 # 合同
189
                 # 合同
192
                 if ($status == 1) {
190
                 if ($status == 1) {
193
                     $finishArray = Db::name('crm_contract')->field($finishField)->where($finishWhere)->group('time')->select();
191
                     $finishArray = Db::name('crm_contract')->field($finishField)->where($finishWhere)->group('time')->select();
194
                 }
192
                 }
195
-
193
+                
196
                 # 回款
194
                 # 回款
197
                 if ($status == 2) {
195
                 if ($status == 2) {
198
                     $finishArray = Db::name('crm_receivables')->field($finishField)->where($finishWhere)->group('time')->select();
196
                     $finishArray = Db::name('crm_receivables')->field($finishField)->where($finishWhere)->group('time')->select();
199
                 }
197
                 }
200
-
198
+                
201
                 # 计算完成情况
199
                 # 计算完成情况
202
                 foreach ($finishArray as $k => $v) {
200
                 foreach ($finishArray as $k => $v) {
203
                     if (!empty($result[$value['obj_id']]['list'][$v['time']])) {
201
                     if (!empty($result[$value['obj_id']]['list'][$v['time']])) {
204
                         $achievement = $result[$value['obj_id']]['list'][$v['time']]['achievement'];
202
                         $achievement = $result[$value['obj_id']]['list'][$v['time']]['achievement'];
205
-
203
+                        
206
                         $result[$value['obj_id']]['list'][$v['time']]['money'] = (int)$v['money'];
204
                         $result[$value['obj_id']]['list'][$v['time']]['money'] = (int)$v['money'];
207
                         $result[$value['obj_id']]['list'][$v['time']]['rate'] = (int)(($v['money'] / $achievement) * 100);
205
                         $result[$value['obj_id']]['list'][$v['time']]['rate'] = (int)(($v['money'] / $achievement) * 100);
208
                     }
206
                     }
209
                 }
207
                 }
210
-
208
+                
211
                 $result[$value['obj_id']]['list'] = array_values($result[$value['obj_id']]['list']);
209
                 $result[$value['obj_id']]['list'] = array_values($result[$value['obj_id']]['list']);
212
             }
210
             }
213
         }
211
         }
214
-
212
+        
215
         return array_values($result);
213
         return array_values($result);
216
     }
214
     }
217
-
215
+    
218
     public function excelStatistics($param)
216
     public function excelStatistics($param)
219
     {
217
     {
220
         # 结果数据
218
         # 结果数据
221
         $result = [];
219
         $result = [];
222
-
220
+    
223
         # 参数
221
         # 参数
224
         $status = !empty($param['status']) ? $param['status'] : 1; # 类型:1合同目标;2回款目标;
222
         $status = !empty($param['status']) ? $param['status'] : 1; # 类型:1合同目标;2回款目标;
225
         $year = !empty($param['year']) ? $param['year'] : 0; # 年份
223
         $year = !empty($param['year']) ? $param['year'] : 0; # 年份
226
         $structureId = !empty($param['structure_id']) ? $param['structure_id'] : 0; # 部门
224
         $structureId = !empty($param['structure_id']) ? $param['structure_id'] : 0; # 部门
227
         $userId = !empty($param['user_id']) ? $param['user_id'] : 0; # 员工
225
         $userId = !empty($param['user_id']) ? $param['user_id'] : 0; # 员工
228
         $type = !empty($param['type']) ? $param['type'] : 1; # 类型:1部门;2员工
226
         $type = !empty($param['type']) ? $param['type'] : 1; # 类型:1部门;2员工
229
-
227
+    
230
         # 设置业绩目标条件
228
         # 设置业绩目标条件
231
         $achievementWhere['year'] = $year;
229
         $achievementWhere['year'] = $year;
232
         $achievementWhere['status'] = $status;
230
         $achievementWhere['status'] = $status;
233
         $achievementWhere['type'] = !empty($type) && $type == 1 ? 2 : 3;
231
         $achievementWhere['type'] = !empty($type) && $type == 1 ? 2 : 3;
234
         if (!empty($userId)) $achievementWhere['obj_id'] = $userId;
232
         if (!empty($userId)) $achievementWhere['obj_id'] = $userId;
235
         if (!empty($structureId)) $achievementWhere['obj_id'] = $structureId;
233
         if (!empty($structureId)) $achievementWhere['obj_id'] = $structureId;
236
-
234
+    
237
         # 查询业绩目标数据
235
         # 查询业绩目标数据
238
         $achievementList = Db::name('crm_achievement')->where($achievementWhere)->select();
236
         $achievementList = Db::name('crm_achievement')->where($achievementWhere)->select();
239
-
237
+    
240
         if (empty($achievementList)) return [];
238
         if (empty($achievementList)) return [];
241
-
239
+    
242
         # 部门
240
         # 部门
243
         if ($type == 1) {
241
         if ($type == 1) {
244
             foreach ($achievementList as $key => $value) {
242
             foreach ($achievementList as $key => $value) {
245
                 # 组装结果数据
243
                 # 组装结果数据
246
-                $result[] = [
247
-                    ['name' => $value['name'], 'achievement' => (int)$value['january'], 'money' => 0, 'rate' => 0, 'month' => '一月'],
248
-                    ['name' => $value['name'], 'achievement' => (int)$value['february'], 'money' => 0, 'rate' => 0, 'month' => '二月'],
249
-                    ['name' => $value['name'], 'achievement' => (int)$value['march'], 'money' => 0, 'rate' => 0, 'month' => '三月'],
250
-
251
-                    ['name' => '', 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第一季度'],
252
-
253
-                    ['name' => $value['name'], 'achievement' => (int)$value['april'], 'money' => 0, 'rate' => 0, 'month' => '四月'],
254
-                    ['name' => $value['name'], 'achievement' => (int)$value['may'], 'money' => 0, 'rate' => 0, 'month' => '五月'],
255
-                    ['name' => $value['name'], 'achievement' => (int)$value['june'], 'money' => 0, 'rate' => 0, 'month' => '六月'],
256
-
257
-                    ['name' => $value['name'], 'achievement' => (int)$value['april'], 'money' => 0, 'rate' => 0, 'month' => '第二季度'],
258
-
259
-                    ['name' => $value['name'], 'achievement' => (int)$value['july'], 'money' => 0, 'rate' => 0, 'month' => '七月'],
260
-                    ['name' => $value['name'], 'achievement' => (int)$value['august'], 'money' => 0, 'rate' => 0, 'month' => '八月'],
261
-                    ['name' => $value['name'], 'achievement' => (int)$value['september'], 'money' => 0, 'rate' => 0, 'month' => '九月'],
262
-
263
-                    ['name' => $value['name'], 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第三季度'],
264
-
265
-                    ['name' => $value['name'], 'achievement' => (int)$value['october'], 'money' => 0, 'rate' => 0, 'month' => '十月'],
266
-                    ['name' => $value['name'], 'achievement' => (int)$value['november'], 'money' => 0, 'rate' => 0, 'month' => '十一月'],
267
-                    ['name' => $value['name'], 'achievement' => (int)$value['december'], 'money' => 0, 'rate' => 0, 'month' => '十二月'],
268
-
269
-                    ['name' => $value['name'], 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第四季度'],
270
-                    ['name' => $value['name'], 'achievement' => (int)$value['yeartarget'], 'money' => 0, 'rate' => 0, 'month' => '全年'],
244
+                $result[$value['obj_id']] = [
245
+                    'list' => [
246
+                        
247
+                        '01' => ['name' => $value['name'] ,'achievement' => (int)$value['january'], 'money' => 0, 'rate' => 0, 'month' => '一月'],
248
+                        '02' => ['name' => $value['name'] ,'achievement' => (int)$value['february'], 'money' => 0, 'rate' => 0, 'month' => '二月'],
249
+                        '03' => ['name' => $value['name'] ,'achievement' => (int)$value['march'], 'money' => 0, 'rate' => 0, 'month' => '三月'],
250
+                        
251
+                        '04' => ['name' => '', 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第一季度'],
252
+                        
253
+                        '05' => ['name' => $value['name'] ,'achievement' => (int)$value['april'], 'money' => 0, 'rate' => 0, 'month' => '四月'],
254
+                        '06' => ['name' => $value['name'] ,'achievement' => (int)$value['may'], 'money' => 0, 'rate' => 0, 'month' => '五月'],
255
+                        '07' => ['name' => $value['name'] ,'achievement' => (int)$value['june'], 'money' => 0, 'rate' => 0, 'month' => '六月'],
256
+                        
257
+                        '08' => ['name' => '', 'achievement' => (int)$value['april'], 'money' => 0, 'rate' => 0, 'month' => '第二季度'],
258
+                        
259
+                        '09' => ['name' => $value['name'] ,'achievement' => (int)$value['july'], 'money' => 0, 'rate' => 0, 'month' => '七月'],
260
+                        '10' => ['name' => $value['name'] ,'achievement' => (int)$value['august'], 'money' => 0, 'rate' => 0, 'month' => '八月'],
261
+                        '11' => ['name' => $value['name'] ,'achievement' => (int)$value['september'], 'money' => 0, 'rate' => 0, 'month' => '九月'],
262
+                        
263
+                        '12' => ['name' => '', 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第三季度'],
264
+                        
265
+                        '13' => ['name' => $value['name'] ,'achievement' => (int)$value['october'], 'money' => 0, 'rate' => 0, 'month' => '十月'],
266
+                        '14' => ['name' => $value['name'] ,'achievement' => (int)$value['november'], 'money' => 0, 'rate' => 0, 'month' => '十一月'],
267
+                        '15' => ['name' => $value['name'] ,'achievement' => (int)$value['december'], 'money' => 0, 'rate' => 0, 'month' => '十二月'],
268
+                        
269
+                        '16' => ['name' => '', 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第四季度'],
270
+                        '17' => ['name' => '', 'achievement' => (int)$value['yeartarget'], 'money' => 0, 'rate' => 0, 'month' => '全年'],
271
+                    ]
271
                 ];
272
                 ];
272
-
273
+            
273
                 # 获取部门下的员工ID
274
                 # 获取部门下的员工ID
274
                 $userIds = Db::name('admin_user')->where('structure_id', $value['obj_id'])->column('id');
275
                 $userIds = Db::name('admin_user')->where('structure_id', $value['obj_id'])->column('id');
275
-
276
+            
276
                 # 业绩完成字段
277
                 # 业绩完成字段
277
                 $finishField = ["DATE_FORMAT(FROM_UNIXTIME(`create_time`,'%Y-%m-%d'),'%m') AS time", 'sum(money) AS money'];
278
                 $finishField = ["DATE_FORMAT(FROM_UNIXTIME(`create_time`,'%Y-%m-%d'),'%m') AS time", 'sum(money) AS money'];
278
-
279
+            
279
                 # 业绩完成条件
280
                 # 业绩完成条件
280
                 $finishWhere['check_status'] = 2;
281
                 $finishWhere['check_status'] = 2;
281
                 $finishWhere['owner_user_id'] = ['in', $userIds];
282
                 $finishWhere['owner_user_id'] = ['in', $userIds];
282
-
283
+            
283
                 # 合同
284
                 # 合同
284
                 if ($status == 1) {
285
                 if ($status == 1) {
285
                     $finishArray = Db::name('crm_contract')->field($finishField)->where($finishWhere)->group('time')->select();
286
                     $finishArray = Db::name('crm_contract')->field($finishField)->where($finishWhere)->group('time')->select();
286
                 }
287
                 }
287
-
288
+            
288
                 # 回款
289
                 # 回款
289
                 if ($status == 2) {
290
                 if ($status == 2) {
290
                     $finishArray = Db::name('crm_receivables')->field($finishField)->where($finishWhere)->group('time')->select();
291
                     $finishArray = Db::name('crm_receivables')->field($finishField)->where($finishWhere)->group('time')->select();
291
                 }
292
                 }
292
-
293
+            
293
                 # 计算完成情况
294
                 # 计算完成情况
294
                 foreach ($finishArray as $k => $v) {
295
                 foreach ($finishArray as $k => $v) {
295
-                    if (!empty($result[$v['time']])) {
296
-                        $achievement = $result[$v['time']]['achievement'];
297
-                        $result[$v['time']]['money'] = (int)$v['money'];
298
-                        $result[$v['time']]['rate'] = (int)(($v['money'] / $achievement) * 100);
296
+                    if (!empty($result[$value['obj_id']]['list'][$v['time']])) {
297
+                        $achievement = $result[$value['obj_id']]['list'][$v['time']]['achievement'];
298
+                    
299
+                        $result[$value['obj_id']]['list'][$v['time']]['money'] = (int)$v['money'];
300
+                        $result[$value['obj_id']]['list'][$v['time']]['rate'] = (int)(($v['money'] / $achievement) * 100);
301
+                    
299
                     }
302
                     }
300
-
301
-                }
302
-                foreach ($result as &$val){
303
-                    $val[3]['money']=$val[0]['money']+$val[1]['money']+$val[2]['money'];
304
-                    $val[3]['rate']=$val[0]['rate']+$val[1]['rate']+$val[2]['rate'];
305
-                    $val[7]['money']=$val[4]['money']+$val[5]['money']+$val[6]['money'];
306
-                    $val[7]['rate']=$val[4]['rate']+$val[5]['rate']+$val[6]['rate'];
307
-                    $val[11]['money']=$val[7]['money']+$val[9]['money']+$val[10]['money'];
308
-                    $val[11]['rate']=$val[8]['rate']+$val[9]['rate']+$val[10]['rate'];
309
-                    $val[15]['money']=$val[12]['money']+$val[13]['money']+$val[14]['money'];
310
-                    $val[15]['rate']=$val[12]['rate']+$val[13]['rate']+$val[14]['rate'];
311
-                    $val[15]['money']=$val[12]['money']+$val[13]['money']+$val[14]['money'];
312
-                    $val[15]['rate']=$val[12]['rate']+$val[13]['rate']+$val[14]['rate'];
313
-                    $val[16]['money']=$val[3]['money']+$val[7]['money']+$val[11]['money']+$val[15]['money'];
314
-                    $val[16]['rate']=$val[3]['rate']+$val[7]['rate']+$val[11]['rate']+$val[15]['rate'];
315
                 }
303
                 }
316
-
317
-                $result = array_values($result);
304
+            
305
+                $result[$value['obj_id']]['list'] = array_values($result[$value['obj_id']]['list']);
306
+                $item[]=$result[$value['obj_id']]['list'];
318
             }
307
             }
319
         }
308
         }
320
 
309
 
321
         # 员工
310
         # 员工
322
         if ($type == 2) {
311
         if ($type == 2) {
323
-            foreach ($achievementList AS $key => $value) {
312
+            $userData = [];
313
+            $userList = db('admin_user')->field(['id', 'realname'])->select();
314
+            foreach ($userList as $key => $value) {
315
+                $userData[$value['id']] = $value['realname'];
316
+            }
317
+        
318
+            foreach ($achievementList as $key => $value) {
324
                 # 组装结果数据
319
                 # 组装结果数据
325
-
326
-
327
-                $result[] = [
328
-                    ['name' => $value['name'], 'achievement' => (int)$value['january'], 'money' => 0, 'rate' => 0, 'month' => '一月'],
329
-                    ['name' => $value['name'], 'achievement' => (int)$value['february'], 'money' => 0, 'rate' => 0, 'month' => '二月'],
330
-                    ['name' => $value['name'], 'achievement' => (int)$value['march'], 'money' => 0, 'rate' => 0, 'month' => '三月'],
331
-
332
-                    ['name' => '', 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第一季度'],
333
-
334
-                    ['name' => $value['name'], 'achievement' => (int)$value['april'], 'money' => 0, 'rate' => 0, 'month' => '四月'],
335
-                    ['name' => $value['name'], 'achievement' => (int)$value['may'], 'money' => 0, 'rate' => 0, 'month' => '五月'],
336
-                    ['name' => $value['name'], 'achievement' => (int)$value['june'], 'money' => 0, 'rate' => 0, 'month' => '六月'],
337
-
338
-                    ['name' => $value['name'], 'achievement' => (int)$value['april'], 'money' => 0, 'rate' => 0, 'month' => '第二季度'],
339
-
340
-                    ['name' => $value['name'], 'achievement' => (int)$value['july'], 'money' => 0, 'rate' => 0, 'month' => '七月'],
341
-                    ['name' => $value['name'], 'achievement' => (int)$value['august'], 'money' => 0, 'rate' => 0, 'month' => '八月'],
342
-                    ['name' => $value['name'], 'achievement' => (int)$value['september'], 'money' => 0, 'rate' => 0, 'month' => '九月'],
343
-
344
-                    ['name' => $value['name'], 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第三季度'],
345
-
346
-                    ['name' => $value['name'], 'achievement' => (int)$value['october'], 'money' => 0, 'rate' => 0, 'month' => '十月'],
347
-                    ['name' => $value['name'], 'achievement' => (int)$value['november'], 'money' => 0, 'rate' => 0, 'month' => '十一月'],
348
-                    ['name' => $value['name'], 'achievement' => (int)$value['december'], 'money' => 0, 'rate' => 0, 'month' => '十二月'],
349
-
350
-                    ['name' => $value['name'], 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第四季度'],
351
-                    ['name' => $value['name'], 'achievement' => (int)$value['yeartarget'], 'money' => 0, 'rate' => 0, 'month' => '全年'],
320
+                $result[$value['obj_id']] = [
321
+                    'list' => [
322
+                        '01' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['january'], 'money' => 0, 'rate' => 0, 'month' => '一月'],
323
+                        '02' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['february'], 'money' => 0, 'rate' => 0, 'month' => '二月'],
324
+                        '03' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['march'], 'money' => 0, 'rate' => 0, 'month' => '三月'],
325
+                        
326
+                        '04' => ['name' => '', 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第一季度'],
327
+                        
328
+                        '05' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['april'], 'money' => 0, 'rate' => 0, 'month' => '四月'],
329
+                        '06' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['may'], 'money' => 0, 'rate' => 0, 'month' => '五月'],
330
+                        '07' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['june'], 'money' => 0, 'rate' => 0, 'month' => '六月'],
331
+                        
332
+                        '08' => ['name' => '', 'achievement' => (int)$value['april'], 'money' => 0, 'rate' => 0, 'month' => '第二季度'],
333
+                        
334
+                        '09' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['july'], 'money' => 0, 'rate' => 0, 'month' => '七月'],
335
+                        '10' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['august'], 'money' => 0, 'rate' => 0, 'month' => '八月'],
336
+                        '11' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['september'], 'money' => 0, 'rate' => 0, 'month' => '九月'],
337
+                        
338
+                        '12' => ['name' => '', 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第三季度'],
339
+                        
340
+                        '13' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['october'], 'money' => 0, 'rate' => 0, 'month' => '十月'],
341
+                        '14' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['november'], 'money' => 0, 'rate' => 0, 'month' => '十一月'],
342
+                        '15' => ['name' =>!empty($value['name']) ? $value['name'] : $userData[$value['obj_id']],'achievement' => (int)$value['december'], 'money' => 0, 'rate' => 0, 'month' => '十二月'],
343
+                        
344
+                        '16' => ['name' => '', 'achievement' => 0, 'money' => 0, 'rate' => 0, 'month' => '第四季度'],
345
+                        '17' => ['name' => '', 'achievement' => (int)$value['yeartarget'], 'money' => 0, 'rate' => 0, 'month' => '全年'],
346
+                    ]
352
                 ];
347
                 ];
353
-
354
-
355
-
356
                 # 业绩完成字段
348
                 # 业绩完成字段
357
                 $finishField = ["DATE_FORMAT(FROM_UNIXTIME(`create_time`,'%Y-%m-%d'),'%m') AS time", 'sum(money) AS money'];
349
                 $finishField = ["DATE_FORMAT(FROM_UNIXTIME(`create_time`,'%Y-%m-%d'),'%m') AS time", 'sum(money) AS money'];
358
-
350
+            
359
                 # 业绩完成条件
351
                 # 业绩完成条件
360
                 $finishWhere = ['check_status' => 2, 'owner_user_id' => $value['obj_id']];
352
                 $finishWhere = ['check_status' => 2, 'owner_user_id' => $value['obj_id']];
361
-
353
+            
362
                 # 合同
354
                 # 合同
363
                 if ($status == 1) {
355
                 if ($status == 1) {
364
                     $finishArray = Db::name('crm_contract')->field($finishField)->where($finishWhere)->group('time')->select();
356
                     $finishArray = Db::name('crm_contract')->field($finishField)->where($finishWhere)->group('time')->select();
365
                 }
357
                 }
366
-
358
+            
367
                 # 回款
359
                 # 回款
368
                 if ($status == 2) {
360
                 if ($status == 2) {
369
                     $finishArray = Db::name('crm_receivables')->field($finishField)->where($finishWhere)->group('time')->select();
361
                     $finishArray = Db::name('crm_receivables')->field($finishField)->where($finishWhere)->group('time')->select();
370
                 }
362
                 }
371
-
363
+            
372
                 # 计算完成情况
364
                 # 计算完成情况
373
-                foreach ($finishArray AS $k => $v) {
374
-                    if (!empty($result[$v['time']])) {
375
-                        $achievement = $result[$v['time']]['achievement'];
376
-
377
-                        $result[$v['time']]['money'] = (int)$v['money'];
378
-                        $result[$v['time']]['rate']  = (int)(($v['money'] / $achievement) * 100);
365
+                foreach ($finishArray as $k => $v) {
366
+                    if (!empty($result[$value['obj_id']]['list'][$v['time']])) {
367
+                        $achievement = $result[$value['obj_id']]['list'][$v['time']]['achievement'];
368
+                    
369
+                        $result[$value['obj_id']]['list'][$v['time']]['money'] = (int)$v['money'];
370
+                        $result[$value['obj_id']]['list'][$v['time']]['rate'] = (int)(($v['money'] / $achievement) * 100);
379
                     }
371
                     }
380
                 }
372
                 }
381
-
382
-                foreach ($result as &$val){
383
-                    $val[3]['money']=$val[0]['money']+$val[1]['money']+$val[2]['money'];
384
-                    $val[3]['rate']=$val[0]['rate']+$val[1]['rate']+$val[2]['rate'];
385
-                    $val[7]['money']=$val[4]['money']+$val[5]['money']+$val[6]['money'];
386
-                    $val[7]['rate']=$val[4]['rate']+$val[5]['rate']+$val[6]['rate'];
387
-                    $val[11]['money']=$val[7]['money']+$val[9]['money']+$val[10]['money'];
388
-                    $val[11]['rate']=$val[8]['rate']+$val[9]['rate']+$val[10]['rate'];
389
-                    $val[15]['money']=$val[12]['money']+$val[13]['money']+$val[14]['money'];
390
-                    $val[15]['rate']=$val[12]['rate']+$val[13]['rate']+$val[14]['rate'];
391
-                    $val[15]['money']=$val[12]['money']+$val[13]['money']+$val[14]['money'];
392
-                    $val[15]['rate']=$val[12]['rate']+$val[13]['rate']+$val[14]['rate'];
393
-                    $val[16]['money']=$val[3]['money']+$val[7]['money']+$val[11]['money']+$val[15]['money'];
394
-                    $val[16]['rate']=$val[3]['rate']+$val[7]['rate']+$val[11]['rate']+$val[15]['rate'];
395
-                }
396
-                $result = array_values($result);
373
+            
374
+                $result[$value['obj_id']]['list'] = array_values($result[$value['obj_id']]['list']);
375
+                $item[]=$result[$value['obj_id']]['list'];
397
             }
376
             }
398
         }
377
         }
399
-
400
-        return array_values($result);
378
+       
379
+        foreach ($item as &$val){
380
+            $val[3]['money']=$val[0]['money']+$val[1]['money']+$val[2]['money'];
381
+            $val[3]['rate']=$val[0]['rate']+$val[1]['rate']+$val[2]['rate'];
382
+            $val[3]['achievement']=$val[0]['achievement']+$val[1]['achievement']+$val[2]['achievement'];
383
+            $val[7]['money']=$val[4]['money']+$val[5]['money']+$val[6]['money'];
384
+            $val[7]['rate']=$val[4]['rate']+$val[5]['rate']+$val[6]['rate'];
385
+            $val[7]['achievement']=$val[4]['achievement']+$val[5]['achievement']+$val[6]['achievement'];
386
+            $val[11]['money']=$val[7]['money']+$val[9]['money']+$val[10]['money'];
387
+            $val[11]['rate']=$val[8]['rate']+$val[9]['rate']+$val[10]['rate'];
388
+            $val[11]['achievement']=$val[8]['achievement']+$val[9]['achievement']+$val[10]['achievement'];
389
+            $val[15]['money']=$val[12]['money']+$val[13]['money']+$val[14]['money'];
390
+            $val[15]['rate']=$val[12]['rate']+$val[13]['rate']+$val[14]['rate'];
391
+            $val[15]['achievement']=$val[12]['achievement']+$val[13]['achievement']+$val[14]['achievement'];
392
+            $val[16]['money']=$val[3]['money']+$val[7]['money']+$val[11]['money']+$val[15]['money'];
393
+            $val[16]['rate']=$val[3]['rate']+$val[7]['rate']+$val[11]['rate']+$val[15]['rate'];
394
+        }
395
+        return $item;
401
     }
396
     }
402
-
397
+    
403
     /**
398
     /**
404
      * 导出
399
      * 导出
405
      * @param $type
400
      * @param $type
409
     {
404
     {
410
         $param = $this->param;
405
         $param = $this->param;
411
         $list = $this->statistics($param);
406
         $list = $this->statistics($param);
412
-        if(empty($list)){
413
-            return resultArray(['data'=>'数据不存在']);
407
+        if (empty($list)) {
408
+            return resultArray(['data' => '数据不存在']);
414
         }
409
         }
415
         $excelLogic = new ExcelLogic();
410
         $excelLogic = new ExcelLogic();
416
-        $data = $excelLogic->achienementExcel($param, $list);
411
+        $data = $excelLogic->achienementExcel($list);
417
         return $data;
412
         return $data;
418
     }
413
     }
419
 }
414
 }

+ 48
- 39
application/bi/controller/Business.php Целия файл

58
         if (empty($this->param['type_id'])) return resultArray(['error' => '请选择商机组!']);
58
         if (empty($this->param['type_id'])) return resultArray(['error' => '请选择商机组!']);
59
 
59
 
60
         $businessModel = new \app\crm\model\Business();
60
         $businessModel = new \app\crm\model\Business();
61
-
62
         $param = $this->param;
61
         $param = $this->param;
63
-
64
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
62
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
65
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
63
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
66
         unset($param['sort_field']);
64
         unset($param['sort_field']);
67
         unset($param['sort_value']);
65
         unset($param['sort_value']);
68
 
66
 
69
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
70
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
67
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
68
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
71
 
69
 
72
         $data = $businessModel->getFunnel($param);
70
         $data = $businessModel->getFunnel($param);
73
         foreach ($data['list'] AS $key => $value) {
71
         foreach ($data['list'] AS $key => $value) {
93
         $userModel     = new \app\admin\model\User();
91
         $userModel     = new \app\admin\model\User();
94
         $adminModel    = new \app\admin\model\Admin();
92
         $adminModel    = new \app\admin\model\Admin();
95
         $param         = $this->param;
93
         $param         = $this->param;
96
-
97
         $perUserIds = $userModel->getUserByPer('bi', 'business', 'read'); //权限范围内userIds
94
         $perUserIds = $userModel->getUserByPer('bi', 'business', 'read'); //权限范围内userIds
98
         $whereArr = $adminModel->getWhere($param, '', $perUserIds); //统计条件
95
         $whereArr = $adminModel->getWhere($param, '', $perUserIds); //统计条件
99
         $userIds = $whereArr['userIds'];
96
         $userIds = $whereArr['userIds'];
109
             'owner_user_id' => !empty($userIds) ? implode(',',$userIds) : '9999999999'
106
             'owner_user_id' => !empty($userIds) ? implode(',',$userIds) : '9999999999'
110
         ];
107
         ];
111
         $sql = [];
108
         $sql = [];
112
-
113
         foreach ($time['list'] as $val) {
109
         foreach ($time['list'] as $val) {
114
             $whereArr = $where;
110
             $whereArr = $where;
115
             $whereArr['type'] = $val['type'];
111
             $whereArr['type'] = $val['type'];
136
         $businessModel = new \app\bi\model\Business();
132
         $businessModel = new \app\bi\model\Business();
137
         $crmBusinessModel = new \app\crm\model\Business();
133
         $crmBusinessModel = new \app\crm\model\Business();
138
         $userModel = new \app\admin\model\User();
134
         $userModel = new \app\admin\model\User();
135
+        $adminModel    = new \app\admin\model\Admin();
139
         $param = $this->param;
136
         $param = $this->param;
140
         unset($param['types']);
137
         unset($param['types']);
141
-
142
         # 日期条件
138
         # 日期条件
143
         if (!empty($param['type'])) {
139
         if (!empty($param['type'])) {
144
             $param['start_time'] = strtotime($param['type'] . '-01 00:00:00');
140
             $param['start_time'] = strtotime($param['type'] . '-01 00:00:00');
166
             $dataList['list'][$k]['create_user_name'] = $create_user_id_info['realname'];
162
             $dataList['list'][$k]['create_user_name'] = $create_user_id_info['realname'];
167
             $owner_user_id_info = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
163
             $owner_user_id_info = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
168
             $dataList['list'][$k]['owner_user_name'] = $owner_user_id_info['realname'];
164
             $dataList['list'][$k]['owner_user_name'] = $owner_user_id_info['realname'];
169
-            $dataList['list'][$k]['business_stage'] = db('crm_business_status')->where('status_id',$v['status_id'])->value('name');//销售阶段
165
+                if($v['is_end']!=0){
166
+                    $dataList['list'][$k]['business_stage'] = db('crm_business_status')->where('status_id',$v['is_end'])->value('name');//销售阶段
167
+                }else{
168
+                    $dataList['list'][$k]['business_stage'] = db('crm_business_status')->where('status_id',$v['status_id'])->value('name');//销售阶段
169
+                }
170
             $dataList['list'][$k]['business_type'] = db('crm_business_type')->where('type_id',$v['type_id'])->value('name');//商机状态组
170
             $dataList['list'][$k]['business_type'] = db('crm_business_type')->where('type_id',$v['type_id'])->value('name');//商机状态组
171
+            
171
         }
172
         }
172
 
173
 
173
         # 排序
174
         # 排序
190
         $userModel = new \app\admin\model\User();
191
         $userModel = new \app\admin\model\User();
191
         $adminModel = new \app\admin\model\Admin(); 
192
         $adminModel = new \app\admin\model\Admin(); 
192
         $param = $this->param;
193
         $param = $this->param;
193
-
194
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
194
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
195
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
195
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
196
         $userIds    = $whereArr['userIds'];
196
         $userIds    = $whereArr['userIds'];
203
         if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
203
         if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
204
         $time = getTimeArray($param['start_time'], $param['end_time']);
204
         $time = getTimeArray($param['start_time'], $param['end_time']);
205
         $sql = db('crm_business')->alias('business')->field([
205
         $sql = db('crm_business')->alias('business')->field([
206
-                    "FROM_UNIXTIME(business.create_time, '{$time['time_format']}')" => 'type',
207
-                    'COUNT(business.business_id)' => 'business_num',
208
-                    'SUM(
206
+            "FROM_UNIXTIME(business.create_time, '{$time['time_format']}')" => 'type',
207
+            'COUNT(business.business_id)' => 'business_num',
208
+            'COUNT(
209
                             CASE WHEN
209
                             CASE WHEN
210
-                                `check_status` = 2
211
-                            THEN 1 ELSE 0 END
210
+                                `is_end` = 1
211
+                            THEN 1 ELSE NULL END
212
                         )' => 'business_end'
212
                         )' => 'business_end'
213
-                ])->join('__CRM_CONTRACT__ contract', 'contract.business_id = business.business_id', 'left')
214
-                ->where([
215
-                    'business.owner_user_id' => ['IN', $userIds],
216
-                    'business.create_time' => ['BETWEEN', $time['between']]
217
-                ])
218
-                ->group('type')
219
-                ->fetchSql()
220
-                ->select();
213
+        ])->join('__CRM_CONTRACT__ contract', 'contract.business_id = business.business_id', 'left')
214
+            ->where([
215
+                'business.owner_user_id' => ['IN', $userIds],
216
+                'business.create_time' => ['BETWEEN', $time['between']]
217
+            ])
218
+            ->group('type')
219
+            ->fetchSql()
220
+            ->select();
221
         $res = queryCache($sql);
221
         $res = queryCache($sql);
222
         $res = array_column($res, null, 'type');
222
         $res = array_column($res, null, 'type');
223
         foreach ($time['list'] as $key =>$val) {
223
         foreach ($time['list'] as $key =>$val) {
246
         $businessModel = new \app\bi\model\Business();
246
         $businessModel = new \app\bi\model\Business();
247
         $crmBusinessModel = new \app\crm\model\Business();
247
         $crmBusinessModel = new \app\crm\model\Business();
248
         $userModel = new \app\admin\model\User();
248
         $userModel = new \app\admin\model\User();
249
+        $adminModel    = new \app\admin\model\Admin();
249
         $param = $this->param;
250
         $param = $this->param;
250
-
251
+        unset($param['types']);
251
         # 日期条件
252
         # 日期条件
252
-        if (!empty($param['date'])) {
253
-            $param['start_time'] = strtotime($param['date'] . '-01 00:00:00');
253
+        if (!empty($param['type'])) {
254
+            $param['start_time'] = strtotime($param['type'] . '-01 00:00:00');
254
             $endMonth = strtotime(date('Y-m-d', $param['start_time']) . " +1 month -1 day");
255
             $endMonth = strtotime(date('Y-m-d', $param['start_time']) . " +1 month -1 day");
255
-            $param['end_time'] = strtotime(date('Y-m-d 23:59:59', $endMonth)) ;
256
+            $param['end_time'] = strtotime(date('Y-m-d 23:59:59', $endMonth));
256
             unset($param['type']);
257
             unset($param['type']);
258
+        } else {
259
+            if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
260
+            if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
257
         }
261
         }
258
-
262
+    
259
         # 排序参数
263
         # 排序参数
260
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
264
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
261
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
265
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
262
-
266
+    
263
         # 赢单条件
267
         # 赢单条件
264
         $param['is_end'] = 1;
268
         $param['is_end'] = 1;
265
 
269
 
266
         $dataList = $businessModel->getDataList($param);
270
         $dataList = $businessModel->getDataList($param);
267
-        foreach ($dataList as $k => $v) {
271
+        foreach ($dataList['list'] as $k => $v) {
268
             $business_info = $crmBusinessModel->getDataById($v['business_id']);
272
             $business_info = $crmBusinessModel->getDataById($v['business_id']);
269
-            $dataList[$k]['business_name'] = $business_info['name'];
270
-            $dataList[$k]['create_time'] = date('Y-m-d',strtotime($business_info['create_time']));
271
-            $dataList[$k]['customer_id'] = $v['customer_id'];
273
+            $dataList['list'][$k]['business_name'] = $business_info['name'];
274
+            $dataList['list'][$k]['create_time'] = date('Y-m-d',strtotime($business_info['create_time']));
275
+            $dataList['list'][$k]['customer_id'] = $v['customer_id'];
272
             $customer = db('crm_customer')->field('name')->where('customer_id',$v['customer_id'])->find();
276
             $customer = db('crm_customer')->field('name')->where('customer_id',$v['customer_id'])->find();
273
-            $dataList[$k]['customer_name'] = $customer['name'];
277
+            $dataList['list'][$k]['customer_name'] = $customer['name'];
274
             $create_user_id_info = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
278
             $create_user_id_info = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
275
-            $dataList[$k]['create_user_name'] = $create_user_id_info['realname'];
279
+            $dataList['list'][$k]['create_user_name'] = $create_user_id_info['realname'];
276
             $owner_user_id_info = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
280
             $owner_user_id_info = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
277
-            $dataList[$k]['owner_user_name'] = $owner_user_id_info['realname'];
278
-            $dataList[$k]['business_stage'] = db('crm_business_status')->where('status_id',$v['status_id'])->value('name');//销售阶段
279
-            $dataList[$k]['business_type'] = db('crm_business_type')->where('type_id',$v['type_id'])->value('name');//商机状态组
281
+            $dataList['list'][$k]['owner_user_name'] = $owner_user_id_info['realname'];
282
+            if($v['is_end']!=0){
283
+                $dataList['list'][$k]['business_stage'] = db('crm_business_status')->where('status_id',$v['is_end'])->value('name');//销售阶段
284
+            }else{
285
+                $dataList['list'][$k]['business_stage'] = db('crm_business_status')->where('status_id',$v['status_id'])->value('name');//销售阶段
286
+            }
287
+            $dataList['list'][$k]['business_type'] = db('crm_business_type')->where('type_id',$v['type_id'])->value('name');//商机状态组
288
+        
280
         }
289
         }
281
-
290
+    
282
         # 排序
291
         # 排序
283
         if (!empty($dataList)) $dataList = $this->sortCommon($dataList, $sortField, $sortValue);
292
         if (!empty($dataList)) $dataList = $this->sortCommon($dataList, $sortField, $sortValue);
284
-
293
+    
285
         return resultArray(['data' => $dataList]);
294
         return resultArray(['data' => $dataList]);
286
     }
295
     }
287
 }
296
 }

+ 3
- 3
application/bi/controller/Contract.php Целия файл

64
         if ($param['excel_type'] != 1) {
64
         if ($param['excel_type'] != 1) {
65
             $param = $this->param;
65
             $param = $this->param;
66
         }
66
         }
67
-
68
         $perUserIds = $userModel->getUserByPer('bi', 'contract', 'read'); // 权限范围内userIds
67
         $perUserIds = $userModel->getUserByPer('bi', 'contract', 'read'); // 权限范围内userIds
69
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds);       // 统计条件
68
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds);       // 统计条件
70
         $userIds    = $whereArr['userIds'];
69
         $userIds    = $whereArr['userIds'];
140
         if($param['excel_type']!=1){
139
         if($param['excel_type']!=1){
141
             $param = $this->param;
140
             $param = $this->param;
142
         }
141
         }
143
-
142
+        
144
         $perUserIds = $userModel->getUserByPer('bi', 'contract', 'read'); //权限范围内userIds
143
         $perUserIds = $userModel->getUserByPer('bi', 'contract', 'read'); //权限范围内userIds
145
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
144
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
146
         $userIds    = $whereArr['userIds'];
145
         $userIds    = $whereArr['userIds'];
233
         if($param['excel_type']!=1){
232
         if($param['excel_type']!=1){
234
             $param = $this->param;
233
             $param = $this->param;
235
         }
234
         }
236
-
237
         $perUserIds = $userModel->getUserByPer('bi', 'contract', 'read'); //权限范围内userIds
235
         $perUserIds = $userModel->getUserByPer('bi', 'contract', 'read'); //权限范围内userIds
238
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
236
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
239
         $userIds    = $whereArr['userIds'];
237
         $userIds    = $whereArr['userIds'];
341
                 break;
339
                 break;
342
             case 'summary':
340
             case 'summary':
343
                 $list = $this->summary($excel_type);
341
                 $list = $this->summary($excel_type);
342
+                $list=$list['list'];
344
                 $type['type'] = '合同汇总表';
343
                 $type['type'] = '合同汇总表';
345
                 break;
344
                 break;
346
             case 'invoice':
345
             case 'invoice':
347
                 $list = $this->invoice($excel_type);
346
                 $list = $this->invoice($excel_type);
347
+                $list=$list['list'];
348
                 $type['type'] = '发票统计分析表';
348
                 $type['type'] = '发票统计分析表';
349
                 break;
349
                 break;
350
         }
350
         }

+ 95
- 48
application/bi/controller/Customer.php Целия файл

76
         if($param['excel_type']!=1){
76
         if($param['excel_type']!=1){
77
             $param = $this->param;
77
             $param = $this->param;
78
         }
78
         }
79
-
80
         # 排序参数
79
         # 排序参数
81
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
80
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
82
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
81
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
88
             $param['start_time'] = $timeArr[0];
87
             $param['start_time'] = $timeArr[0];
89
             $param['end_time'] = $timeArr[1];
88
             $param['end_time'] = $timeArr[1];
90
         } else {
89
         } else {
91
-            if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
92
-            if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
90
+            if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
91
+            if (!empty($param['end_time']))   $param['end_time']   =$param['end_time'] . ' 23:59:59';
93
         }
92
         }
94
-
93
+       
95
         $data = $customerModel->getStatistics($param);
94
         $data = $customerModel->getStatistics($param);
96
 
95
 
97
         # 排序
96
         # 排序
113
         $userModel = new \app\admin\model\User();
112
         $userModel = new \app\admin\model\User();
114
         $adminModel = new \app\admin\model\Admin();
113
         $adminModel = new \app\admin\model\Admin();
115
         $param = $this->param;
114
         $param = $this->param;
116
-
117
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
115
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
118
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
116
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
119
         $userIds    = $whereArr['userIds'];
117
         $userIds    = $whereArr['userIds'];
120
-
121
         # 处理无员工的情况
118
         # 处理无员工的情况
122
         if (empty($userIds)) return resultArray(['data' => []]);
119
         if (empty($userIds)) return resultArray(['data' => []]);
123
 
120
 
124
         if (empty($param['type']) && empty($param['start_time'])) {
121
         if (empty($param['type']) && empty($param['start_time'])) {
125
             $param['type'] = 'month';
122
             $param['type'] = 'month';
126
         }
123
         }
127
-
128
         if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
124
         if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
129
         if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
125
         if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
130
         $time = getTimeArray($param['start_time'], $param['end_time']);
126
         $time = getTimeArray($param['start_time'], $param['end_time']);
141
             $whereArr['end_time'] = $val['end_time'];
137
             $whereArr['end_time'] = $val['end_time'];
142
             $sql[] = $customerModel->getAddDealSql($whereArr);
138
             $sql[] = $customerModel->getAddDealSql($whereArr);
143
         }
139
         }
144
-
145
         $sql = implode(' UNION ALL ', $sql);
140
         $sql = implode(' UNION ALL ', $sql);
146
 
141
 
147
         $list = queryCache($sql);
142
         $list = queryCache($sql);
161
         $userModel = new \app\admin\model\User();
156
         $userModel = new \app\admin\model\User();
162
         $adminModel = new \app\admin\model\Admin();
157
         $adminModel = new \app\admin\model\Admin();
163
         $param = $this->param;
158
         $param = $this->param;
164
-
165
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
159
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
166
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
160
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
167
         $userIds    = $whereArr['userIds'];
161
         $userIds    = $whereArr['userIds'];
213
         if($param['excel_type']!=1){
207
         if($param['excel_type']!=1){
214
             $param = $this->param;
208
             $param = $this->param;
215
         }
209
         }
216
-
217
         # 排序参数
210
         # 排序参数
218
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
211
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
219
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
212
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
273
         # 排序
266
         # 排序
274
         if (!empty($result['list'])) $result['list'] = $this->sortCommon($result['list'], $sortField, $sortValue);
267
         if (!empty($result['list'])) $result['list'] = $this->sortCommon($result['list'], $sortField, $sortValue);
275
         //导出使用
268
         //导出使用
276
-        if (!empty($param['excel_type'])) return $recordData;
269
+        if (!empty($param['excel_type'])) {
270
+            return $result;
271
+        }
277
         return resultArray(['data' => $result]);
272
         return resultArray(['data' => $result]);
278
     }
273
     }
279
 
274
 
374
         # 排序
369
         # 排序
375
         if (!empty($result['list'])) $result['list'] = $this->sortCommon($result['list'], $sortField, $sortValue);
370
         if (!empty($result['list'])) $result['list'] = $this->sortCommon($result['list'], $sortField, $sortValue);
376
         //导出使用
371
         //导出使用
377
-        if (!empty($param['excel_type'])) return $result['list'];
372
+        if (!empty($param['excel_type'])) return $result;
378
         return resultArray(['data' => $result]);
373
         return resultArray(['data' => $result]);
379
     }
374
     }
380
 
375
 
391
         $userModel = new \app\admin\model\User();
386
         $userModel = new \app\admin\model\User();
392
         $adminModel = new \app\admin\model\Admin();
387
         $adminModel = new \app\admin\model\Admin();
393
         $param = $this->param;
388
         $param = $this->param;
394
-
395
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
389
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
396
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
390
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
397
         if (empty($whereArr['userIds'])) resultArray(['data' => []]);
391
         if (empty($whereArr['userIds'])) resultArray(['data' => []]);
492
         $userModel         = new \app\admin\model\User();
486
         $userModel         = new \app\admin\model\User();
493
         $adminModel        = new \app\admin\model\Admin();
487
         $adminModel        = new \app\admin\model\Admin();
494
         $param             = $this->param;
488
         $param             = $this->param;
495
-
496
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
489
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
497
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
490
         $whereArr   = $adminModel->getWhere($param, '', $perUserIds); //统计条件
498
         $userIds    = $whereArr['userIds'];
491
         $userIds    = $whereArr['userIds'];
542
     {
535
     {
543
         $userModel = new \app\admin\model\User();
536
         $userModel = new \app\admin\model\User();
544
         $actionRecordModel = new \app\bi\model\ActionRecord();
537
         $actionRecordModel = new \app\bi\model\ActionRecord();
538
+        $CustomerModel = new \app\crm\model\Customer();
545
         $adminModel = new \app\admin\model\Admin();
539
         $adminModel = new \app\admin\model\Admin();
546
-        if($param['excel_type']!=1){
540
+        if ($param['excel_type'] != 1) {
547
             $param = $this->param;
541
             $param = $this->param;
548
         }
542
         }
549
-
543
+        
550
         # 排序参数
544
         # 排序参数
551
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
545
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
552
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
546
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
553
         unset($param['sort_field']);
547
         unset($param['sort_field']);
554
         unset($param['sort_value']);
548
         unset($param['sort_value']);
555
-
549
+    
556
         if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
550
         if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
557
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
558
-
559
-        $perUserIds   = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
560
-        $whereArr     = $adminModel->getWhere($param, '', $perUserIds); //统计条件
561
-        $userIds      = $whereArr['userIds'];
551
+        if (!empty($param['end_time'])) $param['end_time'] = strtotime($param['end_time'] . ' 23:59:59');
552
+    
553
+        $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
554
+        $whereArr = $adminModel->getWhere($param, '', $perUserIds); //统计条件
555
+        $userIds = $whereArr['userIds'];
562
         $between_time = $whereArr['between_time'];
556
         $between_time = $whereArr['between_time'];
563
-
564
         $sql = CustomerModel::field([
557
         $sql = CustomerModel::field([
565
             'COUNT(*)' => 'customer_num',
558
             'COUNT(*)' => 'customer_num',
566
             'owner_user_id'
559
             'owner_user_id'
575
         $customer_num_list = queryCache($sql);
568
         $customer_num_list = queryCache($sql);
576
         $customer_num_list = array_column($customer_num_list, null, 'owner_user_id');
569
         $customer_num_list = array_column($customer_num_list, null, 'owner_user_id');
577
 
570
 
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');
597
+        }
578
         $sql = $actionRecordModel
598
         $sql = $actionRecordModel
579
             ->field([
599
             ->field([
580
                 'user_id',
600
                 'user_id',
592
             ->select();
612
             ->select();
593
         $action_record_list = queryCache($sql);
613
         $action_record_list = queryCache($sql);
594
         $action_record_list = array_column($action_record_list, null, 'user_id');
614
         $action_record_list = array_column($action_record_list, null, 'user_id');
595
-
615
+    
596
         $res = [];
616
         $res = [];
597
         $receiveCount = 0; # 领取公海客户总数
617
         $receiveCount = 0; # 领取公海客户总数
598
         $putInCount = 0; # 进入公海客户总数
618
         $putInCount = 0; # 进入公海客户总数
599
         foreach ($userIds as $val) {
619
         foreach ($userIds as $val) {
600
-            $item['put_in'] = !empty($action_record_list[$val]['put_in']) ? (int)$action_record_list[$val]['put_in'] : 0;
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'];
601
             $item['receive'] = !empty($action_record_list[$val]['receive']) ? (int)$action_record_list[$val]['receive'] : 0;
622
             $item['receive'] = !empty($action_record_list[$val]['receive']) ? (int)$action_record_list[$val]['receive'] : 0;
602
             $item['customer_num'] = !empty($customer_num_list[$val]['customer_num']) ? (int)$customer_num_list[$val]['customer_num'] : 0;
623
             $item['customer_num'] = !empty($customer_num_list[$val]['customer_num']) ? (int)$customer_num_list[$val]['customer_num'] : 0;
603
             $user_info = $userModel->getUserById($val);
624
             $user_info = $userModel->getUserById($val);
634
         if($param['excel_type']!=1){
655
         if($param['excel_type']!=1){
635
             $param = $this->param;
656
             $param = $this->param;
636
         }
657
         }
637
-
638
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
658
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
639
         $whereData  = $adminModel->getWhere($param, '', $perUserIds); //统计条件
659
         $whereData  = $adminModel->getWhere($param, '', $perUserIds); //统计条件
640
         $userIds    = $whereData['userIds'];
660
         $userIds    = $whereData['userIds'];
701
      * @throws \think\db\exception\ModelNotFoundException
721
      * @throws \think\db\exception\ModelNotFoundException
702
      * @throws \think\exception\DbException
722
      * @throws \think\exception\DbException
703
      */
723
      */
704
-    public function userCycleList()
724
+    public function userCycleList($param='')
705
     {
725
     {
706
         $userModel = new \app\admin\model\User();
726
         $userModel = new \app\admin\model\User();
707
         $adminModel = new \app\admin\model\Admin();
727
         $adminModel = new \app\admin\model\Admin();
708
-        $param = $this->param;
709
-
728
+        if($param['excel_type']!=1){
729
+            $param = $this->param;
730
+        }
710
         # 排序参数
731
         # 排序参数
711
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
732
         $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
712
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
733
         $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
787
         # 排序
808
         # 排序
788
         if (!empty($datas['users'])) $datas['users'] = $this->sortCommon($datas['users'], $sortField, $sortValue);
809
         if (!empty($datas['users'])) $datas['users'] = $this->sortCommon($datas['users'], $sortField, $sortValue);
789
         //导出使用
810
         //导出使用
790
-        if (!empty($param['excel_type'])) return $datas['list'];
811
+        if (!empty($param['excel_type'])) return $datas;
791
         return resultArray(['data' => $datas]);
812
         return resultArray(['data' => $datas]);
792
     }
813
     }
793
 
814
 
801
     {
822
     {
802
         $biCustomerModel = new \app\bi\model\Customer();
823
         $biCustomerModel = new \app\bi\model\Customer();
803
         $productModel = new \app\bi\model\Product();
824
         $productModel = new \app\bi\model\Product();
804
-        $param = $this->param;
825
+        if($param['excel_type']!=1){
826
+            $param = $this->param;
827
+        }
805
         $list = $productModel->getDealByProduct($param);
828
         $list = $productModel->getDealByProduct($param);
806
         $datas = array();
829
         $datas = array();
807
         $cycleCount    = 0;
830
         $cycleCount    = 0;
823
         }
846
         }
824
 
847
 
825
         $datas['total'] = ['product_name' => '总计', 'cycle' => $cycleCount, 'customer_num' => $customerCount];
848
         $datas['total'] = ['product_name' => '总计', 'cycle' => $cycleCount, 'customer_num' => $customerCount];
826
-
849
+        //导出使用
850
+        if (!empty($param['excel_type'])) return $datas;
827
         return resultArray(['data' => $datas]);
851
         return resultArray(['data' => $datas]);
828
     }
852
     }
829
 
853
 
833
      * @return
857
      * @return
834
      * @author zhi
858
      * @author zhi
835
      */
859
      */
836
-    public function addressCycle()
860
+    public function addressCycle($param='')
837
     {
861
     {
838
         $userModel = new \app\admin\model\User();
862
         $userModel = new \app\admin\model\User();
839
         $customerModel = new \app\crm\model\Customer();
863
         $customerModel = new \app\crm\model\Customer();
840
         $biCustomerModel = new \app\bi\model\Customer();
864
         $biCustomerModel = new \app\bi\model\Customer();
841
         $address_arr = \app\crm\model\Customer::$address;
865
         $address_arr = \app\crm\model\Customer::$address;
842
-        $param = $this->param;
866
+        if($param['excel_type']!=1){
867
+            $param = $this->param;
868
+        }
843
         if (empty($param['type']) && empty($param['start_time'])) {
869
         if (empty($param['type']) && empty($param['start_time'])) {
844
             $param['type'] = 'month';
870
             $param['type'] = 'month';
845
         }
871
         }
907
         }
933
         }
908
 
934
 
909
         $res['total'] = ['address' => '总计', 'cycle' => $cycleCount, 'customer_num' => $customerCount];
935
         $res['total'] = ['address' => '总计', 'cycle' => $cycleCount, 'customer_num' => $customerCount];
936
+        //导出使用
910
         
937
         
938
+        if (!empty($param['excel_type'])) return $res;
911
         return resultArray(['data' => $res]);
939
         return resultArray(['data' => $res]);
912
     }
940
     }
913
 
941
 
919
      * @throws \think\db\exception\ModelNotFoundException
947
      * @throws \think\db\exception\ModelNotFoundException
920
      * @throws \think\exception\DbException
948
      * @throws \think\exception\DbException
921
      */
949
      */
922
-    public function addressAnalyse()
950
+    public function addressAnalyse($param='')
923
     {
951
     {
924
-        $param = $this->param;
952
+        if($param['excel_type']!=1){
953
+            $param = $this->param;
954
+        }
925
         // $customerModel = new \app\crm\model\Customer();
955
         // $customerModel = new \app\crm\model\Customer();
926
         $userModel = new \app\admin\model\User();
956
         $userModel = new \app\admin\model\User();
927
         $address_arr = \app\crm\model\Customer::$address;
957
         $address_arr = \app\crm\model\Customer::$address;
936
 
966
 
937
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
967
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
938
         $userIds    = $map_user_ids ? array_intersect($map_user_ids, $perUserIds) : $perUserIds; //数组交集
968
         $userIds    = $map_user_ids ? array_intersect($map_user_ids, $perUserIds) : $perUserIds; //数组交集
939
-
969
+    
940
         if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
970
         if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
941
         if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
971
         if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
942
         $time = getTimeArray($param['start_time'], $param['end_time']);
972
         $time = getTimeArray($param['start_time'], $param['end_time']);
966
             $item['dealCustomer'] = !empty($list[$val]['dealCustomer']) ? (int)$list[$val]['dealCustomer'] : 0;
996
             $item['dealCustomer'] = !empty($list[$val]['dealCustomer']) ? (int)$list[$val]['dealCustomer'] : 0;
967
             $data[] = $item;
997
             $data[] = $item;
968
         }
998
         }
999
+        //导出使用
1000
+        if (!empty($param['excel_type'])) return $res;
969
         return resultArray(['data' => $data]);
1001
         return resultArray(['data' => $data]);
970
     }
1002
     }
971
 
1003
 
983
         $userModel       = new \app\admin\model\User();
1015
         $userModel       = new \app\admin\model\User();
984
         $adminModel      = new \app\admin\model\Admin();
1016
         $adminModel      = new \app\admin\model\Admin();
985
         $param           = $this->param;
1017
         $param           = $this->param;
986
-
987
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
1018
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
988
         $whereData = $adminModel->getWhere($param, '', $perUserIds); //统计条件
1019
         $whereData = $adminModel->getWhere($param, '', $perUserIds); //统计条件
989
         $userIds = $whereData['userIds'];
1020
         $userIds = $whereData['userIds'];
1099
      * @throws \think\db\exception\ModelNotFoundException
1130
      * @throws \think\db\exception\ModelNotFoundException
1100
      * @throws \think\exception\DbException
1131
      * @throws \think\exception\DbException
1101
      */
1132
      */
1102
-    public function customerSatisfaction(BiCustomerLogic $biCustomerLogic, $param='')
1133
+    public function customerSatisfaction($param='')
1103
     {
1134
     {
1135
+        $adminModel      = new \app\admin\model\Admin();
1136
+        $userModel = new \app\admin\model\User();
1104
         $param = $this->param;
1137
         $param = $this->param;
1105
-
1106
         $param['start_time'] = !empty($param['start_time']) ? strtotime($param['start_time']) : '';
1138
         $param['start_time'] = !empty($param['start_time']) ? strtotime($param['start_time']) : '';
1107
         $param['end_time']   = !empty($param['end_time'])   ? strtotime($param['end_time'])   : '';
1139
         $param['end_time']   = !empty($param['end_time'])   ? strtotime($param['end_time'])   : '';
1108
 
1140
 
1109
         if (!empty($param['type'])) {
1141
         if (!empty($param['type'])) {
1110
             # 日期工具类
1142
             # 日期工具类
1111
             $timeArr = getTimeByType($param['type']);
1143
             $timeArr = getTimeByType($param['type']);
1112
-            # 设置日期参数
1144
+            # 设置日期参数pool
1113
             $param['start_time'] = $timeArr[0];
1145
             $param['start_time'] = $timeArr[0];
1114
             $param['end_time']   = $timeArr[1];
1146
             $param['end_time']   = $timeArr[1];
1115
         }
1147
         }
1116
-
1148
+        $biCustomerLogic=new BiCustomerLogic();
1117
         $data = $biCustomerLogic->getCustomerSatisfaction($param);
1149
         $data = $biCustomerLogic->getCustomerSatisfaction($param);
1118
         //导出使用
1150
         //导出使用
1119
         if (!empty($param['excel_type'])) return $data;
1151
         if (!empty($param['excel_type'])) return $data;
1130
      * @throws \think\db\exception\ModelNotFoundException
1162
      * @throws \think\db\exception\ModelNotFoundException
1131
      * @throws \think\exception\DbException
1163
      * @throws \think\exception\DbException
1132
      */
1164
      */
1133
-    public function productSatisfaction(BiCustomerLogic $biCustomerLogic, $param='')
1165
+    public function productSatisfaction($param='')
1134
     {
1166
     {
1135
         $param = $this->param;
1167
         $param = $this->param;
1136
-
1168
+        $userInfo=$this->userInfo;
1137
         $param['start_time'] = !empty($param['start_time']) ? strtotime($param['start_time']) : '';
1169
         $param['start_time'] = !empty($param['start_time']) ? strtotime($param['start_time']) : '';
1138
         $param['end_time']   = !empty($param['end_time'])   ? strtotime($param['end_time'])   : '';
1170
         $param['end_time']   = !empty($param['end_time'])   ? strtotime($param['end_time'])   : '';
1139
-
1140
         if (!empty($param['type'])) {
1171
         if (!empty($param['type'])) {
1141
             # 日期工具类
1172
             # 日期工具类
1142
             $timeArr = getTimeByType($param['type']);
1173
             $timeArr = getTimeByType($param['type']);
1144
             $param['start_time'] = $timeArr[0];
1175
             $param['start_time'] = $timeArr[0];
1145
             $param['end_time'] = $timeArr[1];
1176
             $param['end_time'] = $timeArr[1];
1146
         }
1177
         }
1147
-
1178
+    
1179
+        $biCustomerLogic= new BiCustomerLogic();
1148
         $data = $biCustomerLogic->getProductSatisfaction($param);
1180
         $data = $biCustomerLogic->getProductSatisfaction($param);
1149
         //导出使用
1181
         //导出使用
1150
         if (!empty($param['excel_type'])) return $data;
1182
         if (!empty($param['excel_type'])) return $data;
1182
                 break;
1214
                 break;
1183
             case 'recordMode':
1215
             case 'recordMode':
1184
                 $list = $this->recordMode($param);
1216
                 $list = $this->recordMode($param);
1217
+                $list=$list['list'];
1185
                 $type['type'] = '客户跟进方式分析';
1218
                 $type['type'] = '客户跟进方式分析';
1186
                 break;
1219
                 break;
1187
             case 'poolList':
1220
             case 'poolList':
1195
                 break;
1228
                 break;
1196
             case 'customerSatisfaction':
1229
             case 'customerSatisfaction':
1197
                 $list = $this->customerSatisfaction($param);
1230
                 $list = $this->customerSatisfaction($param);
1198
-                $list=$list['list'];
1199
                 $type['type'] = '员工客户满意度分析';
1231
                 $type['type'] = '员工客户满意度分析';
1200
                 break;
1232
                 break;
1201
             case 'productSatisfaction':
1233
             case 'productSatisfaction':
1202
                 $list = $this->productSatisfaction($param);
1234
                 $list = $this->productSatisfaction($param);
1203
-                $list=$list['list'];
1204
                 $type['type'] = '产品满意度分析';
1235
                 $type['type'] = '产品满意度分析';
1205
                 break;
1236
                 break;
1237
+            case 'userCycleList':
1238
+                $list = $this->userCycleList($param);
1239
+                $list=$list['list'];
1240
+                $type['type'] = '成交周期';
1241
+                break;
1242
+            case 'productCycle':
1243
+                $list = $this->addressCycle($param);
1244
+               
1245
+                $list=$list['list'];
1246
+                $type['type'] = '地区成交周期';
1247
+                break;
1248
+            case 'addressCycle':
1249
+                $list = $this->productCycle($param);
1250
+                $list=$list['list'];
1251
+                $type['type'] = '地区成交周期';
1252
+                break;
1206
         }
1253
         }
1207
 
1254
 
1208
         if(empty($list)){
1255
         if(empty($list)){

+ 0
- 1
application/bi/controller/Log.php Целия файл

45
     public function statistics()
45
     public function statistics()
46
     {  
46
     {  
47
         $param  = $this->param;
47
         $param  = $this->param;
48
-
49
         if ($param['type']) {
48
         if ($param['type']) {
50
             $timeArr = getTimeByType($param['type']);
49
             $timeArr = getTimeByType($param['type']);
51
             $param['start_time'] = $timeArr[0];
50
             $param['start_time'] = $timeArr[0];

+ 10
- 12
application/bi/controller/Product.php Целия файл

54
         if($param['excel_type']!=1){
54
         if($param['excel_type']!=1){
55
             $param = $this->param;
55
             $param = $this->param;
56
         }
56
         }
57
-
58
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
59
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
57
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
58
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
60
 
59
 
61
         $list = $productModel->getStatistics($param);
60
         $list = $productModel->getStatistics($param);
62
 
61
 
78
     public function productCategory()
77
     public function productCategory()
79
     {
78
     {
80
         $param = $this->param;
79
         $param = $this->param;
81
-
82
         $productModel = new \app\bi\model\Product();
80
         $productModel = new \app\bi\model\Product();
83
 
81
 
84
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
85
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
82
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
83
+        if (!empty($param['end_time']))   $param['end_time']   =$param['end_time'] . ' 23:59:59';
86
 
84
 
87
         $list = $productModel->getStatistics($param);
85
         $list = $productModel->getStatistics($param);
88
 
86
 
105
         $subtotalCount = [];
103
         $subtotalCount = [];
106
         $sumCount = [];
104
         $sumCount = [];
107
         $item = [];
105
         $item = [];
108
-        $unm = 0;
109
-        $subtotal = 0;
110
         $res = [];
106
         $res = [];
111
-        foreach ($list as $val) {
107
+        foreach ($list as &$val) {
112
             $res[] = $val['product_id'];
108
             $res[] = $val['product_id'];
113
             $data[$val['product_id']][] = $val;
109
             $data[$val['product_id']][] = $val;
114
         }
110
         }
115
         $res = array_unique($res);
111
         $res = array_unique($res);
116
         foreach ($res as $e) {
112
         foreach ($res as $e) {
113
+            $unm = 0;
114
+            $subtotal = 0;
117
             foreach ($list as $v) {
115
             foreach ($list as $v) {
118
                 if ($e == $v['product_id']) {
116
                 if ($e == $v['product_id']) {
119
                     $unm += $v['num'];
117
                     $unm += $v['num'];
120
                     $subtotal += $v['subtotal'];
118
                     $subtotal += $v['subtotal'];
121
-                    $sumCount[$e] = $unm + $v['num'];
122
-                    $subtotalCount[$e] = (float)$subtotal + $v['subtotal'];
119
+                    $sumCount[$e] = $unm;
120
+                    $subtotalCount[$e] = (float)$subtotal;
123
                 }
121
                 }
124
             }
122
             }
125
             $item[$e][] = [
123
             $item[$e][] = [
126
                 'type' => '',
124
                 'type' => '',
127
                 'category_id_info' => '',
125
                 'category_id_info' => '',
128
                 'product_name' => '',
126
                 'product_name' => '',
129
-                'contract_name' => '',
127
+                'contract_num' => '',
130
                 'realname' => '',
128
                 'realname' => '',
131
                 'name' => '',
129
                 'name' => '',
132
                 'price' => '合计',
130
                 'price' => '合计',

+ 61
- 51
application/bi/controller/Ranking.php Целия файл

67
             $param = $this->param;
67
             $param = $this->param;
68
         }
68
         }
69
 
69
 
70
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
71
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
70
+        if (!empty($param['start_time'])) $param['start_time'] =$param['start_time'] . ' 00:00:00';
71
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
72
 
72
 
73
         $whereArr = $this->com($param, 'contract');
73
         $whereArr = $this->com($param, 'contract');
74
         $whereArr['check_status'] = 2;
74
         $whereArr['check_status'] = 2;
75
 
75
 
76
         //导出使用
76
         //导出使用
77
-        if (!empty($param['excel_type'])) return $this->handel(
78
-            new \app\bi\model\Contract,
79
-            $whereArr,
80
-            ['field' => 'SUM(`money`)', 'alias' => 'money', 'default' => '0.00'],
81
-            $param['excel_type']
82
-        );
77
+        if (!empty($param['excel_type']))  {
78
+            $data=$this->handel(
79
+                new \app\bi\model\Contract,
80
+                $whereArr,
81
+                ['field' => 'SUM(`money`)', 'alias' => 'money', 'default' => '0.00'],
82
+                $param['excel_type']
83
+            );
84
+                return $data;
85
+}
86
+        
87
+     
83
         return $this->handel(
88
         return $this->handel(
84
             new \app\bi\model\Contract,
89
             new \app\bi\model\Contract,
85
             $whereArr,
90
             $whereArr,
96
         if($param['excel_type']!=1){
101
         if($param['excel_type']!=1){
97
             $param = $this->param;
102
             $param = $this->param;
98
         }
103
         }
99
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
100
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
104
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
105
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
101
         $whereArr = $this->com($param, 'receivables');
106
         $whereArr = $this->com($param, 'receivables');
102
         $whereArr['check_status'] = 2;
107
         $whereArr['check_status'] = 2;
103
-
104
         //导出使用
108
         //导出使用
105
-        if (!empty($param['excel_type'])) return $this->handel(
106
-            new \app\bi\model\Receivables,
107
-            $whereArr,
108
-            ['field' => 'SUM(`money`)', 'alias' => 'money', 'default' => '0.00'],
109
-            $param['excel_type']
110
-        );
109
+        if (!empty($param['excel_type']))  {
110
+            $data=$this->handel(
111
+                new \app\bi\model\Receivables,
112
+                $whereArr,
113
+                ['field' => 'SUM(`money`)', 'alias' => 'money', 'default' => '0.00'],
114
+                $param['excel_type']
115
+            );
116
+            return $data;
117
+}
111
         return $this->handel(
118
         return $this->handel(
112
             new \app\bi\model\Receivables,
119
             new \app\bi\model\Receivables,
113
             $whereArr,
120
             $whereArr,
124
         if($param['excel_type']!=1){
131
         if($param['excel_type']!=1){
125
             $param = $this->param;
132
             $param = $this->param;
126
         }
133
         }
127
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
128
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
134
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
135
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
129
         $whereArr = $this->com($param, 'contract');
136
         $whereArr = $this->com($param, 'contract');
130
         $whereArr['check_status'] = 2;
137
         $whereArr['check_status'] = 2;
131
 
138
 
132
         //导出使用
139
         //导出使用
133
-        if (!empty($param['excel_type'])) $this->handel(
134
-            new ContractModel,
135
-            $whereArr,
136
-            ['field' => 'COUNT(*)', 'alias' => 'count', 'default' => 0],
137
-            $param['excel_type']
138
-        );
140
+        if (!empty($param['excel_type'])) {
141
+            $data= $this->handel(
142
+                new ContractModel,
143
+                $whereArr,
144
+                ['field' => 'COUNT(*)', 'alias' => 'count', 'default' => 0],
145
+                $param['excel_type']
146
+            );
147
+            return $data;
148
+}
149
+        
139
         return $this->handel(
150
         return $this->handel(
140
             new ContractModel,
151
             new ContractModel,
141
             $whereArr,
152
             $whereArr,
152
         if($param['excel_type']!=1){
163
         if($param['excel_type']!=1){
153
             $param = $this->param;
164
             $param = $this->param;
154
         }
165
         }
155
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
156
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
166
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
167
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
157
         $whereArr = $this->com($param, 'customer');
168
         $whereArr = $this->com($param, 'customer');
158
 
169
 
159
         $poolWhere = $this->getWhereByPool();
170
         $poolWhere = $this->getWhereByPool();
181
     public function addContacts()
192
     public function addContacts()
182
     {
193
     {
183
         $param = $this->param;
194
         $param = $this->param;
184
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
185
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
195
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
196
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
186
         $whereArr = $this->com($param, 'contacts');
197
         $whereArr = $this->com($param, 'contacts');
187
 
198
 
188
         //导出使用
199
         //导出使用
213
         if($param['excel_type']!=1){
224
         if($param['excel_type']!=1){
214
             $param = $this->param;
225
             $param = $this->param;
215
         }
226
         }
216
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
217
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
227
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
228
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
218
         $whereArr = $this->com($param, 'record');
229
         $whereArr = $this->com($param, 'record');
219
 
230
 
220
         # 权限内的员工列表
231
         # 权限内的员工列表
265
         if($param['excel_type']!=1){
276
         if($param['excel_type']!=1){
266
             $param = $this->param;
277
             $param = $this->param;
267
         }
278
         }
268
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
269
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
279
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
280
+        if (!empty($param['end_time']))   $param['end_time']   =$param['end_time'] . ' 23:59:59';
270
         $whereArr = $this->com($param, 'record');
281
         $whereArr = $this->com($param, 'record');
271
 
282
 
272
         # 权限内的员工列表
283
         # 权限内的员工列表
316
         if($param['excel_type']!=1){
327
         if($param['excel_type']!=1){
317
             $param = $this->param;
328
             $param = $this->param;
318
         }
329
         }
319
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
320
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
330
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
331
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
321
         $whereArr = $this->com($param, 'record');
332
         $whereArr = $this->com($param, 'record');
322
         $whereArr['category_id'] = 3; // 审批类型,3出差
333
         $whereArr['category_id'] = 3; // 审批类型,3出差
323
         $whereArr['check_status'] = 2;
334
         $whereArr['check_status'] = 2;
351
         if($param['excel_type']!=1){
362
         if($param['excel_type']!=1){
352
             $param = $this->param;
363
             $param = $this->param;
353
         }
364
         }
354
-        if (!empty($param['start_time'])) $param['start_time'] = strtotime($param['start_time'] . ' 00:00:00');
355
-        if (!empty($param['end_time']))   $param['end_time']   = strtotime($param['end_time'] . ' 23:59:59');
365
+        if (!empty($param['start_time'])) $param['start_time'] = $param['start_time'] . ' 00:00:00';
366
+        if (!empty($param['end_time']))   $param['end_time']   = $param['end_time'] . ' 23:59:59';
356
         $list = $productModel->getSortByProduct($param);
367
         $list = $productModel->getSortByProduct($param);
357
         $list = array_column($list, null, 'owner_user_id');
368
         $list = array_column($list, null, 'owner_user_id');
358
 
369
 
466
         switch ($param['excel_types']) {
477
         switch ($param['excel_types']) {
467
             case 'contract':
478
             case 'contract':
468
                 $list = $this->contract($param);
479
                 $list = $this->contract($param);
469
-
470
-                foreach ($list as $key => $v) {
471
-                    $list[$key]['id'] = $key + 1;
472
-                }
473
-                $type['type'] = '合同金额排行';
480
+                $param['type'] = '合同金额排行';
474
                 break;
481
                 break;
475
-            case'receivables':
482
+            case 'receivablesRanKingExport':
476
                 $list = $this->receivables($param);
483
                 $list = $this->receivables($param);
477
-                $type['type'] = '回款金额排行';
484
+                $param['type'] = '回款金额排行';
478
                 break;
485
                 break;
479
             case 'signing':
486
             case 'signing':
480
                 $list = $this->signing($param);
487
                 $list = $this->signing($param);
481
-                $type['type'] = '签约合同排行';
488
+                $param['type'] = '签约合同排行';
482
                 break;
489
                 break;
483
             case 'product':
490
             case 'product':
484
                 $list = $this->product($param);
491
                 $list = $this->product($param);
485
-                $type['type'] = '产品销量排行';
492
+                $param['type'] = '产品销量排行';
486
                 break;
493
                 break;
487
             case 'addCustomer':
494
             case 'addCustomer':
488
                 $list = $this->addCustomer($param);
495
                 $list = $this->addCustomer($param);
489
-                $type['type'] = '新增客户数排行';
496
+                $param['type'] = '新增客户数排行';
490
                 break;
497
                 break;
491
             case 'addContacts':
498
             case 'addContacts':
492
                 $list = $this->addContacts($param);
499
                 $list = $this->addContacts($param);
493
-                $type['type'] = '新增联系人数排行';
500
+                $param['type'] = '新增联系人数排行';
494
                 break;
501
                 break;
495
             case 'recordNun':
502
             case 'recordNun':
496
                 $list = $this->recordNun($param);
503
                 $list = $this->recordNun($param);
497
-                $type['type'] = '跟进次数排行';
504
+                $param['type'] = '跟进次数排行';
498
                 break;
505
                 break;
499
             case 'recordCustomer':
506
             case 'recordCustomer':
500
                 $list = $this->recordCustomer($param);
507
                 $list = $this->recordCustomer($param);
501
-                $type['type'] = '跟进客户数排行';
508
+                $param['type'] = '跟进客户数排行';
502
                 break;
509
                 break;
503
             case 'examine':
510
             case 'examine':
504
                 $list = $this->examine($param);
511
                 $list = $this->examine($param);
505
-                $type['type'] = '出差次数排行';
512
+                $param['type'] = '出差次数排行';
506
                 break;
513
                 break;
507
         }
514
         }
508
         if(empty($list)){
515
         if(empty($list)){
509
             return resultArray(['data'=>'数据不存在']);
516
             return resultArray(['data'=>'数据不存在']);
510
         }
517
         }
511
         $excelLogic = new ExcelLogic();
518
         $excelLogic = new ExcelLogic();
519
+        foreach ($list as $key => $v) {
520
+            $list[$key]['id'] = $key + 1;
521
+        }
512
         $data = $excelLogic->rankingExcle($param, $list);
522
         $data = $excelLogic->rankingExcle($param, $list);
513
         return $data;
523
         return $data;
514
     }
524
     }

+ 20
- 6
application/bi/logic/BiCustomerLogic.php Целия файл

29
         $result = [];
29
         $result = [];
30
 
30
 
31
         $userModel = new \app\admin\model\User();
31
         $userModel = new \app\admin\model\User();
32
-
32
+        $adminModel      = new \app\admin\model\Admin();
33
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); # 权限范围内userIds
33
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); # 权限范围内userIds
34
-        $userIds    = $perUserIds; # 数组交集
35
-        if (empty($userIds)) return [];
36
-
34
+        $whereData = $adminModel->getWhere($param, '', $perUserIds); //统计条件
35
+        $userIds = $whereData['userIds'];
36
+        if (empty($userIds)) {
37
+            # 普通员工没有查看权限,返回固定数据(根据员工筛选)
38
+            $result[] = [
39
+                'realname' => db('admin_user')->where('id', $param['user_id'])->value('realname'),
40
+                'visitContractNum' => 0,
41
+                '很满意' => 0,
42
+                '满意' => 0,
43
+                '一般' => 0,
44
+                '不满意' => 0,
45
+                '很不满意' => 0,
46
+            ];
47
+            return $result;
48
+        }
37
         # 员工信息
49
         # 员工信息
38
         $userList = db('admin_user')->field(['id', 'realname'])->whereIn('id', $userIds)->select();
50
         $userList = db('admin_user')->field(['id', 'realname'])->whereIn('id', $userIds)->select();
39
         foreach ($userList AS $key => $value) {
51
         foreach ($userList AS $key => $value) {
94
 
106
 
95
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); # 权限范围内userIds
107
         $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); # 权限范围内userIds
96
         $userIds    = !empty($param['user_id']) ? array_intersect([$param['user_id']], $perUserIds) : $perUserIds; # 数组交集
108
         $userIds    = !empty($param['user_id']) ? array_intersect([$param['user_id']], $perUserIds) : $perUserIds; # 数组交集
97
-        if (empty($userIds)) return [];
98
 
109
 
99
         # 产品列表(上架中)
110
         # 产品列表(上架中)
100
-        $productList = db('crm_product')->field(['product_id', 'name'])->where('status', '上架')->select();
111
+        $productList = db('crm_product')->field(['product_id', 'name'])->where( 'delete_user_id',0)->select();
101
         foreach ($productList AS $key => $value) {
112
         foreach ($productList AS $key => $value) {
102
             $productData[$value['product_id']] = [
113
             $productData[$value['product_id']] = [
103
                 'productName' => $value['name'],
114
                 'productName' => $value['name'],
110
             ];
121
             ];
111
         }
122
         }
112
 
123
 
124
+        # 普通员工没有查询权限,返回固定数据(根据员工筛选)
125
+        if (empty($userIds)) array_values($productData);
126
+
113
         # 回访条件
127
         # 回访条件
114
         $where['visit.owner_user_id'] = ['in', $userIds];
128
         $where['visit.owner_user_id'] = ['in', $userIds];
115
         $where['visit.create_time']   = ['between', [$param['start_time'], $param['end_time']]];
129
         $where['visit.create_time']   = ['between', [$param['start_time'], $param['end_time']]];

+ 53
- 32
application/bi/logic/ExcelLogic.php Целия файл

38
             case 'recordMode':
38
             case 'recordMode':
39
                 $file_name = 'customerRecordCategoryStats';
39
                 $file_name = 'customerRecordCategoryStats';
40
                 $field_list = [
40
                 $field_list = [
41
-                    '0' => ['name' => '员工姓名', 'field' => 'realname'],
42
-                    '1' => ['name' => '跟进次数', 'field' => 'record_num'],
43
-                    '2' => ['name' => '跟进客户数', 'field' => 'customer_num'],
41
+                    '0' => ['name' => '跟进方式', 'field' => 'category'],
42
+                    '1' => ['name' => '个数', 'field' => 'recordNum'],
43
+                    '2' => ['name' => '占比', 'field' => 'proportion'],
44
                 ];
44
                 ];
45
                 break;
45
                 break;
46
             case 'poolList':
46
             case 'poolList':
52
                     '3' => ['name' => '进入公海客户数', 'field' => 'put_in'],
52
                     '3' => ['name' => '进入公海客户数', 'field' => 'put_in'],
53
                 ];
53
                 ];
54
                 break;
54
                 break;
55
-            case 'userCycle':
55
+            case 'userCycleList':
56
                 $file_name = 'employeeCycleInfo';
56
                 $file_name = 'employeeCycleInfo';
57
                 $field_list = [
57
                 $field_list = [
58
                     '0' => ['name' => '员工姓名', 'field' => 'realname'],
58
                     '0' => ['name' => '员工姓名', 'field' => 'realname'],
60
                     '2' => ['name' => '成交客户数', 'field' => 'customer_num'],
60
                     '2' => ['name' => '成交客户数', 'field' => 'customer_num'],
61
                 ];
61
                 ];
62
                 break;
62
                 break;
63
+            case 'productCycle':
64
+                $file_name = 'addressCycleInfo';
65
+                $field_list = [
66
+                    '0' => ['name' => '地区', 'field' => 'address'],
67
+                    '1' => ['name' => '成交周期(天)', 'field' => 'cycle'],
68
+                    '2' => ['name' => '成交客户数', 'field' => 'customer_num'],
69
+                ];
70
+                break;
71
+            case 'addressCycle':
72
+                $file_name = 'productCycleInfo';
73
+                $field_list = [
74
+                    '0' => ['name' => '产品名称', 'field' => 'product_name'],
75
+                    '1' => ['name' => '成交周期(天)', 'field' => 'cycle'],
76
+                    '2' => ['name' => '成交客户数', 'field' => 'customer_num'],
77
+                ];
78
+                break;
63
             case 'customerSatisfaction':
79
             case 'customerSatisfaction':
64
                 $file_name = 'customerSatisfaction';
80
                 $file_name = 'customerSatisfaction';
65
                 $field_list = [
81
                 $field_list = [
66
                     '0' => ['name' => '员工姓名', 'field' => 'realname'],
82
                     '0' => ['name' => '员工姓名', 'field' => 'realname'],
67
-                    '1' => ['name' => '回访合同总数', 'field' => 'visit'],
68
-                    '2' => ['name' => '很满意', 'field' => 'satisfaction1'],
69
-                    '3' => ['name' => '满意', 'field' => 'satisfaction2'],
70
-                    '4' => ['name' => '一般', 'field' => 'satisfaction3'],
71
-                    '5' => ['name' => '不满意', 'field' => 'satisfaction4'],
72
-                    '6' => ['name' => '很不满意', 'field' => 'satisfaction5'],
83
+                    '1' => ['name' => '回访合同总数', 'field' => 'visitContractNum'],
84
+                    '2' => ['name' => '很满意', 'field' => '很满意'],
85
+                    '3' => ['name' => '满意', 'field' => '满意'],
86
+                    '4' => ['name' => '一般', 'field' => '一般'],
87
+                    '5' => ['name' => '不满意', 'field' => '不满意'],
88
+                    '6' => ['name' => '很不满意', 'field' => '很不满意'],
73
                 ];
89
                 ];
74
                 break;
90
                 break;
75
             case 'productSatisfaction':
91
             case 'productSatisfaction':
76
                 $file_name = 'productSatisfaction';
92
                 $file_name = 'productSatisfaction';
77
                 $field_list = [
93
                 $field_list = [
78
-                    '0' => ['name' => '员工姓名', 'field' => 'realname'],
79
-                    '1' => ['name' => '回访合同总数', 'field' => 'visit'],
80
-                    '2' => ['name' => '很满意', 'field' => 'satisfaction1'],
81
-                    '3' => ['name' => '满意', 'field' => 'satisfaction2'],
82
-                    '4' => ['name' => '一般', 'field' => 'satisfaction3'],
83
-                    '5' => ['name' => '不满意', 'field' => 'satisfaction4'],
84
-                    '6' => ['name' => '很不满意', 'field' => 'satisfaction5'],
94
+                    '0' => ['name' => '产品名称', 'field' => 'productName'],
95
+                    '1' => ['name' => '回访次数', 'field' => 'visitNum'],
96
+                    '2' => ['name' => '很满意', 'field' => '很满意'],
97
+                    '3' => ['name' => '满意', 'field' => '满意'],
98
+                    '4' => ['name' => '一般', 'field' => '一般'],
99
+                    '5' => ['name' => '不满意', 'field' => '不满意'],
100
+                    '6' => ['name' => '很不满意', 'field' => '很不满意'],
85
                 ];
101
                 ];
86
                 break;
102
                 break;
87
         }
103
         }
101
         if($type['excel_types']=='analysis'){
117
         if($type['excel_types']=='analysis'){
102
             $file_name = 'contractNumStats';
118
             $file_name = 'contractNumStats';
103
             $field_list = [];
119
             $field_list = [];
104
-            p($excelModel->template_download($file_name, $field_list, $type['type'], $param));
120
+            
105
             return $excelModel->template_download($file_name, $field_list, $type['type'], $param);
121
             return $excelModel->template_download($file_name, $field_list, $type['type'], $param);
106
         }elseif ($type['excel_types']=='summary'){
122
         }elseif ($type['excel_types']=='summary'){
107
             $file_name = 'totalContract';
123
             $file_name = 'totalContract';
111
                 '2' => ['name' => '签约合同金额(元)', 'field' => 'money'],
127
                 '2' => ['name' => '签约合同金额(元)', 'field' => 'money'],
112
                 '3' => ['name' => '回款金额(元)', 'field' => 'back'],
128
                 '3' => ['name' => '回款金额(元)', 'field' => 'back'],
113
             ];
129
             ];
114
-            return $excelModel->biExportExcel($file_name, $field_list, $type['type'], $param['items']);
130
+            return $excelModel->biExportExcel($file_name, $field_list, $type['type'], $param);
115
         }elseif ($type['excel_types']=='invoice'){
131
         }elseif ($type['excel_types']=='invoice'){
116
             $file_name = 'invoiceStats';
132
             $file_name = 'invoiceStats';
117
             $field_list = [
133
             $field_list = [
164
     {
180
     {
165
         $file_name = 'contractNumStats';
181
         $file_name = 'contractNumStats';
166
         $field_list = [
182
         $field_list = [
167
-            '0' => ['name' => '日期', 'field' => 'type'],
168
-            '1' => ['name' => '产品分类', 'field' => 'category_id_info'],
169
-            '2' => ['name' => '产品名称', 'field' => 'product_name'],
170
-            '3' => ['name' => '合同编号', 'field' => 'contract_name'],
171
-            '4' => ['name' => '负责人', 'field' => 'realname'],
172
-            '5' => ['name' => '客户名称', 'field' => 'name'],
173
-            '6' => ['name' => '销售单价', 'field' => 'price'],
174
-            '7' => ['name' => '数量', 'field' => 'num'],
175
-            '8' => ['name' => '订单产品小计', 'field' => 'subtotal'],
183
+            '0' => ['name' => '产品分类', 'field' => 'category_id_info'],
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'],
176
         ];
191
         ];
177
         $type = '产品销售情况统计';
192
         $type = '产品销售情况统计';
178
         $excelModel = new \app\admin\model\Excel();
193
         $excelModel = new \app\admin\model\Excel();
199
                     '3' => ['name' => '合同金额(元)', 'field' => 'money'],
214
                     '3' => ['name' => '合同金额(元)', 'field' => 'money'],
200
                 ];
215
                 ];
201
                 break;
216
                 break;
202
-            case 'receivables':
217
+            case 'receivablesRanKingExport':
203
                 $file_name = 'receivablesRanKing';
218
                 $file_name = 'receivablesRanKing';
204
                 $field_list = [
219
                 $field_list = [
205
                     '0' => ['name' => '公司总排名', 'field' => 'id'],
220
                     '0' => ['name' => '公司总排名', 'field' => 'id'],
281
      * @param $param
296
      * @param $param
282
      * @return mixed
297
      * @return mixed
283
      */
298
      */
284
-    public function achienementExcel($type, $param)
299
+    public function achienementExcel($param)
285
     {
300
     {
286
         $file_name = 'contractNumStats';
301
         $file_name = 'contractNumStats';
287
         $field_list = [
302
         $field_list = [
289
             '1' => ['name' => '月份', 'field' => 'month'],
304
             '1' => ['name' => '月份', 'field' => 'month'],
290
             '2' => ['name' => '目标', 'field' => 'achievement'],
305
             '2' => ['name' => '目标', 'field' => 'achievement'],
291
             '3' => ['name' => '完成', 'field' => 'money'],
306
             '3' => ['name' => '完成', 'field' => 'money'],
292
-            '4' => ['name' => 'rate', 'field' => 'realname'],
307
+            '4' => ['name' => '完成率', 'field' => 'rate'],
293
         ];
308
         ];
294
         $type = '业绩目标完成情况';
309
         $type = '业绩目标完成情况';
295
         $excelModel = new \app\admin\model\Excel();
310
         $excelModel = new \app\admin\model\Excel();
296
-        return $excelModel->biExportExcel($file_name, $field_list, $type, $param);
311
+        $item=[];
312
+        foreach ($param as $value) {
313
+            foreach ($value as $v) {
314
+                $item[] = $v;
315
+            }
316
+        }
317
+        return $excelModel->biExportExcel($file_name, $field_list, $type, $item);
297
     }
318
     }
298
 
319
 
299
 
320
 

+ 4
- 8
application/bi/model/Business.php Целия файл

67
         $perUserIds = $userModel->getUserByPer('bi', 'business', 'read'); //权限范围内userIds
67
         $perUserIds = $userModel->getUserByPer('bi', 'business', 'read'); //权限范围内userIds
68
         $whereData  = $adminModel->getWhere($param, '', $perUserIds); //统计条件
68
         $whereData  = $adminModel->getWhere($param, '', $perUserIds); //统计条件
69
         $userIds    = $whereData['userIds'];
69
         $userIds    = $whereData['userIds'];
70
-
71
-        if (!empty($whereData['between_time']['last_time'])) unset($whereData['between_time']['last_time']);
70
+        if (!empty($whereData['between_time'][0])) unset($whereData['between_time'][1]);
72
         $between_time = $whereData['between_time'];
71
         $between_time = $whereData['between_time'];
73
         $where['business.owner_user_id'] = array('in',$userIds);
72
         $where['business.owner_user_id'] = array('in',$userIds);
74
-        $where['business.create_time'] = ['between', $between_time];
75
-        $where['check_status'] = 2;
73
+        $where['business.create_time'] = ['between', [$param['start_time'],$param['end_time']]];
76
         if (!empty($param['is_end']) && $param['is_end'] == 1) $where['is_end'] = 1;
74
         if (!empty($param['is_end']) && $param['is_end'] == 1) $where['is_end'] = 1;
77
 
75
 
78
         $count = db('crm_business')->alias('business')
76
         $count = db('crm_business')->alias('business')
79
             ->join('__CRM_CONTRACT__ contract', 'contract.business_id = business.business_id', 'left')
77
             ->join('__CRM_CONTRACT__ contract', 'contract.business_id = business.business_id', 'left')
80
             ->where($where)->group('business.business_id')->count();
78
             ->where($where)->group('business.business_id')->count();
81
         $sql = db('crm_business')->alias('business')
79
         $sql = db('crm_business')->alias('business')
82
-            ->field('business.business_id,business.customer_id,business.money,business.type_id,business.status_id,business.deal_date,business.create_user_id,business.owner_user_id')
80
+            ->field('business.business_id,business.customer_id,business.money,business.type_id,business.status_id,business.deal_date,business.create_user_id,business.owner_user_id,business.is_end')
83
             ->join('__CRM_CONTRACT__ contract', 'contract.business_id = business.business_id', 'left')
81
             ->join('__CRM_CONTRACT__ contract', 'contract.business_id = business.business_id', 'left')
84
             ->where($where)
82
             ->where($where)
85
-            ->fetchSql()
86
             ->limit(($page - 1) * $limit, $limit)
83
             ->limit(($page - 1) * $limit, $limit)
87
             ->order(['money' => 'DESC'])
84
             ->order(['money' => 'DESC'])
88
             ->group('business.business_id')
85
             ->group('business.business_id')
89
             ->select();
86
             ->select();
90
-
91
-        return ['dataCount' => $count, 'list' => queryCache($sql)];
87
+        return ['dataCount' => $count, 'list' => $sql];
92
    }
88
    }
93
 }
89
 }

+ 2
- 3
application/bi/model/Examine.php Целия файл

59
         $userIds = $whereData['userIds'];        
59
         $userIds = $whereData['userIds'];        
60
 
60
 
61
         //时间
61
         //时间
62
-        $time_array = getTimeArray();
63
-
62
+       
64
         $category_list = db('oa_examine_category')
63
         $category_list = db('oa_examine_category')
65
             ->where(['status' => 1,'is_deleted' => ['neq',1]])
64
             ->where(['status' => 1,'is_deleted' => ['neq',1]])
66
             ->field('category_id,title')
65
             ->field('category_id,title')
75
         
74
         
76
         $sql = OaExamineModel::field($fields)
75
         $sql = OaExamineModel::field($fields)
77
             ->where([
76
             ->where([
78
-                'create_time' => ['BETWEEN', $time_array['between']],
77
+                'create_time' => ['BETWEEN', $whereData['between_time']],
79
                 'create_user_id' => ['IN', $userIds],
78
                 'create_user_id' => ['IN', $userIds],
80
                 'check_status' => ['neq', 4]
79
                 'check_status' => ['neq', 4]
81
             ])
80
             ])

+ 11
- 6
application/common.php Целия файл

166
                 if (!empty($v['end']))   $v['end']   = date('Y-m-d', $v['end']);
166
                 if (!empty($v['end']))   $v['end']   = date('Y-m-d', $v['end']);
167
             }
167
             }
168
             # 创建人、负责人、回访人(非自定义字段)
168
             # 创建人、负责人、回访人(非自定义字段)
169
-            if ($v['form_type'] == 'user' && in_array($k, ['create_user_id', 'owner_user_id'])) {
170
-                if ($v['condition'] == 'is') $v['condition'] = 'contains';
171
-            }
169
+//            if ($v['form_type'] == 'user' && in_array($k, ['create_user_id', 'owner_user_id'])) {
170
+//                if ($v['condition'] == 'is') $v['condition'] = 'contains';
171
+//            }
172
             # 自定义字段的user、structure类型
172
             # 自定义字段的user、structure类型
173
             if (($v['form_type'] == 'user' && !in_array($k, ['create_user_id', 'owner_user_id'])) || $v['form_type'] == 'structure') {
173
             if (($v['form_type'] == 'user' && !in_array($k, ['create_user_id', 'owner_user_id'])) || $v['form_type'] == 'structure') {
174
                 if ($v['condition'] == 'is') $v['condition'] = 'contains';
174
                 if ($v['condition'] == 'is') $v['condition'] = 'contains';
175
                 if ($v['condition'] == 'isNot') {
175
                 if ($v['condition'] == 'isNot') {
176
-                    return "(".$c.$k." not like '%".$v['value'][0]."%' OR ".$c.$k." is null)";
176
+                    return "(".$c.$k." not like ',%".$v['value'][0]."%,' OR ".$c.$k." is null)";
177
                 }
177
                 }
178
             }
178
             }
179
             # 处理多选字段的精确搜索
179
             # 处理多选字段的精确搜索
182
                 if ($v['condition'] == 'is' && count($v['value']) > 1) {
182
                 if ($v['condition'] == 'is' && count($v['value']) > 1) {
183
                     $checkboxLike = '';
183
                     $checkboxLike = '';
184
                     foreach ($v['value'] AS $kk => $vv) {
184
                     foreach ($v['value'] AS $kk => $vv) {
185
-                        $checkboxLike .= $c.$k." like "."'%".$vv."%' AND ";
185
+                        $checkboxLike .= $c.$k." like "."',%".$vv."%,' AND ";
186
                     }
186
                     }
187
                     return "(".$checkboxLike."LENGTH(".$c.$k.") = LENGTH('".arrayToString($v['value'])."'))";
187
                     return "(".$checkboxLike."LENGTH(".$c.$k.") = LENGTH('".arrayToString($v['value'])."'))";
188
                 }
188
                 }
779
 {
779
 {
780
     if (is_array($oldData) && is_array($newData) && $user_id) {
780
     if (is_array($oldData) && is_array($newData) && $user_id) {
781
         $differentData = array_diff_assoc($newData, $oldData);
781
         $differentData = array_diff_assoc($newData, $oldData);
782
-
783
         $fieldModel = new FieldModel();
782
         $fieldModel = new FieldModel();
784
         $userModel = new UserModel();
783
         $userModel = new UserModel();
785
         $structureModel = new \app\admin\model\Structure();
784
         $structureModel = new \app\admin\model\Structure();
791
         $unField = ['update_time','create_time']; //定义过滤字段
790
         $unField = ['update_time','create_time']; //定义过滤字段
792
         $message = [];
791
         $message = [];
793
         $un_form_type = ['file', 'form'];
792
         $un_form_type = ['file', 'form'];
793
+        
794
         foreach ($differentData as $k => $v) {
794
         foreach ($differentData as $k => $v) {
795
             if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
795
             if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
796
                 $field_name = '';
796
                 $field_name = '';
829
                 } elseif ($newFieldArr[$k]['form_type'] == 'visit') {
829
                 } elseif ($newFieldArr[$k]['form_type'] == 'visit') {
830
                     $new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
830
                     $new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
831
                     $old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
831
                     $old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
832
+                } elseif ($newFieldArr[$k]['form_type'] == 'single_user'){
833
+                    $new_value = $v ? db('admin_user')->where(['id' => $v])->value('realname') : '';
834
+                    $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) : '';
832
                 }
837
                 }
833
                 $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
838
                 $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
834
             }
839
             }

+ 4
- 3
application/common/behavior/AuthenticateBehavior.php Целия файл

6
 // +----------------------------------------------------------------------
6
 // +----------------------------------------------------------------------
7
 namespace app\common\behavior;
7
 namespace app\common\behavior;
8
 
8
 
9
+use think\Cache;
9
 use think\Request;
10
 use think\Request;
10
 use think\Db;
11
 use think\Db;
11
 
12
 
30
 		$permission = $params['permission']; //无限制
31
 		$permission = $params['permission']; //无限制
31
 		/*获取头部信息*/ 
32
 		/*获取头部信息*/ 
32
         $header = $request->header();
33
         $header = $request->header();
33
-        $authKey = $header['authkey'];
34
+        $authKey = trim($header['authkey']);
34
         
35
         
35
 		$paramArr = $request->param();
36
 		$paramArr = $request->param();
36
         $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求分类(mobile,ding)
37
         $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求分类(mobile,ding)
37
-        $cache = cache('Auth_'.$authKey.$platform); 
38
+        $cache = Cache::get('Auth_'.$authKey.$platform);
38
         $userInfo = $cache['userInfo'];
39
         $userInfo = $cache['userInfo'];
39
     	
40
     	
40
     	if (in_array($a, $permission)) {
41
     	if (in_array($a, $permission)) {
41
     		return true;
42
     		return true;
42
     	}   
43
     	}   
43
 
44
 
44
-    	if (empty($userInfo)) {
45
+    	if (empty($userInfo['id'])) {
45
 			header('Content-Type:application/json; charset=utf-8');
46
 			header('Content-Type:application/json; charset=utf-8');
46
             exit(json_encode(['code'=>101,'error'=>'请先登录']));
47
             exit(json_encode(['code'=>101,'error'=>'请先登录']));
47
     	}
48
     	}

+ 3
- 2
application/common/controller/Common.php Целия файл

7
 
7
 
8
 namespace app\common\controller;
8
 namespace app\common\controller;
9
 
9
 
10
+use think\Cache;
10
 use think\Controller;
11
 use think\Controller;
11
 use think\Request;
12
 use think\Request;
12
 
13
 
30
         $this->param = $param;   
31
         $this->param = $param;   
31
         $request = request();
32
         $request = request();
32
         $header = $request->header();
33
         $header = $request->header();
33
-        $authKey = $header['authkey'];
34
-        $cache = cache('Auth_'.$authKey.$platform);
34
+        $authKey = trim($header['authkey']);
35
+        $cache = Cache::get('Auth_'.$authKey.$platform);
35
         if ($cache) $this->userInfo = $cache['userInfo'];
36
         if ($cache) $this->userInfo = $cache['userInfo'];
36
 
37
 
37
         $m = strtolower($request->module());
38
         $m = strtolower($request->module());

+ 16
- 12
application/crm/controller/Achievement.php Целия файл

65
 	//员工业绩目标列表
65
 	//员工业绩目标列表
66
 	public function indexForuser(AchievementLogic $achievementLogic)
66
 	public function indexForuser(AchievementLogic $achievementLogic)
67
     {
67
     {
68
-//        $model = model('Achievement');
69
-//        $param = $this->param;
70
-//        $data = $model->getDataListForUser($param);
71
-//        return resultArray(['data' => $data]);
72
-        if (empty($this->param['year'])) return resultArray(['error' => '请选择年份!']);
73
-        if (empty($this->param['type'])) return resultArray(['error' => '请选择业绩类型']);
74
-        if (empty($this->param['structure_id']) && empty($this->param['user_id'])) {
75
-            return resultArray(['error' => '请选择部门或员工!']);
68
+        $model = model('Achievement');
69
+        $param = $this->param;
70
+        $data = $model->getDataListForUser($param);
71
+        # 剔除没有业绩目标的员工
72
+        foreach ($data AS $key => $value) {
73
+            if (empty((int)$value['yeartarget'])) unset($data[(int)$key]);
76
         }
74
         }
77
-
78
-        $data = $achievementLogic->getEmployeeList($this->param);
79
-
80
-        return resultArray(['data' => $data]);
75
+        return resultArray(['data' => array_values($data)]);
76
+//        if (empty($this->param['year'])) return resultArray(['error' => '请选择年份!']);
77
+//        if (empty($this->param['type'])) return resultArray(['error' => '请选择业绩类型']);
78
+//        if (empty($this->param['structure_id']) && empty($this->param['user_id'])) {
79
+//            return resultArray(['error' => '请选择部门或员工!']);
80
+//        }
81
+//
82
+//        $data = $achievementLogic->getEmployeeList($this->param);
83
+//
84
+//        return resultArray(['data' => $data]);
81
     }
85
     }
82
 
86
 
83
     /**
87
     /**

+ 32
- 12
application/crm/controller/Business.php Целия файл

8
 namespace app\crm\controller;
8
 namespace app\crm\controller;
9
 
9
 
10
 use app\admin\controller\ApiCommon;
10
 use app\admin\controller\ApiCommon;
11
+use app\crm\traits\SearchConditionTrait;
11
 use app\crm\traits\StarTrait;
12
 use app\crm\traits\StarTrait;
12
 use think\Hook;
13
 use think\Hook;
13
 use think\Request;
14
 use think\Request;
15
 
16
 
16
 class Business extends ApiCommon
17
 class Business extends ApiCommon
17
 {
18
 {
18
-    use StarTrait;
19
+    use StarTrait, SearchConditionTrait;
19
 
20
 
20
     /**
21
     /**
21
      * 用于判断权限
22
      * 用于判断权限
93
         $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
94
         $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
94
         $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');        
95
         $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');        
95
         if (!in_array($data['owner_user_id'],$auth_user_ids) && !$rwPre && !$roPre) {
96
         if (!in_array($data['owner_user_id'],$auth_user_ids) && !$rwPre && !$roPre) {
96
-            $authData['dataAuth'] = 0;
97
+            $authData['dataAuth'] = (int)0;
97
             return resultArray(['data' => $authData]);
98
             return resultArray(['data' => $authData]);
98
         }        
99
         }        
99
         //商机状态组
100
         //商机状态组
212
     public function statusList()
213
     public function statusList()
213
     {
214
     {
214
         $businessStatusModel = model('BusinessStatus');
215
         $businessStatusModel = model('BusinessStatus');
215
-        $key = 'BI_queryCache_StatusList_Data1';
216
+        $key = 'BI_queryCache_StatusList_Data';
216
         $list = cache($key);
217
         $list = cache($key);
217
         if (!$list) {
218
         if (!$list) {
218
             $userInfo = $this->userInfo;
219
             $userInfo = $this->userInfo;
225
             foreach ($list as $k=>$v) {
226
             foreach ($list as $k=>$v) {
226
                 $list[$k]['statusList'] = $businessStatusModel->getDataList($v['type_id']);
227
                 $list[$k]['statusList'] = $businessStatusModel->getDataList($v['type_id']);
227
             }
228
             }
228
-            cache($key, $list, true);
229
+            cache($key, $list, config('business_status_cache_time'));
229
         }
230
         }
230
 
231
 
231
         return resultArray(['data' => $list]);
232
         return resultArray(['data' => $list]);
415
                 'create_user_id'   => $businessInfo['owner_user_id'],
416
                 'create_user_id'   => $businessInfo['owner_user_id'],
416
                 'update_time'      => time(),
417
                 'update_time'      => time(),
417
                 'create_time'      => time(),
418
                 'create_time'      => time(),
418
-                'customer_ids'     => $businessInfo['customer_id']
419
+                'customer_ids'     => ',' . $businessInfo['customer_id'] . ','
419
             ]);
420
             ]);
420
 
421
 
421
 			//推进记录添加
422
 			//推进记录添加
426
             $temp['owner_user_id'] = $userInfo['id'];
427
             $temp['owner_user_id'] = $userInfo['id'];
427
 			$temp['remark'] = $param['remark'] ? : '';
428
 			$temp['remark'] = $param['remark'] ? : '';
428
 			Db::name('CrmBusinessLog')->insert($temp);
429
 			Db::name('CrmBusinessLog')->insert($temp);
429
-            return resultArray(['data' => '推进成功']);
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'],
438
+                'status_list' => $businessStatus
439
+            ];
440
+
441
+            return resultArray(['data' => $result]);
430
         }
442
         }
431
     }
443
     }
432
     
444
     
523
 
535
 
524
         $businessId = $this->param['business_id'];
536
         $businessId = $this->param['business_id'];
525
 
537
 
538
+        $userInfo = $this->userInfo;
539
+
540
+        # 查询联系人和商机关联数据
541
+        $contactsIds = Db::name('crm_contacts_business')->where('business_id', $businessId)->column('contacts_id');
542
+
526
         # 联系人
543
         # 联系人
527
-        $contactsCount = Db::name('crm_contacts_business')->alias('business')
528
-            ->join('__CRM_CONTACTS__ contacts', 'contacts.contacts_id = business.contacts_id')
529
-            ->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = contacts.customer_id')
530
-            ->where('business_id', $businessId)->count();
544
+        $contactsAuth = $this->getContactsSearchWhere($userInfo['id']);
545
+        $contactsCount = Db::name('crm_contacts')->whereIn('contacts_id', $contactsIds)->where($contactsAuth)->count();
531
 
546
 
532
         # 合同
547
         # 合同
533
-        $contractCount = Db::name('crm_contract')->where('business_id', $businessId)->count();
548
+        $contractAuth = $this->getContractSearchWhere($userInfo['id']);
549
+        $contractCount = Db::name('crm_contract')->where('business_id', $businessId)->where($contractAuth)->count();
550
+
551
+        # 查询商机和产品的关联表
552
+        $productIds = Db::name('crm_business_product')->where('business_id', $businessId)->column('product_id');
534
 
553
 
535
         # 产品
554
         # 产品
536
-        $productCount = Db::name('crm_business_product')->where('business_id', $businessId)->count();
555
+        $productAuth = $this->getProductSearchWhere();
556
+        $productCount = Db::name('crm_product')->whereIn('product_id', $productIds)->whereIn('owner_user_id', $productAuth)->count();
537
 
557
 
538
         # 附件
558
         # 附件
539
         $fileCount = Db::name('crm_business_file')->alias('business')->join('__ADMIN_FILE__ file', 'file.file_id = business.file_id', 'LEFT')->where('business_id', $businessId)->count();
559
         $fileCount = Db::name('crm_business_file')->alias('business')->join('__ADMIN_FILE__ file', 'file.file_id = business.file_id', 'LEFT')->where('business_id', $businessId)->count();

+ 16
- 8
application/crm/controller/Contacts.php Целия файл

8
 namespace app\crm\controller;
8
 namespace app\crm\controller;
9
 
9
 
10
 use app\admin\controller\ApiCommon;
10
 use app\admin\controller\ApiCommon;
11
+use app\crm\traits\SearchConditionTrait;
11
 use app\crm\traits\StarTrait;
12
 use app\crm\traits\StarTrait;
12
 use think\Hook;
13
 use think\Hook;
13
 use think\Request;
14
 use think\Request;
15
 
16
 
16
 class Contacts extends ApiCommon
17
 class Contacts extends ApiCommon
17
 {
18
 {
18
-    use StarTrait;
19
+    use StarTrait, SearchConditionTrait;
19
 
20
 
20
     /**
21
     /**
21
      * 用于判断权限
22
      * 用于判断权限
67
         $param['owner_user_id'] = $userInfo['id'];
68
         $param['owner_user_id'] = $userInfo['id'];
68
         
69
         
69
         if ($data = $contactsModel->createData($param)) {
70
         if ($data = $contactsModel->createData($param)) {
70
-            //关联 联系人与商机  客户添加与商机添加联系人可共用此接口
71
-            $business_id = $param['business_id']?$param['business_id']:0;
72
-            if($business_id != 0){
73
-                $data['cancel_or_relation'] = 1;// 1:关联 0取消
71
+            # 商机管理联系人
72
+            $business_id = $param['business_id'] ? $param['business_id'] : 0;
73
+            if (!empty($business_id)) {
74
                 $data['business_id'] = $business_id;
74
                 $data['business_id'] = $business_id;
75
-                if ($res =  Db::name('crm_contacts_business')->data($data)->insert()) {
75
+                if ($res = Db::name('crm_contacts_business')->data($data)->insert()) {
76
                     return resultArray(['data' => '添加成功']);
76
                     return resultArray(['data' => '添加成功']);
77
                 } else {
77
                 } else {
78
                     return resultArray(['error' => Db::name('crm_contacts_business')->getError()]);
78
                     return resultArray(['error' => Db::name('crm_contacts_business')->getError()]);
99
         //判断权限
99
         //判断权限
100
         $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'read');
100
         $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'read');
101
         if (!in_array($data['owner_user_id'],$auth_user_ids)) {
101
         if (!in_array($data['owner_user_id'],$auth_user_ids)) {
102
-            $authData['dataAuth'] = 0;
102
+            $authData['dataAuth'] = (int)0;
103
             return resultArray(['data' => $authData]);
103
             return resultArray(['data' => $authData]);
104
         }         
104
         }         
105
         if (!$data) {
105
         if (!$data) {
494
 
494
 
495
         $contactsId = $this->param['contacts_id'];
495
         $contactsId = $this->param['contacts_id'];
496
 
496
 
497
+        $userInfo = $this->userInfo;
498
+
499
+        # 查询联系人和商机的关联表
500
+        $businessIds = Db::name('crm_contacts_business')->where('contacts_id', $contactsId)->column('business_id');
501
+
502
+        # 商机权限条件
503
+        $businessAuth = $this->getBusinessSearchWhere($userInfo['id']);
504
+
497
         # 商机
505
         # 商机
498
-        $businessCount = Db::name('crm_business')->where('contacts_id', $contactsId)->count();
506
+        $businessCount = Db::name('crm_business')->whereIn('business_id', $businessIds)->where($businessAuth)->count();
499
 
507
 
500
         # 附件
508
         # 附件
501
         $fileCount = Db::name('crm_contacts_file')->alias('contacts')->join('__ADMIN_FILE__ file', 'file.file_id = contacts.file_id', 'LEFT')->where('contacts_id', $contactsId)->count();
509
         $fileCount = Db::name('crm_contacts_file')->alias('contacts')->join('__ADMIN_FILE__ file', 'file.file_id = contacts.file_id', 'LEFT')->where('contacts_id', $contactsId)->count();

+ 14
- 5
application/crm/controller/Contract.php Целия файл

12
 use app\admin\model\User;
12
 use app\admin\model\User;
13
 use app\crm\model\NumberSequence;
13
 use app\crm\model\NumberSequence;
14
 use app\crm\traits\AutoNumberTrait;
14
 use app\crm\traits\AutoNumberTrait;
15
+use app\crm\traits\SearchConditionTrait;
15
 use think\Db;
16
 use think\Db;
16
 use think\Hook;
17
 use think\Hook;
17
 use think\Request;
18
 use think\Request;
18
 
19
 
19
 class Contract extends ApiCommon
20
 class Contract extends ApiCommon
20
 {
21
 {
21
-    use AutoNumberTrait;
22
+    use AutoNumberTrait, SearchConditionTrait;
22
 
23
 
23
     /**
24
     /**
24
      * 用于判断权限
25
      * 用于判断权限
149
         $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
150
         $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
150
         $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');                
151
         $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');                
151
         if (!in_array($data['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
152
         if (!in_array($data['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
152
-            $authData['dataAuth'] = 0;
153
+            $authData['dataAuth'] = (int)0;
153
             return resultArray(['data' => $authData]);
154
             return resultArray(['data' => $authData]);
154
         }         
155
         }         
155
         if (!$data) {
156
         if (!$data) {
771
 
772
 
772
         $contractId = $this->param['contract_id'];
773
         $contractId = $this->param['contract_id'];
773
 
774
 
775
+        $userInfo = $this->userInfo;
776
+
774
         $contract = Db::name('crm_contract')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contract_id', $contractId)->find();
777
         $contract = Db::name('crm_contract')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contract_id', $contractId)->find();
775
 
778
 
776
         # 团队
779
         # 团队
779
         $contract['owner_user_id'] = [$contract['owner_user_id']];
782
         $contract['owner_user_id'] = [$contract['owner_user_id']];
780
         $teamCount = array_filter(array_unique(array_merge($contract['ro_user_id'], $contract['rw_user_id'], $contract['owner_user_id'])));
783
         $teamCount = array_filter(array_unique(array_merge($contract['ro_user_id'], $contract['rw_user_id'], $contract['owner_user_id'])));
781
 
784
 
785
+        # 查询合同和产品的关联数据
786
+        $productIds = Db::name('crm_contract_product')->where('contract_id', $contractId)->column('product_id');
787
+
782
         # 产品
788
         # 产品
783
-        $productCount = Db::name('crm_contract_product')->where('contract_id', $contractId)->count();
789
+        $productAuth = $this->getProductSearchWhere();
790
+        $productCount = Db::name('crm_product')->whereIn('product_id', $productIds)->whereIn('owner_user_id', $productAuth)->count();
784
 
791
 
785
         # 回款
792
         # 回款
786
-        $receivablesCount = Db::name('crm_receivables')->where('contract_id', $contractId)->count();
793
+        $receivablesAuth = $this->getReceivablesSearchWhere();
794
+        $receivablesCount = Db::name('crm_receivables')->where('contract_id', $contractId)->whereIn('owner_user_id', $receivablesAuth)->count();
787
 
795
 
788
         # 回访
796
         # 回访
789
-        $visitCount = Db::name('crm_visit')->where('contract_id', $contractId)->count();
797
+        $visitAuth = $this->getVisitSearchWhere($userInfo['id']);
798
+        $visitCount = Db::name('crm_visit')->where('contract_id', $contractId)->where($visitAuth)->count();
790
 
799
 
791
         # 附件
800
         # 附件
792
         $fileCount = Db::name('crm_contract_file')->alias('contract')->join('__ADMIN_FILE__ file', 'file.file_id = contract.file_id', 'LEFT')->where('contract_id', $contractId)->count();
801
         $fileCount = Db::name('crm_contract_file')->alias('contract')->join('__ADMIN_FILE__ file', 'file.file_id = contract.file_id', 'LEFT')->where('contract_id', $contractId)->count();

+ 272
- 252
application/crm/controller/Customer.php
Файловите разлики са ограничени, защото са твърде много
Целия файл


+ 34
- 42
application/crm/controller/Index.php Целия файл

128
             $end_time = $between_time[1];
128
             $end_time = $between_time[1];
129
         } else {
129
         } else {
130
             //自定义时间
130
             //自定义时间
131
-            $start_time = $param['start_time'] ?: strtotime(date('Y-01-01', time()));
132
-            $end_time = $param['end_time'] ? strtotime(date('Y-m-01', $param['end_time']) . ' +1 month -1 day') : strtotime(date('Y-m-01', time()) . ' +1 month -1 day');
131
+            $start_time = $param['start_time'] ?strtotime($param['start_time'].'00:00:00'): strtotime(date('Y-01-01', time()));
132
+            $end_time = $param['end_time'] ? strtotime($param['end_time'].'23:59:59') : strtotime(date('Y-m-01', time()) . ' +1 month -1 day');
133
             $between_time = array($start_time, $end_time);
133
             $between_time = array($start_time, $end_time);
134
         }
134
         }
135
 
135
 
214
         $param['user_id'] = $param['user_id'] ?: $userInfo['id'];;
214
         $param['user_id'] = $param['user_id'] ?: $userInfo['id'];;
215
         $businessModel = new \app\crm\model\Business();
215
         $businessModel = new \app\crm\model\Business();
216
         $param['merge'] = 1;
216
         $param['merge'] = 1;
217
-        if($param['dataType']==1){
218
-            $userIds[] = $param['user_id'];
219
-        }elseif($param['dataType']==2){
220
-            $param['perUserIds'] = getSubUserId(true,0,$param['user_id']);
221
-        }
222
-        if ($param['dataType'] == 3 || $param['dataType'] == 4) {
223
-            $param['structure_id'] = $userInfo['structure_id'];
217
+        if($param['start_time'] && $param['end_time']){
218
+            $param['start_time']=$param['start_time'].' 00:00:00';
219
+            $param['end_time']=$param['end_time'].' 23:59:59';
224
         }
220
         }
225
         $list = $businessModel->getFunnel($param);
221
         $list = $businessModel->getFunnel($param);
226
         return resultArray(['data' => $list]);
222
         return resultArray(['data' => $list]);
238
         //统计条件
234
         //统计条件
239
         $param = $this->param;
235
         $param = $this->param;
240
         $userInfo = $this->userInfo;
236
         $userInfo = $this->userInfo;
241
-        $userWhere['type']=3;
242
         $userWhere['status']=$param['label'];
237
         $userWhere['status']=$param['label'];
243
-        $userIds = [];
244
         if ($param['dataType'] == 3 || $param['dataType'] == 4) {
238
         if ($param['dataType'] == 3 || $param['dataType'] == 4) {
245
-            $param['structure_id'] = $userInfo['structure_id'];
246
             $userWhere['type']=2;
239
             $userWhere['type']=2;
240
+        }else{
241
+            $userWhere['type']=3;
242
+        }
243
+        if ($param['type']) {
244
+            $last_where_contract = getTimeByType($param['type']);
245
+            $userWhere['year']=date('Y',$last_where_contract[0]);
246
+            $time = getTimeArray();
247
+        } else {
248
+            //自定义时间
249
+            $param['start_time']=$param['start_time']?$param['start_time'].' 00:00:00':0;
250
+            $param['end_time']=$param['end_time'].' 23:59:59';
251
+            $time = getTimeArray(strtotime($param['start_time']),strtotime($param['end_time']));
247
         }
252
         }
248
         $whereArr = $adminModel->getWhere($param, 1, '');
253
         $whereArr = $adminModel->getWhere($param, 1, '');
249
         if($param['user_id']){
254
         if($param['user_id']){
251
         }elseif ($param['structure_id']){
256
         }elseif ($param['structure_id']){
252
             $userWhere['type']=2;
257
             $userWhere['type']=2;
253
         }
258
         }
254
-        $param['user_id'] = $param['user_id'] ?: $userInfo['id'];
255
-        if ($param['dataType'] == 1) {
256
-            $userIds[] = $param['user_id'];
257
-        } else {
258
-            $userIds = $whereArr['userIds'];
259
-        }
260
-        if (!isset($param['user_id'])) {
259
+        $userIds = $whereArr['userIds'];
260
+        if (!empty($param['user_id'])) {
261
             $userWhere['obj_id'] = $param['user_id'];
261
             $userWhere['obj_id'] = $param['user_id'];
262
         } else {
262
         } else {
263
             $userWhere['obj_id'] = ['in', $userIds];
263
             $userWhere['obj_id'] = ['in', $userIds];
264
         }
264
         }
265
-        if (!empty($param['type'])) {
266
-            $last_where_contract = getTimeByType($param['type']);
267
-            $userWhere['year']=date('Y',$last_where_contract[0]);
268
-        } else {
269
-            //自定义时间
270
-            $userWhere['year']=$param['start_time'] ?date('Y',$param['start_time']): strtotime(date('Y', time()));
271
-        }
272
         //时间
265
         //时间
273
-        $time = getTimeArray();
274
         $ax = 7;
266
         $ax = 7;
275
         if ($time['time_format'] == '%Y-%m-%d') {
267
         if ($time['time_format'] == '%Y-%m-%d') {
276
             $ax = 10;
268
             $ax = 10;
314
         }
306
         }
315
         $list = array();
307
         $list = array();
316
         $money = '0.00';
308
         $money = '0.00';
309
+        
317
         foreach ($time['list'] as $val) {
310
         foreach ($time['list'] as $val) {
318
             $item = [];
311
             $item = [];
319
             $item['type'] = $val['type'];
312
             $item['type'] = $val['type'];
322
 
315
 
323
             $achievement=Db::name('crm_achievement')->where($userWhere)->select();
316
             $achievement=Db::name('crm_achievement')->where($userWhere)->select();
324
             $data_time=date('m',strtotime($val['type']));
317
             $data_time=date('m',strtotime($val['type']));
318
+            $num='';
325
             foreach ($achievement as $val){
319
             foreach ($achievement as $val){
326
-                    $item['achievement']=$val[$this->monthName[$data_time]];
320
+                $num+=(int)$val[$this->monthName[$data_time]];
321
+                    $item['achievement']=$num;
327
             }
322
             }
328
             $list[] = $item;
323
             $list[] = $item;
329
         }
324
         }
342
     {
337
     {
343
         $param = $this->param;
338
         $param = $this->param;
344
         $adminModel = new \app\admin\model\Admin();
339
         $adminModel = new \app\admin\model\Admin();
340
+        if($param['start_time'] && $param['end_time']){
341
+            $param['start_time']=$param['start_time'].'00:00:00';
342
+            $param['end_time']=$param['end_time'].'23:59:59';
343
+        }
345
         $whereArr = $adminModel->getWhere($param, '', ''); //统计条件
344
         $whereArr = $adminModel->getWhere($param, '', ''); //统计条件
346
         $userIds = $whereArr['userIds'];
345
         $userIds = $whereArr['userIds'];
347
         $where = [];
346
         $where = [];
367
     {
366
     {
368
         $param = $this->param;
367
         $param = $this->param;
369
         $adminModel = new \app\admin\model\Admin();
368
         $adminModel = new \app\admin\model\Admin();
369
+        
370
         $whereArr = $adminModel->getWhere($param, '', ''); //统计条件
370
         $whereArr = $adminModel->getWhere($param, '', ''); //统计条件
371
         $userIds = $whereArr['userIds'];
371
         $userIds = $whereArr['userIds'];
372
         $where = [];
372
         $where = [];
537
         $types = $param['types'];
537
         $types = $param['types'];
538
         $userInfo = $this->userInfo;
538
         $userInfo = $this->userInfo;
539
         $user_id = $param['user_id'] ? : $userInfo['id'];
539
         $user_id = $param['user_id'] ? : $userInfo['id'];
540
-
540
+        if($param['start_time'] && $param['end_time']){
541
+            $param['start_time']=$param['start_time'].' 00:00:00';
542
+            $param['end_time']=$param['end_time'].' 23:59:59';
543
+        }
541
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
544
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
542
         $userIds = $whereArr['userIds'];
545
         $userIds = $whereArr['userIds'];
543
         $between_time = $whereArr['between_time'];        
546
         $between_time = $whereArr['between_time'];        
664
         // Db::query('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;');
667
         // Db::query('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;');
665
         $param = $this->param;
668
         $param = $this->param;
666
         $userInfo = $this->userInfo;
669
         $userInfo = $this->userInfo;
667
-        $param['user_id'] = $userInfo['id'];
670
+        $param['user_id'] = $param['user_id']?:$userInfo['id'];
668
         $indexModel = new IndexLogic;
671
         $indexModel = new IndexLogic;
669
         $data = $indexModel->ranking($param);
672
         $data = $indexModel->ranking($param);
670
         return resultArray(['data' => $data]);
673
         return resultArray(['data' => $data]);
678
     {
681
     {
679
         $param = $this->param;
682
         $param = $this->param;
680
         $userInfo = $this->userInfo;
683
         $userInfo = $this->userInfo;
681
-        $param['user_id'] = $userInfo['id'];
684
+        $param['user_id'] = $param['user_id']?:$userInfo['id'];
682
         $indexModel = new IndexLogic;
685
         $indexModel = new IndexLogic;
683
         $data = $indexModel->queryDataInfo($param);
686
         $data = $indexModel->queryDataInfo($param);
684
         return resultArray(['data' => $data]);
687
         return resultArray(['data' => $data]);
692
         $param = $this->param;
695
         $param = $this->param;
693
         $userInfo = $this->userInfo;
696
         $userInfo = $this->userInfo;
694
         $param['user_id'] = $param['user_id'] ?: $userInfo['id'];
697
         $param['user_id'] = $param['user_id'] ?: $userInfo['id'];
695
-
696
-        if ($param['dataType'] == 3 || $param['dataType'] == 4) {
697
-            $param['structure_id'] = $userInfo['structure_id'];
698
-        }
699
         $indexModel = new IndexLogic;
698
         $indexModel = new IndexLogic;
700
         $data = $indexModel->businessList($param);
699
         $data = $indexModel->businessList($param);
701
         return resultArray(['data' => $data]);
700
         return resultArray(['data' => $data]);
752
     public function activityList(){
751
     public function activityList(){
753
         $param = $this->param;
752
         $param = $this->param;
754
         $userInfo = $this->userInfo;
753
         $userInfo = $this->userInfo;
755
-        $param['user']=$param['user_id'];
756
         $param['id']=$userInfo['id'];
754
         $param['id']=$userInfo['id'];
757
-        if ($param['dataType'] == 1) {
758
-            $param['user_id']=$param['user_id']?:$userInfo['id'];
759
-        }
760
-        if ($param['dataType'] == 3 || $param['dataType'] == 4) {
761
-            $param['structure_id'] = $userInfo['structure_id'];
762
-        }
763
         $indexLogic=new IndexLogic();
755
         $indexLogic=new IndexLogic();
764
         $data=$indexLogic->activityList($param);
756
         $data=$indexLogic->activityList($param);
765
         return resultArray(['data'=>$data]);
757
         return resultArray(['data'=>$data]);

+ 42
- 6
application/crm/controller/Invoice.php Целия файл

100
             if (empty($numberInfo['number'])) return resultArray(['error' => '请填写发票编号!']);
100
             if (empty($numberInfo['number'])) return resultArray(['error' => '请填写发票编号!']);
101
             $param['invoice_apple_number'] = $numberInfo['number'];
101
             $param['invoice_apple_number'] = $numberInfo['number'];
102
         }
102
         }
103
-
104
         # 检查发票编号是否重复
103
         # 检查发票编号是否重复
105
         if ($invoiceLogic->getInvoiceId(['invoice_apple_number' => $param['invoice_apple_number']])) {
104
         if ($invoiceLogic->getInvoiceId(['invoice_apple_number' => $param['invoice_apple_number']])) {
106
             return resultArray(['error' => '发票编号重复!']);
105
             return resultArray(['error' => '发票编号重复!']);
142
         if (!$invoice_id = $invoiceLogic->save($param)) {
141
         if (!$invoice_id = $invoiceLogic->save($param)) {
143
             return resultArray(['error' => '创建失败!']);
142
             return resultArray(['error' => '创建失败!']);
144
         }
143
         }
145
-
144
+        $send_user_id = stringToArray($param['check_user_id']);
145
+        (new Message())->send(
146
+            Message::INVOICE_TO_DO,
147
+            [
148
+                'title'     => $param['invoice_apple_number'],
149
+                'action_id' => $invoice_id
150
+            ],
151
+            $send_user_id
152
+        );
146
         # 更新crm_number_sequence表中的last_date、create_time字段
153
         # 更新crm_number_sequence表中的last_date、create_time字段
147
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
154
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
148
         updateActionLog($param['create_user_id'], 'crm_invoice', $invoice_id, '', '', '创建了发票');
155
         updateActionLog($param['create_user_id'], 'crm_invoice', $invoice_id, '', '', '创建了发票');
156
+
157
+        # 创建待办事项的关联数据
158
+        $checkUserIds = db('crm_invoice')->where('invoice_id', $invoice_id)->value('check_user_id');
159
+        $checkUserIdArray = stringToArray($checkUserIds);
160
+        $dealtData = [];
161
+        foreach ($checkUserIdArray AS $kk => $vv) {
162
+            $dealtData[] = [
163
+                'types'    => 'crm_invoice',
164
+                'types_id' => $invoice_id,
165
+                'user_id'  => $vv
166
+            ];
167
+        }
168
+        if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
169
+
149
         return resultArray(['data' => '创建成功!']);
170
         return resultArray(['data' => '创建成功!']);
150
     }
171
     }
151
 
172
 
182
         }
203
         }
183
 
204
 
184
         if (!isSuperAdministrators($userInfo['id']) && $readStatus === false) {
205
         if (!isSuperAdministrators($userInfo['id']) && $readStatus === false) {
185
-            $authData['dataAuth'] = 0;
206
+            $authData['dataAuth'] = (int)0;
186
             return resultArray(['data' => $authData]);
207
             return resultArray(['data' => $authData]);
187
         }
208
         }
188
 
209
 
299
         # 更新crm_number_sequence表中的last_date、create_time字段
320
         # 更新crm_number_sequence表中的last_date、create_time字段
300
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
321
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
301
         //修改记录
322
         //修改记录
302
-        // updateActionLog($param['user_id'], 'crm_invoice', $param['invoice_id'], $dataInfo, $param);        
323
+        // updateActionLog($param['user_id'], 'crm_invoice', $param['invoice_id'], $dataInfo, $param);
324
+
325
+        # 删除待办事项的关联数据
326
+        db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'types_id' => ['eq', $param['invoice_id']]])->delete();
327
+        # 创建待办事项的关联数据
328
+        $checkUserIds = db('crm_invoice')->where('invoice_id', $param['invoice_id'])->value('check_user_id');
329
+        $checkUserIdArray = stringToArray($checkUserIds);
330
+        $dealtData = [];
331
+        foreach ($checkUserIdArray AS $kk => $vv) {
332
+            $dealtData[] = [
333
+                'types'    => 'crm_invoice',
334
+                'types_id' => $param['invoice_id'],
335
+                'user_id'  => $vv
336
+            ];
337
+        }
338
+        if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
303
 
339
 
304
         return resultArray(['data' => '编辑成功!']);
340
         return resultArray(['data' => '编辑成功!']);
305
     }
341
     }
490
                         'title'     => $dataInfo['invoice_apple_number'],
526
                         'title'     => $dataInfo['invoice_apple_number'],
491
                         'action_id' => $param['id']
527
                         'action_id' => $param['id']
492
                     ],
528
                     ],
493
-                    $dataInfo['owner_user_id']
529
+                    stringToArray($dataInfo['owner_user_id'])
494
                 );
530
                 );
495
             } else {
531
             } else {
496
                 if (!empty($status)) {
532
                 if (!empty($status)) {
512
                             'title'     => $dataInfo['invoice_apple_number'],
548
                             'title'     => $dataInfo['invoice_apple_number'],
513
                             'action_id' => $param['id']
549
                             'action_id' => $param['id']
514
                         ],
550
                         ],
515
-                        $dataInfo['owner_user_id']
551
+                        stringToArray($dataInfo['owner_user_id'])
516
                     );
552
                     );
517
                 }
553
                 }
518
             }
554
             }

+ 5
- 1
application/crm/controller/Leads.php Целия файл

107
         $auth_user_ids = $userModel->getUserByPer('crm', 'leads', 'read');
107
         $auth_user_ids = $userModel->getUserByPer('crm', 'leads', 'read');
108
         if (!in_array($data['owner_user_id'], $auth_user_ids)) {
108
         if (!in_array($data['owner_user_id'], $auth_user_ids)) {
109
             //无权限
109
             //无权限
110
-            $authData['dataAuth'] = 0;
110
+            $authData['dataAuth'] = (int)0;
111
             return resultArray(['data' => $authData]);
111
             return resultArray(['data' => $authData]);
112
         }
112
         }
113
         if (!$data) {
113
         if (!$data) {
312
                 $errorMessage[] = '"' . $leadsInfo['name'] . '"转移失败,错误原因:无权限;';
312
                 $errorMessage[] = '"' . $leadsInfo['name'] . '"转移失败,错误原因:无权限;';
313
                 continue;
313
                 continue;
314
             }
314
             }
315
+
316
+            # 处理分配标识,待办事项专用
317
+            $data['is_allocation'] = 1;
318
+
315
             $resLeads = db('crm_leads')->where(['leads_id' => $leads_id])->update($data);
319
             $resLeads = db('crm_leads')->where(['leads_id' => $leads_id])->update($data);
316
             if (!$resLeads) {
320
             if (!$resLeads) {
317
                 $errorMessage[] = '"' . $leadsInfo['name'] . '"转移失败,错误原因:数据出错;';
321
                 $errorMessage[] = '"' . $leadsInfo['name'] . '"转移失败,错误原因:数据出错;';

+ 119
- 62
application/crm/controller/Message.php Целия файл

180
             cache('remindReceivablesPlanCount'.$userInfo['id'], $data['remindReceivablesPlan']);
180
             cache('remindReceivablesPlanCount'.$userInfo['id'], $data['remindReceivablesPlan']);
181
             cache('remindReceivablesPlanTime'.$userInfo['id'], time() + 180);
181
             cache('remindReceivablesPlanTime'.$userInfo['id'], time() + 180);
182
         }
182
         }
183
-        # 待回访合同
184
-        $visitContractTime  = cache('visitContractTime'.$userInfo['id']);
185
-        $visitContractCount = cache('visitContractCount'.$userInfo['id']);
186
-        if (time() <= $visitContractTime) {
187
-            $data['returnVisitRemind'] = (int)$visitContractCount;
188
-        } else {
189
-            $visitContract = $this->visitContract(true);
190
-            $data['returnVisitRemind'] = $visitContract['dataCount'] ? : 0;
191
-            cache('visitContractCount'.$userInfo['id'], $data['returnVisitRemind']);
192
-            cache('visitContractTime'.$userInfo['id'], time() + 180);
183
+        if ($configData['visit_config'] == 1) {
184
+            # 待回访合同
185
+            $visitContractTime  = cache('visitContractTime'.$userInfo['id']);
186
+            $visitContractCount = cache('visitContractCount'.$userInfo['id']);
187
+            if (time() <= $visitContractTime) {
188
+                $data['returnVisitRemind'] = (int)$visitContractCount;
189
+            } else {
190
+                $visitContract = $this->visitContract(true);
191
+                $data['returnVisitRemind'] = $visitContract['dataCount'] ? : 0;
192
+                cache('visitContractCount'.$userInfo['id'], $data['returnVisitRemind']);
193
+                cache('visitContractTime'.$userInfo['id'], time() + 180);
194
+            }
193
         }
195
         }
194
         # 即将到期合同
196
         # 即将到期合同
195
         if ($configData['contract_config'] == 1) {
197
         if ($configData['contract_config'] == 1) {
249
         switch ($type) {
251
         switch ($type) {
250
             case '1' :
252
             case '1' :
251
                 $param['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
253
                 $param['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
254
+                $param['is_dealt'] = ['neq', 1];
252
                 break;
255
                 break;
253
             case '2' :
256
             case '2' :
254
                 $param['next_time'] = ['between', [1, time()]];
257
                 $param['next_time'] = ['between', [1, time()]];
258
+                $param['is_dealt'] = ['neq', 1];
255
                 break;
259
                 break;
256
             case '3' :
260
             case '3' :
257
                 $param['last_time'] = ['between', [$todayTime[0], $todayTime[1]]];
261
                 $param['last_time'] = ['between', [$todayTime[0], $todayTime[1]]];
258
-                $param['follow']    = ['eq', '已跟进'];
262
+                $param['is_dealt'] = ['eq', 1];
259
                 break;
263
                 break;
260
         }
264
         }
261
 
265
 
293
 
297
 
294
         switch ($type) {
298
         switch ($type) {
295
             case '1' : 
299
             case '1' : 
296
-                $param['next_time'] = ['between',array($todayTime[0],$todayTime[1])]; 
297
-                // $param['follow'] = ['neq','已跟进'];
300
+                $param['next_time'] = ['between',array($todayTime[0],$todayTime[1])];
301
+                $param['is_dealt'] = ['neq', 1];
298
                 break;
302
                 break;
299
             case '2' : 
303
             case '2' : 
300
-                $param['next_time'] = ['between',array(1,time())]; 
301
-                // $param['today_param'] = 'customer.next_time>record.update_time'; 
304
+                $param['next_time'] = ['between',array(1,time())];
305
+                $param['is_dealt'] = ['neq', 1];
302
                 break;
306
                 break;
303
             case '3' : 
307
             case '3' : 
304
                 $param['last_time'] = ['between',array($todayTime[0],$todayTime[1])];
308
                 $param['last_time'] = ['between',array($todayTime[0],$todayTime[1])];
305
-                $param['follow'] = ['eq','已跟进'];
309
+                $param['is_dealt'] = ['eq', 1];
306
                 break;
310
                 break;
307
         }
311
         }
308
         $data = $customerModel->getDataList($param);
312
         $data = $customerModel->getDataList($param);
343
         switch ($type) {
347
         switch ($type) {
344
             case '1' :
348
             case '1' :
345
                 $param['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
349
                 $param['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
350
+                $param['is_dealt'] = ['neq', 1];
346
                 break;
351
                 break;
347
             case '2' :
352
             case '2' :
348
                 $param['next_time'] = ['between', [1, time()]];
353
                 $param['next_time'] = ['between', [1, time()]];
354
+                $param['is_dealt'] = ['neq', 1];
349
                 break;
355
                 break;
350
             case '3' :
356
             case '3' :
351
                 $param['last_time'] = ['between', [$todayTime[0], $todayTime[1]]];
357
                 $param['last_time'] = ['between', [$todayTime[0], $todayTime[1]]];
358
+                $param['is_dealt'] = ['eq', 1];
352
                 break;
359
                 break;
353
         }
360
         }
354
 
361
 
361
     }
368
     }
362
 
369
 
363
     /**
370
     /**
364
-     * 待跟进线索
371
+     * 分配给我的线索
365
      * @author Michael_xu
372
      * @author Michael_xu
366
      * @return 
373
      * @return 
367
      */
374
      */
382
         $param['owner_user_id'] = $userInfo['id'];
389
         $param['owner_user_id'] = $userInfo['id'];
383
 
390
 
384
         switch ($type) {
391
         switch ($type) {
385
-            case '1' : $param['follow'] = ['neq','已跟进']; break;
386
-            case '2' : $param['follow'] = ['eq','已跟进']; break;
392
+            case '1' :
393
+                $param['follow'] = [['neq','已跟进'], null, 'or'];
394
+                $param['is_allocation'] = 1;
395
+                break;
396
+            case '2' :
397
+                $param['follow'] = ['eq','已跟进'];
398
+                $param['is_allocation'] = 1;
399
+                break;
387
         }
400
         }
388
         $param['user_id'] = $userInfo['id'];
401
         $param['user_id'] = $userInfo['id'];
389
         $data = $leadsModel->getDataList($param);
402
         $data = $leadsModel->getDataList($param);
394
     }        
407
     }        
395
 
408
 
396
     /**
409
     /**
397
-     * 待跟进客户
410
+     * 分配给我的客户
398
      * @author Michael_xu
411
      * @author Michael_xu
399
      * @return 
412
      * @return 
400
      */
413
      */
416
         $param['owner_user_id'] = $userInfo['id'];
429
         $param['owner_user_id'] = $userInfo['id'];
417
 
430
 
418
         switch ($type) {
431
         switch ($type) {
419
-            case '1' : $param['follow'] = ['eq','待跟进']; break;
420
-            case '2' : $param['follow'] = ['eq','已跟进']; break;
432
+            case '1' :
433
+                $param['follow'] = [['eq','待跟进'], null, 'or'];
434
+                $param['is_allocation'] = 1;
435
+                break;
436
+            case '2' :
437
+                $param['follow'] = ['eq','已跟进'];
438
+                $param['is_allocation'] = 1;
439
+                break;
421
         }
440
         }
422
         $data = $customerModel->getDataList($param);
441
         $data = $customerModel->getDataList($param);
423
         if ($types == 'list') {
442
         if ($types == 'list') {
450
         switch ($type) {
469
         switch ($type) {
451
             case '1' : 
470
             case '1' : 
452
                 $param['check_status'] = ['lt','2']; 
471
                 $param['check_status'] = ['lt','2']; 
453
-                $param['check_user_id'] = ['like','%,'.$userInfo['id'].',%'];
472
+                $param['check_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
473
+                # 要提醒的合同ID
474
+                $contractIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_contract'], 'user_id' => ['eq', $userInfo['id']]])->column('types_id');
475
+                $param['contractIdArray'] = !empty($contractIdArray) ? $contractIdArray : -1;
454
                 break;
476
                 break;
455
-            case '2' : 
456
-                // $param['check_status'] = ['egt','2']; 
457
-                $param['flow_user_id'] = ['like','%,'.$userInfo['id'].',%'];
477
+            case '2' :
478
+                $param['flow_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
458
                 break;
479
                 break;
459
         }
480
         }
460
         $param['user_id'] = $userInfo['id'];
481
         $param['user_id'] = $userInfo['id'];
461
         $data = $contractModel->getDataList($param);
482
         $data = $contractModel->getDataList($param);
483
+
462
         if ($types == 'list') {
484
         if ($types == 'list') {
463
             return resultArray(['data' => $data]);
485
             return resultArray(['data' => $data]);
464
         }
486
         }
487
             case '1' :
509
             case '1' :
488
                 # 待审核、审核中
510
                 # 待审核、审核中
489
                 $param['check_status'] = ['lt','2']; 
511
                 $param['check_status'] = ['lt','2']; 
490
-                $param['check_user_id'] = ['like','%,'.$userInfo['id'].',%'];
512
+                $param['check_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
513
+                # 要提醒的回款ID
514
+                $receivablesIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_receivables'], 'user_id' => ['eq', $userInfo['id']]])->column('types_id');
515
+                $param['receivablesIdArray'] = !empty($receivablesIdArray) ? $receivablesIdArray : -1;
491
                 break;
516
                 break;
492
             case '2' :
517
             case '2' :
493
                 # 全部
518
                 # 全部
494
-                $param['flow_user_id'] = ['like','%,'.$userInfo['id'].',%'];
519
+                $param['flow_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
495
                 break;
520
                 break;
496
         }
521
         }
497
         $param['user_id'] = $userInfo['id'];
522
         $param['user_id'] = $userInfo['id'];
527
             case '1' :
552
             case '1' :
528
                 # 待审核、审核中
553
                 # 待审核、审核中
529
                 $param['check_status']  = ['lt', 2];
554
                 $param['check_status']  = ['lt', 2];
530
-                $param['check_user_id'] = ['like', '%,'. $userId .',%'];
555
+                $param['check_user_id'] = ['like', ',%'. $userId .'%,'];
556
+                # 要提醒的发票ID
557
+                $invoiceIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'user_id' => ['eq', $userId]])->column('types_id');
558
+                $param['invoiceIdArray'] = !empty($invoiceIdArray) ? $invoiceIdArray : -1;
559
+                $param['dealt'] = 1;
531
                 break;
560
                 break;
532
             case '2' :
561
             case '2' :
533
                 # 全部
562
                 # 全部
534
-                $param['flow_user_id'] = ['like', '%,'. $userId .',%'];
563
+                $param['flow_user_id'] = ['like', ',%'. $userId .'%,'];
564
+                $param['dealt'] = 1;
535
                 break;
565
                 break;
536
         }
566
         }
537
 
567
 
566
             $param['owner_user_id'] = array('in',getSubUserId(false));
596
             $param['owner_user_id'] = array('in',getSubUserId(false));
567
         }       
597
         }       
568
         switch ($type) {
598
         switch ($type) {
569
-            case '1' : $param['receivables_id'] = 0; 
570
-                       $param['check_status'] = array('lt',2); 
571
-                       $param['remind_date'] = array('elt',date('Y-m-d',time())); 
572
-                       $param['return_date'] = array('egt',date('Y-m-d',time())); 
573
-                       $param['types'] = 1;
574
-                       break;
575
-            case '2' : $param['receivables_id'] = array('gt',0);
576
-                        $param['check_status'] = 2; 
577
-                        break;
578
-            case '3' : $param['receivables_id'] = 0;
579
-                        $param['remind_date'] = array('lt',date('Y-m-d',time())); 
580
-                        break;
599
+            case '1' :
600
+                $param['receivables_id'] = 0;
601
+                $param['check_status'] = array('lt',2);
602
+                $param['remind_date'] = array('elt',date('Y-m-d',time()));
603
+                $param['return_date'] = array('egt',date('Y-m-d',time()));
604
+                $param['types'] = 1;
605
+                $param['is_dealt'] = 0;
606
+                break;
607
+            case '2' :
608
+                $param['receivables_id'] = ['gt', 0];
609
+                $param['check_status'] = 2;
610
+                $param['dealt'] = 1;
611
+                break;
612
+            case '3' :
613
+                $param['receivables_id'] = 0;
614
+                $param['remind_date'] = array('lt',date('Y-m-d',time()));
615
+                break;
581
         }
616
         }
582
         $data = $receivablesPlanModel->getDataList($param);
617
         $data = $receivablesPlanModel->getDataList($param);
583
         if ($types == 'list') {
618
         if ($types == 'list') {
725
             $where['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId;
760
             $where['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId;
726
             # 下次联系时间
761
             # 下次联系时间
727
             $where['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
762
             $where['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
763
+            # 是否已处理(联系)
764
+            $where['is_dealt'] = 0;
728
 
765
 
729
             # 线索
766
             # 线索
730
             if ($type == 'todayLeads') {
767
             if ($type == 'todayLeads') {
731
                 $leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id');
768
                 $leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id');
732
                 Db::name('crm_leads')->whereIn('leads_id', $leadsId)->update([
769
                 Db::name('crm_leads')->whereIn('leads_id', $leadsId)->update([
733
-                    'next_time' => 0,
734
                     'last_time' => time(),
770
                     'last_time' => time(),
771
+                    'is_dealt'  => 1,
735
                     'follow'    => '已跟进'
772
                     'follow'    => '已跟进'
736
                 ]);
773
                 ]);
737
             }
774
             }
739
             if ($type == 'todayCustomer') {
776
             if ($type == 'todayCustomer') {
740
                 $customerId = !empty($typeId) ? $typeId : Db::name('crm_customer')->where($where)->column('customer_id');
777
                 $customerId = !empty($typeId) ? $typeId : Db::name('crm_customer')->where($where)->column('customer_id');
741
                 Db::name('crm_customer')->whereIn('customer_id', $customerId)->update([
778
                 Db::name('crm_customer')->whereIn('customer_id', $customerId)->update([
742
-                    'next_time' => 0,
743
                     'last_time' => time(),
779
                     'last_time' => time(),
780
+                    'is_dealt'  => 1,
744
                     'follow'    => '已跟进'
781
                     'follow'    => '已跟进'
745
                 ]);
782
                 ]);
746
             }
783
             }
748
             if ($type == 'todayBusiness') {
785
             if ($type == 'todayBusiness') {
749
                 $businessId = !empty($typeId) ? $typeId : Db::name('crm_business')->where($where)->column('business_id');
786
                 $businessId = !empty($typeId) ? $typeId : Db::name('crm_business')->where($where)->column('business_id');
750
                 Db::name('crm_business')->whereIn('business_id', $businessId)->update([
787
                 Db::name('crm_business')->whereIn('business_id', $businessId)->update([
751
-                    'next_time' => 0,
752
-                    'last_time' => time()
788
+                    'last_time' => time(),
789
+                    'is_dealt'  => 1
753
                 ]);
790
                 ]);
754
             }
791
             }
755
         }
792
         }
757
         # 处理分配给我的线索、客户
794
         # 处理分配给我的线索、客户
758
         if (in_array($type, ['followLeads', 'followCustomer'])) {
795
         if (in_array($type, ['followLeads', 'followCustomer'])) {
759
             $where['owner_user_id'] = $userId;
796
             $where['owner_user_id'] = $userId;
760
-            $where['follow']        = ['neq','已跟进'];
797
+            $where['follow']        = [['neq','已跟进'], null, 'or'];
798
+            $where['is_allocation'] = 1;
761
 
799
 
762
             # 线索
800
             # 线索
763
             if ($type == 'followLeads') {
801
             if ($type == 'followLeads') {
774
         # 处理待审核合同、回款、发票
812
         # 处理待审核合同、回款、发票
775
         if (in_array($type, ['checkContract', 'checkReceivables', 'checkInvoice'])) {
813
         if (in_array($type, ['checkContract', 'checkReceivables', 'checkInvoice'])) {
776
             $where['check_status']  = ['lt','2'];
814
             $where['check_status']  = ['lt','2'];
777
-            $where['check_user_id'] = ['like','%,' . $userId . ',%'];
778
-
779
-            $update = [
780
-                'check_status'  => 2,
781
-                'flow_id'       => 0,
782
-                'order_id'      => 0,
783
-                'check_user_id' => '',
784
-                'flow_user_id'  => ',' . $userId . ','
785
-            ];
815
+            $where['check_user_id'] = ['like',',%' . $userId . '%,'];
786
 
816
 
787
             # 合同
817
             # 合同
788
             if ($type == 'checkContract') {
818
             if ($type == 'checkContract') {
789
                 $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
819
                 $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
790
-                Db::name('crm_contract')->whereIn('contract_id', $contractId)->update($update);
820
+                db('crm_dealt_relation')->where('user_id', $userId)->where('types', 'crm_contract')->whereIn('types_id', $contractId)->delete();
791
             }
821
             }
792
             # 回款
822
             # 回款
793
             if ($type == 'checkReceivables') {
823
             if ($type == 'checkReceivables') {
794
                 $receivablesId = !empty($typeId) ? $typeId : Db::name('crm_receivables')->where($where)->column('receivables_id');
824
                 $receivablesId = !empty($typeId) ? $typeId : Db::name('crm_receivables')->where($where)->column('receivables_id');
795
-                Db::name('crm_receivables')->whereIn('receivables_id', $receivablesId)->update($update);
825
+                db('crm_dealt_relation')->where('user_id', $userId)->where('types', 'crm_receivables')->whereIn('types_id', $receivablesId)->delete();
796
             }
826
             }
797
             # 发票
827
             # 发票
798
             if ($type == 'checkInvoice') {
828
             if ($type == 'checkInvoice') {
799
                 $invoiceId = !empty($typeId) ? $typeId : Db::name('crm_invoice')->where($where)->column('invoice_id');
829
                 $invoiceId = !empty($typeId) ? $typeId : Db::name('crm_invoice')->where($where)->column('invoice_id');
800
-                Db::name('crm_invoice')->whereIn('invoice_id', $invoiceId)->update($update);
830
+                db('crm_dealt_relation')->where('user_id', $userId)->where('types', 'crm_invoice')->whereIn('types_id', $invoiceId)->delete();
801
             }
831
             }
832
+
802
         }
833
         }
803
 
834
 
804
         # 处理到期合同
835
         # 处理到期合同
831
                 Db::name('crm_customer')->whereIn('customer_id', $typeId)->update([
862
                 Db::name('crm_customer')->whereIn('customer_id', $typeId)->update([
832
                     'follow'      => '已跟进',
863
                     'follow'      => '已跟进',
833
                     'last_time'   => time(),
864
                     'last_time'   => time(),
834
-                    'update_time' => time()
865
+                    'deal_time'   => time(),
866
+                    'update_time' => time(),
835
                 ]);
867
                 ]);
836
             } else {
868
             } else {
837
                 $whereData['page']      = 1;
869
                 $whereData['page']      = 1;
838
-                $whereData['limit']     = 30;
870
+                $whereData['limit']     = 100;
839
                 $whereData['is_remind'] = db('crm_config')->where('name', 'remind_config')->value('value');;
871
                 $whereData['is_remind'] = db('crm_config')->where('name', 'remind_config')->value('value');;
840
                 $whereData['user_id']   = $userId;
872
                 $whereData['user_id']   = $userId;
841
                 $whereData['scene_id']  = db('admin_scene')->where(['types' => 'crm_customer','bydata' => empty($isSub) ? 'me' : 'sub'])->value('scene_id');
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;
842
                 $poolCustomers = (new \app\crm\model\Customer())->getDataList($whereData);
875
                 $poolCustomers = (new \app\crm\model\Customer())->getDataList($whereData);
843
                 $ids = [];
876
                 $ids = [];
844
                 foreach ($poolCustomers['list'] AS $key => $value) {
877
                 foreach ($poolCustomers['list'] AS $key => $value) {
847
                 if (!empty($ids)) Db::name('crm_customer')->whereIn('customer_id', $ids)->update([
880
                 if (!empty($ids)) Db::name('crm_customer')->whereIn('customer_id', $ids)->update([
848
                     'follow'      => '已跟进',
881
                     'follow'      => '已跟进',
849
                     'last_time'   => time(),
882
                     'last_time'   => time(),
850
-                    'update_time' => time()
883
+                    'deal_time'   => time(),
884
+                    'update_time' => time(),
851
                 ]);
885
                 ]);
852
             }
886
             }
853
         }
887
         }
854
 
888
 
889
+        # 带回款提醒
890
+        if ($type == 'remindReceivablesPlan') {
891
+            $planId = [];
892
+            if (!empty($typeId)) {
893
+                $planId = $typeId;
894
+            } else {
895
+                $param['owner_user_id']  = $isSub ? ['in',getSubUserId(false)] : $userId;
896
+                $param['receivables_id'] = 0;
897
+                $param['check_status']   = ['lt', 2];
898
+                $param['remind_date']    = ['elt', date('Y-m-d',time())];
899
+                $param['return_date']    = ['egt', date('Y-m-d',time())];
900
+                $param['types']          = 1;
901
+                $param['page']           = 1;
902
+                $param['limit']          = 1000;
903
+                $receivablesPlanModel    = model('ReceivablesPlan');
904
+                $data = $receivablesPlanModel->getDataList($param);
905
+                foreach ($data['list'] AS $key => $value) {
906
+                    $planId[] = $value['plan_id'];
907
+                }
908
+            }
909
+            if (!empty($planId)) db('crm_receivables_plan')->whereIn('plan_id', $planId)->update(['is_dealt' => 1]);
910
+        }
911
+
855
 
912
 
856
         return resultArray(['data' => '操作成功!']);
913
         return resultArray(['data' => '操作成功!']);
857
     }
914
     }

+ 1
- 1
application/crm/controller/Product.php Целия файл

99
         $auth_user_ids = $userModel->getUserByPer('crm', 'product', 'read');
99
         $auth_user_ids = $userModel->getUserByPer('crm', 'product', 'read');
100
         if (!in_array($data['owner_user_id'], $auth_user_ids)) {
100
         if (!in_array($data['owner_user_id'], $auth_user_ids)) {
101
             //无权限
101
             //无权限
102
-            $authData['dataAuth'] = 0;
102
+            $authData['dataAuth'] = (int)0;
103
             return resultArray(['data' => $authData]);
103
             return resultArray(['data' => $authData]);
104
         }        
104
         }        
105
         if (!$data) {
105
         if (!$data) {

+ 1
- 3
application/crm/controller/Receivables.php Целия файл

68
         $param['user_id'] = $userInfo['id'];
68
         $param['user_id'] = $userInfo['id'];
69
         if ($param['receivables_id']) {
69
         if ($param['receivables_id']) {
70
             $param['receivables_id'] = ['condition' => 'in', 'value' => $param['receivables_id'], 'form_type' => 'text', 'name' => ''];
70
             $param['receivables_id'] = ['condition' => 'in', 'value' => $param['receivables_id'], 'form_type' => 'text', 'name' => ''];
71
-            $param['is_excel'] = 1;
72
         }
71
         }
73
         $excelModel = new \app\admin\model\Excel();
72
         $excelModel = new \app\admin\model\Excel();
74
         // 导出的字段列表
73
         // 导出的字段列表
76
         $field_list = $fieldModel->getIndexFieldConfig('crm_receivables', $userInfo['id']);
75
         $field_list = $fieldModel->getIndexFieldConfig('crm_receivables', $userInfo['id']);
77
         // 文件名
76
         // 文件名
78
         $file_name = '5kcrm_receivables_' . date('Ymd');
77
         $file_name = '5kcrm_receivables_' . date('Ymd');
79
-        
80
         $model = model('Receivables');
78
         $model = model('Receivables');
81
         $temp_file = $param['temp_file'];
79
         $temp_file = $param['temp_file'];
82
         unset($param['temp_file']);
80
         unset($param['temp_file']);
181
         //判断权限
179
         //判断权限
182
         $auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'read');
180
         $auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'read');
183
         if (!in_array($data['owner_user_id'], $auth_user_ids)) {
181
         if (!in_array($data['owner_user_id'], $auth_user_ids)) {
184
-            $authData['dataAuth'] = 0;
182
+            $authData['dataAuth'] = (int)0;
185
             return resultArray(['data' => $authData]);
183
             return resultArray(['data' => $authData]);
186
         }
184
         }
187
         if (!$data) {
185
         if (!$data) {

+ 3
- 1
application/crm/controller/Visit.php Целия файл

70
         }
70
         }
71
         $param['owner_user_id'] = $param['owner_user_id'] ? : $userInfo['id'];
71
         $param['owner_user_id'] = $param['owner_user_id'] ? : $userInfo['id'];
72
         $param['create_user_id'] = $userInfo['id'];
72
         $param['create_user_id'] = $userInfo['id'];
73
+        $param['create_time'] = time();
73
         $param['update_time'] = time();
74
         $param['update_time'] = time();
74
         $res = $Visit->createData($param);
75
         $res = $Visit->createData($param);
75
         if ($res) {
76
         if ($res) {
98
         $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
99
         $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
99
         $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
100
         $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
100
         if (!in_array($data['owner_user_id'], $auth_user_ids) && !$rwPre && !$roPre) {
101
         if (!in_array($data['owner_user_id'], $auth_user_ids) && !$rwPre && !$roPre) {
101
-            $authData['dataAuth'] = 0;
102
+            $authData['dataAuth'] = (int)0;
102
             return resultArray(['data' => $authData]);
103
             return resultArray(['data' => $authData]);
103
         }
104
         }
104
         if (!$data) {
105
         if (!$data) {
129
         //判断权限
130
         //判断权限
130
         $data = $Visit->getDataById($param['id']);
131
         $data = $Visit->getDataById($param['id']);
131
         $auth_user_ids = $userModel->getUserByPer('crm', 'visit', 'update');
132
         $auth_user_ids = $userModel->getUserByPer('crm', 'visit', 'update');
133
+        $param['update_time'] = time();
132
         if ($Visit->updateDataById($param, $param['id'])) {
134
         if ($Visit->updateDataById($param, $param['id'])) {
133
             # 更新crm_number_sequence表中的last_date、create_time字段
135
             # 更新crm_number_sequence表中的last_date、create_time字段
134
             if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
136
             if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);

+ 46
- 89
application/crm/logic/ActivityLogic.php Целия файл

8
 
8
 
9
 namespace app\crm\logic;
9
 namespace app\crm\logic;
10
 
10
 
11
+use app\admin\model\Group;
11
 use app\crm\model\Activity;
12
 use app\crm\model\Activity;
12
 use think\Db;
13
 use think\Db;
13
 
14
 
86
                     $query->where('activity_type_id', $param['activity_type_id']);
87
                     $query->where('activity_type_id', $param['activity_type_id']);
87
                     $query->where('activity_type', $this->moduleToNumber[$param['module']]);
88
                     $query->where('activity_type', $this->moduleToNumber[$param['module']]);
88
                 });
89
                 });
89
-                $query->whereOr('customer_ids', 'like', '%'.$param['activity_type_id'].'%');
90
-                $query->whereOr('contacts_ids', 'like', '%'.$param['activity_type_id'].'%');
91
-                $query->whereOr('contract_ids', 'like', '%'.$param['activity_type_id'].'%');
92
-                $query->whereOr('business_ids', 'like', '%'.$param['activity_type_id'].'%');
93
-                $query->whereOr('leads_ids', 'like', '%'.$param['activity_type_id'].'%');
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'].'%,');
94
             })
95
             })
95
             ->order('update_time', 'desc')
96
             ->order('update_time', 'desc')
96
             ->group('update_time')
97
             ->group('update_time')
190
                         $query->where('activity_type_id', $param['activity_type_id']);
191
                         $query->where('activity_type_id', $param['activity_type_id']);
191
                     });
192
                     });
192
                     $query->whereOr(function ($query) use ($param) {
193
                     $query->whereOr(function ($query) use ($param) {
193
-                        $query->where('customer_ids', 'like', '%' . $param['activity_type_id'] . '%');
194
+                        $query->where('customer_ids', 'like', '%,' . $param['activity_type_id'] . ',%');
195
+                        $query->whereIn('activity_type', [8, 9, 11]);
194
                     });
196
                     });
195
                     if (!empty($contactsData)) {
197
                     if (!empty($contactsData)) {
196
                         $query->whereOr(function ($query) use ($contactsData) {
198
                         $query->whereOr(function ($query) use ($contactsData) {
220
 
222
 
221
                 break;
223
                 break;
222
             case 'contacts' :
224
             case 'contacts' :
223
-                $customerId = Db::name('crm_contacts')->where('contacts_id', $param['activity_type_id'])->value('customer_id');
224
-
225
-                $businessData    = [];
226
-                $contractData    = [];
227
-
228
-                # 商机ID串
229
-                $business = Db::name('crm_business')->field(['business_id'])->where('customer_id', $customerId)->select();
230
-                if (!empty($business)) {
231
-                    $businessData['activity_type']    = 5;
232
-                    $businessData['activity_type_id'] = array_reduce($business, function ($result, $value) {
233
-                        return array_merge($result, array_values($value));
234
-                    }, []);
235
-                }
236
-
237
-                # 合同ID串
238
-                $contract = Db::name('crm_contract')->field(['contract_id'])->where('contacts_id', $customerId)->select();
239
-                if (!empty($contract)) {
240
-                    $contractData['activity_type'] = 6;
241
-                    $contractData['activity_type_id'] = array_reduce($contract, function ($result, $value) {
242
-                        return array_merge($result, array_values($value));
243
-                    }, []);
244
-                }
245
-
246
-
247
                 # 联系人模块查询条件
225
                 # 联系人模块查询条件
248
-                $contactsWhere = function ($query) use ($param, $businessData, $contractData) {
226
+                $contactsWhere = function ($query) use ($param) {
249
                     $query->whereOr(function ($query) use ($param) {
227
                     $query->whereOr(function ($query) use ($param) {
250
                         $query->where('activity_type', 3);
228
                         $query->where('activity_type', 3);
251
                         $query->where('activity_type_id', $param['activity_type_id']);
229
                         $query->where('activity_type_id', $param['activity_type_id']);
252
                     });
230
                     });
253
                     $query->whereOr(function ($query) use ($param) {
231
                     $query->whereOr(function ($query) use ($param) {
254
-                        $query->where('contacts_ids', 'like', '%' . $param['activity_type_id'] . '%');
232
+                        $query->where('contacts_ids', 'like', '%,' . $param['activity_type_id'] . ',%');
233
+                        $query->whereIn('activity_type', [8, 9, 11]);
255
                     });
234
                     });
256
-                    if (!empty($businessData)) {
257
-                        $query->whereOr(function ($query) use ($businessData) {
258
-                            $query->where('activity_type', $businessData['activity_type']);
259
-                            $query->whereIn('activity_type_id', $businessData['activity_type_id']);
260
-                        });
261
-                    }
262
-                    if (!empty($contractData)) {
263
-                        $query->whereOr(function ($query) use ($contractData) {
264
-                            $query->where('activity_type', $contractData['activity_type']);
265
-                            $query->whereIn('activity_type_id', $contractData['activity_type_id']);
266
-                        });
267
-                    }
268
                 };
235
                 };
269
 
236
 
270
                 break;
237
                 break;
271
             case 'business' :
238
             case 'business' :
272
-                $contractData    = [];
273
-                # 合同ID串
274
-                $contract = Db::name('crm_contract')->field(['contract_id'])->where('business_id', $param['activity_type_id'])->select();
275
-                if (!empty($contract)) {
276
-                    $contractData['activity_type'] = 6;
277
-                    $contractData['activity_type_id'] = array_reduce($contract, function ($result, $value) {
278
-                        return array_merge($result, array_values($value));
279
-                    }, []);
280
-                }
281
-
282
                 # 商机模块查询条件
239
                 # 商机模块查询条件
283
-                $businessWhere = function ($query) use ($param, $contractData) {
240
+                $businessWhere = function ($query) use ($param) {
284
                     $query->whereOr(function ($query) use ($param) {
241
                     $query->whereOr(function ($query) use ($param) {
285
                         $query->where('activity_type', 5);
242
                         $query->where('activity_type', 5);
286
                         $query->where('activity_type_id', $param['activity_type_id']);
243
                         $query->where('activity_type_id', $param['activity_type_id']);
287
                     });
244
                     });
288
                     $query->whereOr(function ($query) use ($param) {
245
                     $query->whereOr(function ($query) use ($param) {
289
-                        $query->where('business_ids', 'like', '%' . $param['activity_type_id'] . '%');
290
-                        $query->where(['activity_type' => ['neq', 2]]);
246
+                        $query->where('business_ids', 'like', '%,' . $param['activity_type_id'] . ',%');
247
+                        $query->whereIn('activity_type', [8, 9, 11]);
291
                     });
248
                     });
292
-                    if (!empty($contractData)) {
293
-                        $query->whereOr(function ($query) use ($contractData) {
294
-                            $query->where('activity_type', $contractData['activity_type']);
295
-                            $query->whereIn('activity_type_id', $contractData['activity_type_id']);
296
-                        });
297
-                    }
298
                 };
249
                 };
299
-
300
                 break;
250
                 break;
301
             case 'contract' :
251
             case 'contract' :
302
-                $receivablesData = [];
303
-
304
-                # 回款ID串
305
-                $receivables = Db::name('crm_receivables')->field(['receivables_id'])->where('contract_id', $param['activity_type_id'])->select();
306
-                if (!empty($receivables)) {
307
-                    $receivablesData['activity_type'] = 7;
308
-                    $receivablesData['activity_type_id'] = array_reduce($receivables, function ($result, $value) {
309
-                        return array_merge($result, array_values($value));
310
-                    }, []);
311
-                }
312
-
313
                 # 合同模块查询条件
252
                 # 合同模块查询条件
314
-                $contractWhere = function ($query) use ($param, $receivables) {
253
+                $contractWhere = function ($query) use ($param) {
315
                     $query->whereOr(function ($query) use ($param) {
254
                     $query->whereOr(function ($query) use ($param) {
316
                         $query->where('activity_type', 6);
255
                         $query->where('activity_type', 6);
317
                         $query->where('activity_type_id', $param['activity_type_id']);
256
                         $query->where('activity_type_id', $param['activity_type_id']);
318
                     });
257
                     });
319
                     $query->whereOr(function ($query) use ($param) {
258
                     $query->whereOr(function ($query) use ($param) {
320
-                        $query->where('contract_ids', 'like', '%' . $param['activity_type_id'] . '%');
259
+                        $query->where('contract_ids', 'like', '%,' . $param['activity_type_id'] . ',%');
260
+                        $query->whereIn('activity_type', [8, 9, 11]);
321
                     });
261
                     });
322
-                    if (!empty($receivablesData)) {
323
-                        $query->whereOr(function ($query) use ($receivablesData) {
324
-                            $query->where('activity_type', $receivablesData['activity_type']);
325
-                            $query->whereIn('activity_type_id', $receivablesData['activity_type_id']);
326
-                        });
327
-                    }
328
                 };
262
                 };
329
 
263
 
330
                 break;
264
                 break;
355
             ->where('status', 1)
289
             ->where('status', 1)
356
             ->order('update_time', 'desc')
290
             ->order('update_time', 'desc')
357
             ->select();
291
             ->select();
358
-
292
+ 
359
         $fileModel = new \app\admin\model\File();
293
         $fileModel = new \app\admin\model\File();
360
         foreach ($dataArray AS $key => $value) {
294
         foreach ($dataArray AS $key => $value) {
361
             # 用户信息 todo 有模型文件,时间问题,暂时将查询写在循环中
295
             # 用户信息 todo 有模型文件,时间问题,暂时将查询写在循环中
388
             }
322
             }
389
 
323
 
390
             # 查询联系人信息
324
             # 查询联系人信息
391
-            $dataArray[$key]['contacts_name'] = '';
325
+            $dataArray[$key]['contacts_list'] = [];
392
             if ($dataArray[$key]['type'] == 1 && !empty($dataArray[$key]['contacts_ids'])) {
326
             if ($dataArray[$key]['type'] == 1 && !empty($dataArray[$key]['contacts_ids'])) {
393
-                $dataArray[$key]['contacts_name'] = Db::name('crm_contacts')->where('contacts_id', $dataArray[$key]['contacts_ids'])->value('name');
327
+                $res =  Db::name('crm_contacts')->where('contacts_id', trim($dataArray[$key]['contacts_ids'], ','))->value('name');
328
+                $dataArray[$key]['contacts_list'][] = [
329
+                    'contacts_id' => (int)trim($dataArray[$key]['contacts_ids'], ','),
330
+                    'name' =>empty($res)? null : $res,
331
+                ];
394
             }
332
             }
395
 
333
 
396
             # 时间格式处理
334
             # 时间格式处理
403
 
341
 
404
             # 客户模块跟进记录关联的商机
342
             # 客户模块跟进记录关联的商机
405
             $dataArray[$key]['business_list'] = $value['activity_type'] == 2 ? $this->getBusinessInfo($value['business_ids']) : [];
343
             $dataArray[$key]['business_list'] = $value['activity_type'] == 2 ? $this->getBusinessInfo($value['business_ids']) : [];
344
+
345
+            # 去掉客户模块跟进记录联系人ID两端的逗号
346
+            if ($value['type'] == 1 && $value['activity_type'] == 2) {
347
+                $dataArray[$key]['contacts_ids'] = !empty($value['contacts_ids']) ? trim($value['contacts_ids'], ',') : '';
348
+            }
406
         }
349
         }
407
 
350
 
408
         # 是否是最后一页
351
         # 是否是最后一页
470
 
413
 
471
         $param['create_user_id'] = $userId;
414
         $param['create_user_id'] = $userId;
472
         $param['type']           = 1;
415
         $param['type']           = 1;
473
-        $param['next_time']      = !empty($param['next_time'])    ? strtotime($param['next_time'])            : 0;
474
-        $param['business_ids']   = !empty($param['business_ids']) ? implode(',', $param['business_ids']) : '';
416
+        $param['next_time']      = !empty($param['next_time'])    ? strtotime($param['next_time'])        : 0;
417
+        $param['business_ids']   = !empty($param['business_ids']) ? arrayToString($param['business_ids']) : '';
475
         $param['create_time']    = time();
418
         $param['create_time']    = time();
476
         $param['update_time']    = time();
419
         $param['update_time']    = time();
420
+        if (!empty($param['contacts_ids'])) $param['contacts_ids'] = ',' . $param['contacts_ids'] . ',';
477
 
421
 
478
         $activityJson = Activity::create($param);
422
         $activityJson = Activity::create($param);
479
         if (empty($activityJson)) return false;
423
         if (empty($activityJson)) return false;
531
 
475
 
532
         $param['type']         = 1;
476
         $param['type']         = 1;
533
         $param['next_time']    = strtotime($param['next_time']);
477
         $param['next_time']    = strtotime($param['next_time']);
534
-        $param['business_ids'] = !empty($param['business_ids']) ? implode(',', $param['business_ids']) : '';
478
+        $param['business_ids'] = !empty($param['business_ids']) ? arrayToString($param['business_ids']) : '';
535
         $param['update_time']  = time();
479
         $param['update_time']  = time();
536
 
480
 
537
         if (!Activity::update($param)) return false;
481
         if (!Activity::update($param)) return false;
585
         $activityInfo = Db::name('crm_activity')->where(['activity_id' => $activityId])->find();
529
         $activityInfo = Db::name('crm_activity')->where(['activity_id' => $activityId])->find();
586
         if (Activity::update(['activity_id' => $activityId, 'status' => 0])) {
530
         if (Activity::update(['activity_id' => $activityId, 'status' => 0])) {
587
             $this->updateNextTime($this->activityType[$activityInfo['activity_type']]['en'], $activityInfo['activity_type_id'], '', true);
531
             $this->updateNextTime($this->activityType[$activityInfo['activity_type']]['en'], $activityInfo['activity_type_id'], '', true);
532
+            # 删除附件
533
+            $fileIds = db('crm_activity_file')->where('activity_id', $activityId)->column('file_id');
534
+            if (!empty($fileIds)) {
535
+                db('crm_activity_file')->where('activity_id', $activityId)->delete();
536
+                db('admin_file')->whereIn('file_id', $fileIds)->delete();
537
+            }
538
+            if ($activityInfo['activity_type'] == 3) db('crm_contacts_file')->whereIn('file_id', $fileIds)->delete();
539
+            if ($activityInfo['activity_type'] == 5) db('crm_business_file')->whereIn('file_id', $fileIds)->delete();
540
+            if ($activityInfo['activity_type'] == 6) db('crm_contract_file')->whereIn('file_id', $fileIds)->delete();
588
             return true;
541
             return true;
589
         } else {
542
         } else {
590
             return false;
543
             return false;
635
         if (!$is_del && in_array($types, ['crm_customer', 'crm_leads'])) {
588
         if (!$is_del && in_array($types, ['crm_customer', 'crm_leads'])) {
636
             $data['follow'] = '已跟进';
589
             $data['follow'] = '已跟进';
637
         }
590
         }
591
+        # 设置今日需联系线索、客户、商机
592
+        if (!$is_del && in_array($types, ['crm_customer', 'crm_leads', 'crm_business'])) {
593
+            if (!empty($next_time) && $next_time >= strtotime('Y-m-d 00:00:00')) $data['is_dealt'] = 0;
594
+        }
638
         $dbName->where([$dbId => $types_id])->update($data);
595
         $dbName->where([$dbId => $types_id])->update($data);
639
         return true;
596
         return true;
640
     }
597
     }

+ 8
- 28
application/crm/logic/CommonLogic.php Целия файл

193
         
193
         
194
         # 编辑参数
194
         # 编辑参数
195
         $data = [];
195
         $data = [];
196
-        $item=[];
197
         if (!empty($param['list'])) {
196
         if (!empty($param['list'])) {
198
             foreach ($param['list'] as $key => $value) {
197
             foreach ($param['list'] as $key => $value) {
199
                 foreach ($value as $k => $v) {
198
                 foreach ($value as $k => $v) {
204
                         # 处理产品类别
203
                         # 处理产品类别
205
                         $categorys = explode(',', $v);
204
                         $categorys = explode(',', $v);
206
                         $data[$k] = $categorys[count($categorys) - 1];
205
                         $data[$k] = $categorys[count($categorys) - 1];
207
-                    } elseif (in_array($k, $fileField)) {
208
-                        # 处理附件类型数据
209
-                        $fileArray = [];
210
-                        foreach ($v AS $kk => $vv) {
211
-                            if (!empty($vv['file_id'])) $fileArray[] = $vv['file_id'];
212
-                        }
213
-                        if (!empty($fileArray)) $data[$k] = arrayToString($fileArray);
214
-                    } elseif (in_array($k, $checkboxField)) {
215
-                        # 处理多选类型数据
216
-                        $data[$k] = arrayToString($v);
217
-                    } elseif (in_array($k, $userField)) {
218
-                        # 处理人员类型数据
219
-                        $userArray = [];
220
-                        foreach ($v AS $kk => $vv) {
221
-                           if (!empty($vv['id'])) $userArray[] = $vv['id'];
222
-                        }
223
-                        $data[$k] = !empty($userArray) ? arrayToString($userArray) : '';
224
-                    } elseif (in_array($k, $structureField)) {
225
-                        # 处理部门类型数据
226
-                        $structureArray = [];
227
-                        foreach ($v AS $kk => $vv) {
228
-                            if (!empty($vv['id'])) $structureArray[] = $vv['id'];
229
-                        }
230
-                        $data[$k] = !empty($structureArray) ? arrayToString($structureArray) : '';
206
+                    } elseif (in_array($k, $fileField) || in_array($k, $checkboxField) || in_array($k, $userField) || in_array($k, $structureField)) {
207
+                        # 处理附件、多选、人员、部门类型数据
208
+                        $data[$k] = !empty($v) ? arrayToString($v) : '';
231
                     } elseif ($types == 'crm_visit' && $k == 'contract_id') {
209
                     } elseif ($types == 'crm_visit' && $k == 'contract_id') {
232
                         # 处理回访提交过来的合同编号
210
                         # 处理回访提交过来的合同编号
233
                         if (!empty($v[0]['contract_id'])) $data[$k] = $v[0]['contract_id'];
211
                         if (!empty($v[0]['contract_id'])) $data[$k] = $v[0]['contract_id'];
234
-                    }else {
212
+                    } else {
235
                         $data[$k] = $v;
213
                         $data[$k] = $v;
236
                     }
214
                     }
215
+                    $item[$k]=$v;
237
                 }
216
                 }
238
-                $item=$value;
239
             }
217
             }
240
             $data[$primaryKey]   = $actionId;
218
             $data[$primaryKey]   = $actionId;
241
             $data['update_time'] = time();
219
             $data['update_time'] = time();
242
         }
220
         }
243
         $res = $model->update($data);
221
         $res = $model->update($data);
222
+        unset($data[$primaryKey]);
223
+        unset($data['update_time']);
244
         //详细信息修改新增操作记录
224
         //详细信息修改新增操作记录
245
         if ($res) {
225
         if ($res) {
246
             //修改记录
226
             //修改记录
247
             $user_id = $apiCommon->userInfo;
227
             $user_id = $apiCommon->userInfo;
248
-            updateActionLog($user_id['id'], $types, $actionId, $info, $item);
228
+            updateActionLog($user_id['id'], $types, $actionId, $info, $data);
249
         }
229
         }
250
         return $res;
230
         return $res;
251
     }
231
     }

+ 79
- 40
application/crm/logic/IndexLogic.php Целия файл

37
         $contractModel = new \app\crm\model\Contract();
37
         $contractModel = new \app\crm\model\Contract();
38
         $receivablesModel = new \app\crm\model\Receivables();
38
         $receivablesModel = new \app\crm\model\Receivables();
39
         $activityModel = new \app\crm\model\Activity();
39
         $activityModel = new \app\crm\model\Activity();
40
-
40
+        if($param['start_time'] && $param['end_time']){
41
+            $param['start_time']=$param['start_time'].'00:00:00';
42
+            $param['end_time']=$param['end_time'].'23:59:59';
43
+        }
41
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
44
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
42
         $lastArr = $adminModel->getWhere($param, 1, '', true); //统计条件
45
         $lastArr = $adminModel->getWhere($param, 1, '', true); //统计条件
43
         $userIds = $whereArr['userIds'];
46
         $userIds = $whereArr['userIds'];
44
         $between_time = $whereArr['between_time'];
47
         $between_time = $whereArr['between_time'];
45
         $last_between_time = $lastArr['between_time'];
48
         $last_between_time = $lastArr['between_time'];
46
-
49
+      
50
+        
47
         $customerNum = 0; //新增客户
51
         $customerNum = 0; //新增客户
48
         $customerLastNum = 0; //上期对比
52
         $customerLastNum = 0; //上期对比
49
         $contactsNum = 0; //新增联系人
53
         $contactsNum = 0; //新增联系人
146
 
150
 
147
     public function getCountSql($param)
151
     public function getCountSql($param)
148
     {
152
     {
153
+        $configModel = new \app\crm\model\ConfigData();
154
+        $configInfo = $configModel->getData();
155
+        $follow_day = $configInfo['follow_day'] ? : 0;
156
+        $deal_day = $configInfo['deal_day'] ? : 0;
157
+        //默认公海条件(没有负责人或已经到期)
158
+        $data['follow_time'] = time()-$follow_day*86400;
159
+        $data['deal_time'] = time()-$deal_day*86400;
160
+        $data['deal_status'] = '未成交';
149
         $countSql = "SELECT
161
         $countSql = "SELECT
150
         count(1) count1,
162
         count(1) count1,
151
         0 count2
163
         0 count2
152
         FROM 5kcrm_crm_customer
164
         FROM 5kcrm_crm_customer
153
         WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
165
         WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
154
         and owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")
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 )
155
         UNION ALL
168
         UNION ALL
156
         SELECT
169
         SELECT
157
         count(1) AS count1,
170
         count(1) AS count1,
158
         0 count2
171
         0 count2
159
-        FROM 5kcrm_crm_contacts
160
-        WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
161
-        and owner_user_id IN (" . implode(',', $param['contacts_auth_user_ids']) . ")
172
+        FROM 5kcrm_crm_contacts contacts
173
+         LEFT JOIN 5kcrm_crm_customer customer ON contacts.customer_id=customer.customer_id
174
+        WHERE contacts.create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
175
+        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 )
162
         UNION ALL
177
         UNION ALL
163
         SELECT
178
         SELECT
164
         count(1) AS count1,
179
         count(1) AS count1,
180
         FROM 5kcrm_crm_receivables
195
         FROM 5kcrm_crm_receivables
181
         WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
196
         WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
182
         AND check_status = 2
197
         AND check_status = 2
183
-        and owner_user_id IN (" . implode(',', $param['receivables_auth_user_ids']) . ")                     
198
+        and owner_user_id IN (" . implode(',', $param['receivables_auth_user_ids']) . ")
184
         UNION ALL
199
         UNION ALL
185
         SELECT
200
         SELECT
186
         count(1) AS count,
201
         count(1) AS count,
221
         $adminModel = new \app\admin\model\Admin();
236
         $adminModel = new \app\admin\model\Admin();
222
         $customerModel = new \app\crm\model\Customer();
237
         $customerModel = new \app\crm\model\Customer();
223
         $dateTime = date('Y-m-d H:i:s');
238
         $dateTime = date('Y-m-d H:i:s');
239
+        if($param['start_time'] && $param['end_time']){
240
+            $param['start_time']=$param['start_time'].'00:00:00';
241
+            $param['end_time']=$param['end_time'].'23:59:59';
242
+        }
224
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
243
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
225
         $userIds = $whereArr['userIds'];
244
         $userIds = $whereArr['userIds'];
226
         //权限控制
245
         //权限控制
235
         $customerParam['getCount'] = 1;
254
         $customerParam['getCount'] = 1;
236
         $customerParam['owner_user_id'] = $owner_user_ids;
255
         $customerParam['owner_user_id'] = $owner_user_ids;
237
 
256
 
238
-        $sevenDaysParam['otherMap'] = " ( IFNULL('last_time','create_time') < " . strtotime('-1 week') . ") ";
239
-        $fifteenDaysParam['otherMap'] = " ( IFNULL('last_time','create_time') < " . strtotime('15 day') . ") ";
240
-        $oneMonthParam['otherMap'] = " ( IFNULL('last_time','create_time') < " . strtotime('-30 day') . ") ";
241
-        $threeMonthParam['otherMap'] = " ( IFNULL('last_time','create_time') < " . strtotime('-3 month') . ") ";
242
-        $sixMonthParam['otherMap'] = " ( IFNULL('last_time','create_time') < " . strtotime('-6 month') . ") ";
243
-        $unContactParam['otherMap'] = " ( last_time < next_time AND next_time < now()) ";
244
-
257
+        $sevenDaysParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-1 week') . ") ";
258
+        $fifteenDaysParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-15 day') . ") ";
259
+        $oneMonthParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-30 day') . ") ";
260
+        $threeMonthParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-3 month') . ") ";
261
+        $sixMonthParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-6 month') . ") ";
262
+        $unContactParam['otherMap'] = " ( next_time < " . strtotime(date('Y-m-d 00:00:00')) . " AND (next_time) >0) ";
245
         $data['sevenDays'] = $customerModel->getDataList(array_merge($customerParam, $sevenDaysParam))['dataCount'] ?: 0;
263
         $data['sevenDays'] = $customerModel->getDataList(array_merge($customerParam, $sevenDaysParam))['dataCount'] ?: 0;
246
         $data['fifteenDays'] = $customerModel->getDataList(array_merge($customerParam, $fifteenDaysParam))['dataCount'] ?: 0;
264
         $data['fifteenDays'] = $customerModel->getDataList(array_merge($customerParam, $fifteenDaysParam))['dataCount'] ?: 0;
247
         $data['oneMonth'] = $customerModel->getDataList(array_merge($customerParam, $oneMonthParam))['dataCount'] ?: 0;
265
         $data['oneMonth'] = $customerModel->getDataList(array_merge($customerParam, $oneMonthParam))['dataCount'] ?: 0;
264
         $userModel = new \app\admin\model\User();
282
         $userModel = new \app\admin\model\User();
265
         $adminModel = new \app\admin\model\Admin();
283
         $adminModel = new \app\admin\model\Admin();
266
         $customerModel = new \app\crm\model\Customer();
284
         $customerModel = new \app\crm\model\Customer();
285
+        if($param['start_time'] && $param['end_time']){
286
+            $param['start_time']=$param['start_time'].'00:00:00';
287
+            $param['end_time']=$param['end_time'].'23:59:59';
288
+        }
267
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
289
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
268
         $userIds = $whereArr['userIds'];
290
         $userIds = $whereArr['userIds'];
269
         //权限控制
291
         //权限控制
286
         $customerParam['owner_user_id'] = $owner_user_ids;
308
         $customerParam['owner_user_id'] = $owner_user_ids;
287
 
309
 
288
         switch ($label) {
310
         switch ($label) {
311
+            case 1 :
312
+//                ((( next_time < " . strtotime(date('Y-m-d 00:00:00')).") AND (last_time IS NOT NULL))  AND (IFNULL(last_time,next_time) >0))
313
+                $customerParam['otherMap'] = " (next_time < " . strtotime(date('Y-m-d 00:00:00')) . " AND (next_time) >0) ";
314
+                break;
289
             case 2 :
315
             case 2 :
290
-                $customerParam['otherMap'] = " ( IFNULL('last_time','create_time') < " . strtotime('-1 week') . ") ";
316
+                $customerParam['otherMap'] = " ( IFNULL(last_time,create_time) < " . strtotime('-1 week') . ") ";
291
                 break;
317
                 break;
292
             case 3 :
318
             case 3 :
293
-                $customerParam['otherMap'] = "  (  IFNULL('last_time','create_time') < " . strtotime('15 day') . ") ";
319
+                $customerParam['otherMap'] = "  (  IFNULL(last_time,create_time) < " . strtotime('-15 day') . ") ";
294
                 break;
320
                 break;
295
             case 4 :
321
             case 4 :
296
-                $customerParam['otherMap'] = "  ( IFNULL('last_time','create_time') < " . strtotime('-30 day') . ") ";
322
+                $customerParam['otherMap'] = "  ( IFNULL(last_time,create_time) < " . strtotime('-30 day') . ") ";
297
                 break;
323
                 break;
298
             case 5 :
324
             case 5 :
299
-                $customerParam['otherMap'] = "  ( IFNULL('last_time','create_time') < " . strtotime('-3 month') . ") ";
325
+                $customerParam['otherMap'] = "  ( IFNULL(last_time,create_time) < " . strtotime('-3 month') . ") ";
300
                 break;
326
                 break;
301
             case 6 :
327
             case 6 :
302
-                $customerParam['otherMap'] = "  ( IFNULL('last_time','create_time') < " . strtotime('-6 month') . ") ";
328
+                $customerParam['otherMap'] = "  ( IFNULL(last_time,create_time) < " . strtotime('-6 month') . ") ";
303
                 break;
329
                 break;
304
         }
330
         }
305
         return $customerModel->getDataList($customerParam);
331
         return $customerModel->getDataList($customerParam);
318
         $adminModel = new \app\admin\model\Admin();
344
         $adminModel = new \app\admin\model\Admin();
319
         $user_id = $param['user_id'] ?: [-1];
345
         $user_id = $param['user_id'] ?: [-1];
320
         $status = $param['label'] ?: 1; //1合同目标 2回款目标 3合同数 4新增客户数 5新增联系人数 6新增跟进记录数
346
         $status = $param['label'] ?: 1; //1合同目标 2回款目标 3合同数 4新增客户数 5新增联系人数 6新增跟进记录数
321
-
347
+        if($param['start_time'] && $param['end_time']){
348
+            $param['start_time']=$param['start_time'].'00:00:00';
349
+            $param['end_time']=$param['end_time'].'23:59:59';
350
+        }
322
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
351
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
323
         $userIds = $whereArr['userIds'];
352
         $userIds = $whereArr['userIds'];
324
         $between_time = $whereArr['between_time'];
353
         $between_time = $whereArr['between_time'];
508
             $achievementMoney = db('crm_achievement')->where($where_achievement)->find();
537
             $achievementMoney = db('crm_achievement')->where($where_achievement)->find();
509
             $v['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
538
             $v['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
510
             if ($achievementMoney[$achievement] == 0.00) {
539
             if ($achievementMoney[$achievement] == 0.00) {
511
-                $v['rate'] = 0.00;
540
+                $v['rate'] = 0;
512
             } else {
541
             } else {
513
-                $v['rate'] = (int)$v['money'] / $achievementMoney[$achievement];
542
+                $v['rate'] = round($v['money'] / $achievementMoney[$achievement]*100,2);
514
             }
543
             }
515
             if ($userName['realname'] == $v['realname']) {
544
             if ($userName['realname'] == $v['realname']) {
516
                 $list['self']['sort'] = $k + 1;
545
                 $list['self']['sort'] = $k + 1;
543
     {
572
     {
544
         $userModel = new \app\admin\model\User();
573
         $userModel = new \app\admin\model\User();
545
         $adminModel = new \app\admin\model\Admin();
574
         $adminModel = new \app\admin\model\Admin();
575
+        if($param['start_time'] && $param['end_time']){
576
+            $param['start_time']=$param['start_time'].'00:00:00';
577
+            $param['end_time']=$param['end_time'].'23:59:59';
578
+        }
546
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
579
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
547
         $user_id = $param['user_id'] ?: [-1];
580
         $user_id = $param['user_id'] ?: [-1];
548
         $userIds = $whereArr['userIds'];
581
         $userIds = $whereArr['userIds'];
572
             );
605
             );
573
             $resDataArr = array_merge($resDataArr, $resData[0]);
606
             $resDataArr = array_merge($resDataArr, $resData[0]);
574
         }
607
         }
575
-
576
         return $resDataArr;
608
         return $resDataArr;
577
     }
609
     }
578
 
610
 
583
      */
615
      */
584
     public function getQueryDataSql($param)
616
     public function getQueryDataSql($param)
585
     {
617
     {
618
+        $configModel = new \app\crm\model\ConfigData();
619
+        $configInfo = $configModel->getData();
620
+        $follow_day = $configInfo['follow_day'] ? : 0;
621
+        $deal_day = $configInfo['deal_day'] ? : 0;
622
+        //默认公海条件(没有负责人或已经到期)
623
+        $data['follow_time'] = time()-$follow_day*86400;
624
+        $data['deal_time'] = time()-$deal_day*86400;
625
+        $data['deal_status'] = '未成交';
586
         switch ($param['type']) {
626
         switch ($param['type']) {
587
             case 1 :
627
             case 1 :
588
                 $countSql = "SELECT
628
                 $countSql = "SELECT
590
                 COUNT(CASE WHEN deal_status = '已成交' THEN 1 ELSE NULL END) AS dealCustomer
630
                 COUNT(CASE WHEN deal_status = '已成交' THEN 1 ELSE NULL END) AS dealCustomer
591
                 FROM 5kcrm_crm_customer
631
                 FROM 5kcrm_crm_customer
592
                 WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
632
                 WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
593
-                AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")";
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
+                ";
594
                 break;
636
                 break;
595
             case 2 :
637
             case 2 :
596
                 $countSql = "SELECT
638
                 $countSql = "SELECT
597
-                count(1) activityNum,
598
-                COUNT(CASE WHEN b.activity_type_id in (SELECT customer_id FROM 5kcrm_crm_customer
639
+                 COUNT(distinct CASE WHEN  b.activity_type_id in (SELECT customer_id FROM 5kcrm_crm_customer
599
                 WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
640
                 WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
600
-                AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")
601
-                ) THEN 1 ELSE NULL END ) as activityRealNum
641
+                AND owner_user_id IN (" . implode(',', $param['customer_auth_user_ids']) . ")  AND next_time is not null
642
+                ) THEN b.activity_type_id ELSE NULL END) as  activityNum
602
                 FROM 5kcrm_crm_activity AS b
643
                 FROM 5kcrm_crm_activity AS b
603
                 WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
644
                 WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
604
                 AND b.type = '1'
645
                 AND b.type = '1'
605
-                AND b.activity_type = '2'                
606
-                AND b.status = '1'                
646
+                AND b.activity_type = '2'
647
+                AND b.status = '1'
607
                 AND b.create_user_id IN (" . implode(',', $param['record_auth_user_ids']) . ")";
648
                 AND b.create_user_id IN (" . implode(',', $param['record_auth_user_ids']) . ")";
608
                 break;
649
                 break;
609
             case 3 :
650
             case 3 :
643
     {
684
     {
644
         $userModel = new \app\admin\model\User();
685
         $userModel = new \app\admin\model\User();
645
         $adminModel = new \app\admin\model\Admin();
686
         $adminModel = new \app\admin\model\Admin();
687
+        if($param['start_time'] && $param['end_time']){
688
+            $param['start_time']=$param['start_time'].'00:00:00';
689
+            $param['end_time']=$param['end_time'].'23:59:59';
690
+        }
646
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
691
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
647
         $user_id = $param['user_id'] ?: [-1];
692
         $user_id = $param['user_id'] ?: [-1];
648
         $userIds = $whereArr['userIds'];
693
         $userIds = $whereArr['userIds'];
731
         $userModel = new \app\admin\model\User();
776
         $userModel = new \app\admin\model\User();
732
         $adminModel = new \app\admin\model\Admin();
777
         $adminModel = new \app\admin\model\Admin();
733
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
778
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
734
-        if ($param['dataType'] == 1) {
735
-            $userIds = [];
736
-            $userIds[] = $param['user_id'];
737
-        } else {
738
-            $userIds = $whereArr['userIds'];
739
-        }
740
-
779
+        $userIds = $whereArr['userIds'];
741
         //权限控制
780
         //权限控制
742
         if (!empty($param['type'])) {
781
         if (!empty($param['type'])) {
743
             $last_where_contract = getTimeByType($param['type']);
782
             $last_where_contract = getTimeByType($param['type']);
745
             $where_activity['t.create_time'] = array('between', $between_time);
784
             $where_activity['t.create_time'] = array('between', $between_time);
746
         } else {
785
         } else {
747
             //自定义时间
786
             //自定义时间
748
-            $start_time = $param['start_time'] ?: strtotime(date('Y-01-01', time()));
749
-            $end_time = $param['end_time'] ? strtotime(date('Y-m-01', $param['end_time']) . ' +1 month -1 day') : strtotime(date('Y-m-01', time()) . ' +1 month -1 day');
787
+            $start_time = $param['start_time'] ?strtotime($param['start_time'].'00:00:00'): strtotime(date('Y-01-01', time()));
788
+            $end_time = $param['end_time'] ? strtotime($param['end_time'].'23:59:59') : strtotime(date('Y-m-01', time()) . ' +1 month -1 day');
750
             $where_activity['t.create_time'] = ['between', [$start_time, $end_time]];
789
             $where_activity['t.create_time'] = ['between', [$start_time, $end_time]];
751
         }
790
         }
752
         $auth_customer_user_ids = $userModel->getUserByPer('crm', 'activity', 'index');
791
         $auth_customer_user_ids = $userModel->getUserByPer('crm', 'activity', 'index');
782
             } else {
821
             } else {
783
                 $type['t.type'] = $param['queryType'];
822
                 $type['t.type'] = $param['queryType'];
784
             }
823
             }
785
-            if ($param['user'] == '') {
824
+            if ($param['user_id'] == '') {
786
                 if ($param['subUser'] == '0') {
825
                 if ($param['subUser'] == '0') {
787
                     $type['t.create_user_id'] = $param['id'];
826
                     $type['t.create_user_id'] = $param['id'];
788
                     //下属创建
827
                     //下属创建
796
                     $type['t.create_user_id'] = array('in', $subStr);
835
                     $type['t.create_user_id'] = array('in', $subStr);
797
                 }
836
                 }
798
             } else {
837
             } else {
799
-                $type['t.create_user_id'] = $param['user'];
838
+                $type['t.create_user_id'] = $param['user_id'];
800
             }
839
             }
801
             $type['t.status'] = 1;
840
             $type['t.status'] = 1;
802
             $list = db('crm_activity')
841
             $list = db('crm_activity')

+ 21
- 8
application/crm/logic/InvoiceLogic.php Целия файл

46
 
46
 
47
         $limit = $param['limit'];
47
         $limit = $param['limit'];
48
         $getCount = $param['getCount'];
48
         $getCount = $param['getCount'];
49
+        $userId   = $param['user_id'];
50
+        $invoiceIdArray = $param['invoiceIdArray']; // 待办事项提醒参数
51
+        $dealt = $param['dealt'];
49
 
52
 
50
         unset($param['getCount']);
53
         unset($param['getCount']);
51
         unset($param['limit']);
54
         unset($param['limit']);
52
         unset($param['page']);
55
         unset($param['page']);
56
+        unset($param['user_id']);
57
+        unset($param['invoiceIdArray']);
58
+        unset($param['dealt']);
53
 
59
 
54
         $where = [];
60
         $where = [];
55
         if ($search) {
61
         if ($search) {
56
             # 处理基本参数
62
             # 处理基本参数
57
-            $userId   = $param['user_id'];
63
+
58
             $scene_id = $param['scene_id'];
64
             $scene_id = $param['scene_id'];
59
-            unset($param['user_id']);
60
             unset($param['scene_id']);
65
             unset($param['scene_id']);
61
-//            unset($param['owner_user_id']);
62
-//            unset($param['check_status']);
63
-//            unset($param['check_user_id']);
64
-//            unset($param['flow_user_id']);
65
 
66
 
66
             $common = new Common();
67
             $common = new Common();
67
 
68
 
97
             if ($where) $param = $where;
98
             if ($where) $param = $where;
98
         }
99
         }
99
 
100
 
101
+        # 待办事项查询参数
102
+        $dealtWhere = [];
103
+        if (!empty($invoiceIdArray)) $dealtWhere['invoice_id'] = ['in', $invoiceIdArray];
104
+
105
+        # 权限,不是待办事项,则加上列表权限
106
+        $auth = [];
107
+        if (empty($dealt)) {
108
+            $userModel = new \app\admin\model\User();
109
+            $authUserIds = $userModel->getUserByPer('crm', 'invoice', 'index');
110
+            $auth['owner_user_id'] = ['in', $authUserIds];
111
+        }
112
+
100
         # 查询数据
113
         # 查询数据
101
-        $list  = Invoice::with(['toCustomer', 'toContract', 'toAdminUser'])->field($field)->where($param)
102
-            ->limit($limit)->order('update_time', 'desc')->paginate($limit)->toArray();
114
+        $list = Invoice::with(['toCustomer', 'toContract', 'toAdminUser'])->field($field)->where($auth)
115
+            ->where($param)->where($dealtWhere)->limit($limit)->order('update_time', 'desc')->paginate($limit)->toArray();
103
 
116
 
104
         # 处理发票类型
117
         # 处理发票类型
105
 //        foreach ($list['data'] AS $key => $value) {
118
 //        foreach ($list['data'] AS $key => $value) {

+ 9
- 5
application/crm/logic/VisitLogic.php Целия файл

92
         $userField = $fieldModel->getFieldByFormType('crm_visit', 'user'); //人员类型
92
         $userField = $fieldModel->getFieldByFormType('crm_visit', 'user'); //人员类型
93
         $structureField = $fieldModel->getFieldByFormType('crm_visit', 'structure');  //部门类型
93
         $structureField = $fieldModel->getFieldByFormType('crm_visit', 'structure');  //部门类型
94
         $datetimeField = $fieldModel->getFieldByFormType('crm_visit', 'datetime'); //日期时间类型
94
         $datetimeField = $fieldModel->getFieldByFormType('crm_visit', 'datetime'); //日期时间类型
95
-
95
+        # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
96
+        $temporaryField = str_replace('_name', '', $order_field);
97
+        if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
98
+            $order_field = $temporaryField;
99
+        }
96
         //排序
100
         //排序
97
         if ($order_type && $order_field) {
101
         if ($order_type && $order_field) {
98
             $order = $fieldModel->getOrderByFormtype('crm_visit', 'visit', $order_field, $order_type);
102
             $order = $fieldModel->getOrderByFormtype('crm_visit', 'visit', $order_field, $order_type);
130
             ->where($map)->where($partMap)->where($authMap)->group('visit.visit_id')->count('visit.visit_id');
134
             ->where($map)->where($partMap)->where($authMap)->group('visit.visit_id')->count('visit.visit_id');
131
 
135
 
132
         foreach ($list as $k => $v) {
136
         foreach ($list as $k => $v) {
137
+            $list[$k]['contract_num'] = $v['contract_number'];
133
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
138
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
134
             $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
139
             $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
135
             $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
140
             $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
136
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
141
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
137
             foreach ($userField as $key => $val) {
142
             foreach ($userField as $key => $val) {
138
-                $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
139
-                $list[$k][$val] = implode($usernameField, ',');
143
+                $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
144
+                $list[$k][$val.'_name'] = implode($usernameField, ',');
140
             }
145
             }
141
             foreach ($structureField as $key => $val) {
146
             foreach ($structureField as $key => $val) {
142
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
147
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
143
-                $list[$k][$val]     = implode($structureNameField, ',');
148
+                $list[$k][$val.'_name'] = implode($structureNameField, ',');
144
             }
149
             }
145
             foreach ($datetimeField as $key => $val) {
150
             foreach ($datetimeField as $key => $val) {
146
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
151
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
237
             if ($v == 'visit_user_id') continue;
242
             if ($v == 'visit_user_id') continue;
238
             $param[$v] = arrayToString($param[$v]);
243
             $param[$v] = arrayToString($param[$v]);
239
         }
244
         }
240
-        $param['update_time'] = '';
241
         $visitModel = new Visit();
245
         $visitModel = new Visit();
242
         if ($visitModel->data($param)->allowField(true)->save()) {
246
         if ($visitModel->data($param)->allowField(true)->save()) {
243
             $visit_id = $visitModel->visit_id;
247
             $visit_id = $visitModel->visit_id;

+ 8
- 4
application/crm/model/Achievement.php Целия файл

83
  		if ($request['year']) {
83
  		if ($request['year']) {
84
  			$map['year'] = $request['year'];
84
  			$map['year'] = $request['year'];
85
  		}
85
  		}
86
-        if ($request['status']) {
87
-        	$map['status'] = $request['status'];
86
+        if ($request['type']) {
87
+        	$map['status'] = $request['type'];
88
         }
88
         }
89
         if ($request['user_id']) { //员工
89
         if ($request['user_id']) { //员工
90
         	$map['obj_id'] = $request['user_id'];
90
         	$map['obj_id'] = $request['user_id'];
101
         } elseif ($request['structure_id']) {
101
         } elseif ($request['structure_id']) {
102
 			$map['type'] = 3;
102
 			$map['type'] = 3;
103
 			$result = array();
103
 			$result = array();
104
-			$userlist = Db::name('AdminUser')->field('id,realname as name')->where('structure_id = '.$request['structure_id'].'')->select();
104
+			if ($request['structure_id'] == 1) {
105
+                $userlist = Db::name('AdminUser')->field('id,realname as name')->whereIn('status', [1, 2])->select();
106
+            } else {
107
+                $userlist = Db::name('AdminUser')->field('id,realname as name')->where('structure_id = '.$request['structure_id'].'')->select();
108
+            }
105
 			if (!$userlist) {
109
 			if (!$userlist) {
106
 				return array();
110
 				return array();
107
 			}
111
 			}
273
             foreach ($temp_user_ids as $k =>$v) {
277
             foreach ($temp_user_ids as $k =>$v) {
274
                 $data2['type'] = 3;
278
                 $data2['type'] = 3;
275
                 $data2['obj_id'] = $v;
279
                 $data2['obj_id'] = $v;
280
+                $data2['status'] = $param['status'];
276
                 $data2['year'] = $param['year'];
281
                 $data2['year'] = $param['year'];
277
-                $data2['status'] = !empty($param['status']) ? $param['status'] : 1;
278
                 # 员工名称
282
                 # 员工名称
279
                 $param['name'] = Db::name('admin_user')->where('id', $v)->value('realname');
283
                 $param['name'] = Db::name('admin_user')->where('id', $v)->value('realname');
280
                 $ret = $this->where($data2)->find();
284
                 $ret = $this->where($data2)->find();

+ 40
- 19
application/crm/model/Business.php Целия файл

45
         $order_type = $request['order_type'];
45
         $order_type = $request['order_type'];
46
         $is_excel = $request['is_excel']; //导出
46
         $is_excel = $request['is_excel']; //导出
47
         $getCount = $request['getCount'];
47
         $getCount = $request['getCount'];
48
+        $businessTypeId = $request['typeId']; // 针对mobile
49
+        $businessStatusId = $request['statusId']; // 针对mobile
48
         unset($request['scene_id']);
50
         unset($request['scene_id']);
49
         unset($request['search']);
51
         unset($request['search']);
50
         unset($request['user_id']);
52
         unset($request['user_id']);
53
         unset($request['order_type']);
55
         unset($request['order_type']);
54
         unset($request['is_excel']);
56
         unset($request['is_excel']);
55
         unset($request['getCount']);
57
         unset($request['getCount']);
58
+        unset($request['typeId']);
59
+        unset($request['statusId']);
56
 
60
 
57
         $request = $this->fmtRequest($request);
61
         $request = $this->fmtRequest($request);
58
         $requestMap = $request['map'] ?: [];
62
         $requestMap = $request['map'] ?: [];
68
                 $sceneMap = $sceneModel->getDefaultData('crm_business', $user_id) ?: [];
72
                 $sceneMap = $sceneModel->getDefaultData('crm_business', $user_id) ?: [];
69
             }
73
             }
70
         }
74
         }
71
-        if ($search) {
75
+        if ($search || $search == '0') {
72
             //普通筛选
76
             //普通筛选
73
             $sceneMap['name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '商机名称'];
77
             $sceneMap['name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '商机名称'];
74
         }
78
         }
142
         $userField = $fieldModel->getFieldByFormType('crm_business', 'user'); //人员类型
146
         $userField = $fieldModel->getFieldByFormType('crm_business', 'user'); //人员类型
143
         $structureField = $fieldModel->getFieldByFormType('crm_business', 'structure');  //部门类型
147
         $structureField = $fieldModel->getFieldByFormType('crm_business', 'structure');  //部门类型
144
         $datetimeField = $fieldModel->getFieldByFormType('crm_business', 'datetime'); //日期时间类型
148
         $datetimeField = $fieldModel->getFieldByFormType('crm_business', 'datetime'); //日期时间类型
149
+        # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
150
+        $temporaryField = str_replace('_name', '', $order_field);
151
+        if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
152
+            $order_field = $temporaryField;
153
+        }
145
         //排序
154
         //排序
146
         if ($order_type && $order_field) {
155
         if ($order_type && $order_field) {
147
             $order = $fieldModel->getOrderByFormtype('crm_business', 'business', $order_field, $order_type);
156
             $order = $fieldModel->getOrderByFormtype('crm_business', 'business', $order_field, $order_type);
148
         } else {
157
         } else {
149
             $order = 'business.update_time desc';
158
             $order = 'business.update_time desc';
150
         }
159
         }
160
+        # 商机组和商机状态搜索
161
+        if (!empty($businessTypeId))   $map['business.type_id']   = ['eq', $businessTypeId];
162
+        if (!empty($businessStatusId)) $map['business.status_id'] = ['eq', $businessStatusId];
151
 
163
 
152
         $readAuthIds = $userModel->getUserByPer('crm', 'business', 'read');
164
         $readAuthIds = $userModel->getUserByPer('crm', 'business', 'read');
153
         $updateAuthIds = $userModel->getUserByPer('crm', 'business', 'update');
165
         $updateAuthIds = $userModel->getUserByPer('crm', 'business', 'update');
184
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
196
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
185
             foreach ($userField as $key => $val) {
197
             foreach ($userField as $key => $val) {
186
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
198
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
187
-                $list[$k][$val] = implode($usernameField, ',');
199
+                $list[$k][$val.'_name'] = implode($usernameField, ',');
188
             }
200
             }
189
             foreach ($structureField as $key => $val) {
201
             foreach ($structureField as $key => $val) {
190
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
202
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
191
-                $list[$k][$val]     = implode($structureNameField, ',');
203
+                $list[$k][$val.'_name'] = implode($structureNameField, ',');
192
             }
204
             }
193
             foreach ($datetimeField as $key => $val) {
205
             foreach ($datetimeField as $key => $val) {
194
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
206
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
267
             return false;
279
             return false;
268
         }
280
         }
269
 
281
 
270
-        # 处理下次联系时间
271
-        if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
272
-
273
         //处理部门、员工、附件、多选类型字段
282
         //处理部门、员工、附件、多选类型字段
274
         $arrFieldAtt = $fieldModel->getArrayField('crm_business');
283
         $arrFieldAtt = $fieldModel->getArrayField('crm_business');
275
         foreach ($arrFieldAtt as $k => $v) {
284
         foreach ($arrFieldAtt as $k => $v) {
276
             $param[$v] = arrayToString($param[$v]);
285
             $param[$v] = arrayToString($param[$v]);
277
         }
286
         }
278
 
287
 
288
+        # 设置今日需联系商机
289
+        if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
290
+
279
         $param['money'] = $param['money'] ?: '0.00';
291
         $param['money'] = $param['money'] ?: '0.00';
280
         $param['discount_rate'] = $param['discount_rate'] ?: '0.00';
292
         $param['discount_rate'] = $param['discount_rate'] ?: '0.00';
281
         if ($this->data($param)->allowField(true)->save()) {
293
         if ($this->data($param)->allowField(true)->save()) {
294
+            updateActionLog($param['create_user_id'], 'crm_business', $this->business_id, '', '', '创建了商机');
282
             $business_id = $this->business_id;
295
             $business_id = $this->business_id;
283
             if ($param['product']) {
296
             if ($param['product']) {
284
                 //产品数据处理
297
                 //产品数据处理
310
                 'create_user_id' => $param['create_user_id'],
323
                 'create_user_id' => $param['create_user_id'],
311
                 'update_time' => time(),
324
                 'update_time' => time(),
312
                 'create_time' => time(),
325
                 'create_time' => time(),
313
-                'customer_ids' => $param['customer_id']
326
+                'customer_ids' => ',' . $param['customer_id'] . ','
314
             ]);
327
             ]);
315
 
328
 
316
             return $data;
329
             return $data;
352
             return false;
365
             return false;
353
         }
366
         }
354
 
367
 
355
-        # 处理下次联系时间
356
-        if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
368
+        # 商机金额小数处理
369
+        if (!empty($param['money']) && is_numeric($param['money']) && strpos($param['money'], ".") === false) {
370
+            $param['money'] .= '.00';
371
+        }
357
 
372
 
358
         //处理部门、员工、附件、多选类型字段
373
         //处理部门、员工、附件、多选类型字段
359
         $arrFieldAtt = $fieldModel->getArrayField('crm_business');
374
         $arrFieldAtt = $fieldModel->getArrayField('crm_business');
361
             $param[$v] = arrayToString($param[$v]);
376
             $param[$v] = arrayToString($param[$v]);
362
         }
377
         }
363
 
378
 
379
+        # 设置今日需联系商机
380
+        if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
381
+
364
         $param['money'] = $param['money'] ?: '0.00';
382
         $param['money'] = $param['money'] ?: '0.00';
365
         $param['discount_rate'] = $param['discount_rate'] ?: '0.00';
383
         $param['discount_rate'] = $param['discount_rate'] ?: '0.00';
366
         //商机状态改变
384
         //商机状态改变
464
         $map = [];
482
         $map = [];
465
         $map['create_time'] = $where['create_time'];
483
         $map['create_time'] = $where['create_time'];
466
         $map['owner_user_id'] = ['in', $userIds];
484
         $map['owner_user_id'] = ['in', $userIds];
467
-
485
+        $map['type_id'] = $type_id;
486
+        
468
         $sql_a = CrmBusinessModel::field([
487
         $sql_a = CrmBusinessModel::field([
469
-            'SUM(CASE WHEN status_id = 1 THEN money ELSE 0 END) AS sum_ying',
470
-            'SUM(CASE WHEN status_id = 2 THEN money ELSE 0 END) AS sum_shu'
488
+            'SUM(CASE WHEN is_end = 1 THEN money ELSE 0 END) AS sum_ying',
489
+            'SUM(CASE WHEN is_end = 2 THEN money ELSE 0 END) AS sum_shu',
490
+            'type_id'
471
         ])
491
         ])
472
             ->where($map)
492
             ->where($map)
473
             ->fetchSql()
493
             ->fetchSql()
474
-            ->select();
494
+            ->find();
475
         $res_a = queryCache($sql_a, 200);
495
         $res_a = queryCache($sql_a, 200);
476
         $sql = CrmBusinessModel::field([
496
         $sql = CrmBusinessModel::field([
477
             "status_id",
497
             "status_id",
478
             'COUNT(*)' => 'count',
498
             'COUNT(*)' => 'count',
479
-            'SUM(`money`)' => 'sum'
499
+            'SUM(`money`)' => 'sum',
500
+            'type_id'
480
         ])
501
         ])
481
             ->where($where)
502
             ->where($where)
482
             ->whereNotIn('is_end', '1,2,3')
503
             ->whereNotIn('is_end', '1,2,3')
485
             ->select();
506
             ->select();
486
         $res = queryCache($sql, 200);
507
         $res = queryCache($sql, 200);
487
         $res = array_column($res, null, 'status_id');
508
         $res = array_column($res, null, 'status_id');
488
-
509
+        
489
         $sum_money = 0;
510
         $sum_money = 0;
490
         $count = 0; # 商机数总和
511
         $count = 0; # 商机数总和
491
         $moneyCount = 0; # 金额总和
512
         $moneyCount = 0; # 金额总和
493
             $v['count'] = $res[$v['status_id']]['count'] ?: 0;
514
             $v['count'] = $res[$v['status_id']]['count'] ?: 0;
494
             $v['money'] = $res[$v['status_id']]['sum'] ?: 0;
515
             $v['money'] = $res[$v['status_id']]['sum'] ?: 0;
495
             $v['status_name'] = $v['name'];
516
             $v['status_name'] = $v['name'];
496
-
517
+            
497
             $statusList[$k] = $v;
518
             $statusList[$k] = $v;
498
-
519
+            
499
             $sum_money += $v['money'];
520
             $sum_money += $v['money'];
500
             $moneyCount += $v['money'];
521
             $moneyCount += $v['money'];
501
             $count += $v['count'];
522
             $count += $v['count'];
502
         }
523
         }
503
-        $data['list'] = $statusList;
524
+        
504
         $data['list'] = $statusList;
525
         $data['list'] = $statusList;
505
         $data['sum_ying'] = $res_a[0]['sum_ying'] ?: 0;
526
         $data['sum_ying'] = $res_a[0]['sum_ying'] ?: 0;
506
         $data['sum_shu'] = $res_a[0]['sum_shu'] ?: 0;
527
         $data['sum_shu'] = $res_a[0]['sum_shu'] ?: 0;
507
         $data['sum_money'] = $sum_money ?: 0;
528
         $data['sum_money'] = $sum_money ?: 0;
508
         $data['total'] = ['name' => '合计', 'money_count' => $moneyCount, 'count' => $count];
529
         $data['total'] = ['name' => '合计', 'money_count' => $moneyCount, 'count' => $count];
509
-
530
+        
510
         return $data ?: [];
531
         return $data ?: [];
511
     }
532
     }
512
 
533
 

+ 7
- 2
application/crm/model/BusinessStatus.php Целия файл

44
      * @return    [array]                    [description]
44
      * @return    [array]                    [description]
45
      */		
45
      */		
46
 	public function getTypeList($request)
46
 	public function getTypeList($request)
47
-    {  	
48
-			
47
+    {
48
+        # H5不传page和limit(查全部),商机组不会有太多,把limit设置大一些就行。
49
+        if (empty($request['limit'])) $request['limit'] = 100;
50
+        if (empty($request['page']))  $request['page'] = 1;
51
+
49
     	$userModel = new \app\admin\model\User();
52
     	$userModel = new \app\admin\model\User();
50
     	$structureModel = new \app\admin\model\Structure();
53
     	$structureModel = new \app\admin\model\Structure();
51
         $request = $this->fmtRequest( $request );
54
         $request = $this->fmtRequest( $request );
54
 			//普通筛选
57
 			//普通筛选
55
 			$map['name'] = ['like', '%'.$map['search'].'%'];
58
 			$map['name'] = ['like', '%'.$map['search'].'%'];
56
 		}
59
 		}
60
+
57
         $map['is_display'] = ['eq', 1];
61
         $map['is_display'] = ['eq', 1];
58
 		unset($map['search']);
62
 		unset($map['search']);
59
 		$list = db('crm_business_type')
63
 		$list = db('crm_business_type')
67
         	$list[$k]['structure_id_info'] = $structureModel->getListByStr($v['structure_id']) ? : [];
71
         	$list[$k]['structure_id_info'] = $structureModel->getListByStr($v['structure_id']) ? : [];
68
         	$list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
72
         	$list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
69
             $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
73
             $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
74
+            $list[$k]['status_list'] = db('crm_business_status')->where('type_id', $v['type_id'])->order('order_id', 'asc')->select();
70
         }    
75
         }    
71
         $data = [];
76
         $data = [];
72
         $data['list'] = $list;
77
         $data['list'] = $list;

+ 10
- 8
application/crm/model/Contacts.php Целия файл

63
 			$sceneMap = $sceneModel->getDefaultData('crm_contacts', $user_id) ? : [];
63
 			$sceneMap = $sceneModel->getDefaultData('crm_contacts', $user_id) ? : [];
64
 		}
64
 		}
65
 		$searchMap = [];
65
 		$searchMap = [];
66
-		if ($search) {
66
+		if ($search || $search == '0') {
67
 			//普通筛选
67
 			//普通筛选
68
 			$searchMap = function($query) use ($search){
68
 			$searchMap = function($query) use ($search){
69
 			        $query->where('contacts.name',array('like','%'.$search.'%'))
69
 			        $query->where('contacts.name',array('like','%'.$search.'%'))
109
 		$userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型
109
 		$userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型
110
 		$structureField = $fieldModel->getFieldByFormType('crm_contacts', 'structure');  //部门类型
110
 		$structureField = $fieldModel->getFieldByFormType('crm_contacts', 'structure');  //部门类型
111
         $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
111
         $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
112
-
112
+        # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
113
+        $temporaryField = str_replace('_name', '', $order_field);
114
+        if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
115
+            $order_field = $temporaryField;
116
+        }
113
 		//排序
117
 		//排序
114
 		if ($order_type && $order_field) {
118
 		if ($order_type && $order_field) {
115
 			$order = $fieldModel->getOrderByFormtype('crm_contacts','contacts',$order_field,$order_type);
119
 			$order = $fieldModel->getOrderByFormtype('crm_contacts','contacts',$order_field,$order_type);
147
         		->field('contacts.*,customer.name as customer_name')
151
         		->field('contacts.*,customer.name as customer_name')
148
         		->orderRaw($order)
152
         		->orderRaw($order)
149
         		->select();
153
         		->select();
150
-        
151
         foreach ($list as $k=>$v) {
154
         foreach ($list as $k=>$v) {
152
         	$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
155
         	$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
153
         	$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
156
         	$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
155
         	$list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : '';
158
         	$list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : '';
156
 			foreach ($userField as $key => $val) {
159
 			foreach ($userField as $key => $val) {
157
 			    $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
160
 			    $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
158
-                $list[$k][$val] = implode($usernameField, ',');
161
+                $list[$k][$val.'_name'] = implode($usernameField, ',');
159
         	}
162
         	}
160
 			foreach ($structureField as $key => $val) {
163
 			foreach ($structureField as $key => $val) {
161
 			    $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
164
 			    $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
162
-                $list[$k][$val]     = implode($structureNameField, ',');
165
+                $list[$k][$val.'_name'] = implode($structureNameField, ',');
163
         	}
166
         	}
164
             foreach ($datetimeField as $key => $val) {
167
             foreach ($datetimeField as $key => $val) {
165
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
168
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
194
         $data = [];
197
         $data = [];
195
         $data['list'] = $list;
198
         $data['list'] = $list;
196
         $data['dataCount'] = $dataCount ? : 0;
199
         $data['dataCount'] = $dataCount ? : 0;
197
-
198
         return $data;
200
         return $data;
199
     }
201
     }
200
 
202
 
248
                 'create_user_id'   => $param['create_user_id'],
250
                 'create_user_id'   => $param['create_user_id'],
249
                 'update_time'      => time(),
251
                 'update_time'      => time(),
250
                 'create_time'      => time(),
252
                 'create_time'      => time(),
251
-                'customer_ids'     => $param['customer_id']
253
+                'customer_ids'     => ',' . $param['customer_id'] . ','
252
             ]);
254
             ]);
253
 
255
 
254
             # 处理商机首要联系人
256
             # 处理商机首要联系人
376
         $starId = empty($userId) ? 0 : Db::name('crm_star')->where(['user_id' => $userId, 'target_id' => $id, 'type' => 'crm_contacts'])->value('star_id');
378
         $starId = empty($userId) ? 0 : Db::name('crm_star')->where(['user_id' => $userId, 'target_id' => $id, 'type' => 'crm_contacts'])->value('star_id');
377
         $dataInfo['star'] = !empty($starId) ? 1 : 0;
379
         $dataInfo['star'] = !empty($starId) ? 1 : 0;
378
         # 处理决策人显示问题
380
         # 处理决策人显示问题
379
-        $dataInfo['decision'] = !empty($dataInfo['decision']) && $dataInfo['decision'] == '是' ? '是' : '';
381
+        $dataInfo['decision'] = !empty($dataInfo['decision']) && $dataInfo['decision'] == '是' ? '是' : '';
380
         # 处理时间格式
382
         # 处理时间格式
381
         $fieldModel = new \app\admin\model\Field();
383
         $fieldModel = new \app\admin\model\Field();
382
         $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
384
         $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型

+ 122
- 45
application/crm/model/Contract.php Целия файл

47
     	$order_type = $request['order_type'];     	
47
     	$order_type = $request['order_type'];     	
48
     	$is_excel = $request['is_excel']; //导出
48
     	$is_excel = $request['is_excel']; //导出
49
         $getCount = $request['getCount'];
49
         $getCount = $request['getCount'];
50
+        $contractIdArray = $request['contractIdArray']; // 待办事项提醒参数
50
 
51
 
51
 		unset($request['scene_id']);
52
 		unset($request['scene_id']);
52
 		unset($request['search']);
53
 		unset($request['search']);
55
 		unset($request['order_type']);		  	
56
 		unset($request['order_type']);		  	
56
 		unset($request['is_excel']);
57
 		unset($request['is_excel']);
57
         unset($request['getCount']);
58
         unset($request['getCount']);
59
+        unset($request['contractIdArray']);
58
 
60
 
59
         $request = $this->fmtRequest( $request );
61
         $request = $this->fmtRequest( $request );
60
 
62
 
71
                 $sceneMap = $sceneModel->getDefaultData('crm_contract', $user_id) ? : [];
73
                 $sceneMap = $sceneModel->getDefaultData('crm_contract', $user_id) ? : [];
72
             }
74
             }
73
         }
75
         }
74
-		if ($search) {
75
-			//普通筛选
76
-			$sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '合同名称'];
76
+        $searchWhere = [];
77
+		if ($search || $search == '0') {
78
+            //普通筛选
79
+		    $searchWhere = function ($query) use ($search) {
80
+		        $query->where(function ($query) use ($search){
81
+                    $query->whereLike('customer.name', '%' . $search . '%');
82
+                })->whereOr(function ($query) use ($search) {
83
+                    $query->whereLike('contract.num', '%' . $search . '%');
84
+                })->whereOr(function ($query) use ($search) {
85
+                    $query->whereLike('contract.name', '%' . $search . '%');
86
+                });
87
+            };
88
+//            if (db('crm_customer')->whereLike('name', '%' . $search . '%')->value('customer_id')) {
89
+//                $sceneMap['customer_name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '客户名称'];
90
+//            } elseif (db('crm_contract')->whereLike('num', '%' . $search . '%')->value('contract_id')) {
91
+//                $sceneMap['num'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '合同编号'];
92
+//            } else {
93
+//                $sceneMap['name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '合同名称'];
94
+//            }
77
 		}
95
 		}
78
 		$partMap = [];
96
 		$partMap = [];
79
 		//优先级:普通筛选>高级筛选>场景
97
 		//优先级:普通筛选>高级筛选>场景
128
 		$userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
146
 		$userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
129
 		$structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure');  //部门类型
147
 		$structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure');  //部门类型
130
         $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
148
         $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
149
+        # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
150
+        $temporaryField = str_replace('_name', '', $order_field);
151
+        if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
152
+            $order_field = $temporaryField;
153
+        }
131
 		//排序
154
 		//排序
132
 		if ($order_type && $order_field) {
155
 		if ($order_type && $order_field) {
133
 			$order = $fieldModel->getOrderByFormtype('crm_contract','contract',$order_field,$order_type);
156
 			$order = $fieldModel->getOrderByFormtype('crm_contract','contract',$order_field,$order_type);
134
 		} else {
157
 		} else {
135
 			$order = 'contract.update_time desc';
158
 			$order = 'contract.update_time desc';
136
 		}
159
 		}
160
+
161
+		# 待办事项查询参数
162
+        $dealtWhere = [];
163
+		if (!empty($contractIdArray)) $dealtWhere['contract.contract_id'] = ['in', $contractIdArray];
137
 				
164
 				
138
 		$readAuthIds = $userModel->getUserByPer('crm', 'contract', 'read');
165
 		$readAuthIds = $userModel->getUserByPer('crm', 'contract', 'read');
139
         $updateAuthIds = $userModel->getUserByPer('crm', 'contract', 'update');
166
         $updateAuthIds = $userModel->getUserByPer('crm', 'contract', 'update');
144
             ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
171
             ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
145
             ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
172
             ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
146
             // ->join('__CRM_RECEIVABLES_PLAN__ plan','contract.contract_id = plan.contract_id','LEFT')
173
             // ->join('__CRM_RECEIVABLES_PLAN__ plan','contract.contract_id = plan.contract_id','LEFT')
147
-            ->where($map)->where($partMap)->where($authMap)->group('contract.contract_id')->count('contract.contract_id');
174
+            ->where($searchWhere)->where($map)->where($partMap)->where($authMap)->where($dealtWhere)->group('contract.contract_id')->count('contract.contract_id');
148
         if (!empty($getCount) && $getCount == 1) {
175
         if (!empty($getCount) && $getCount == 1) {
149
             $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
176
             $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
150
 			$contractMoney = $this->getContractMoney($map, $partMap, $authMap);
177
 			$contractMoney = $this->getContractMoney($map, $partMap, $authMap);
151
-	        $receivedMoney = $this->getReceivablesMoney($map, $partMap, $authMap);
152
 	        $data['extraData']['money'] = [
178
 	        $data['extraData']['money'] = [
153
-	            'contractMoney'   => $this->getContractMoney($map, $partMap, $authMap),                        # 合同总金额
154
-	            'receivedMoney'   => $this->getReceivablesMoney($map, $partMap, $authMap),                     # 回款总金额
155
-	            'unReceivedMoney' => sprintf("%.2f", $contractMoney - $receivedMoney) # 未回款
179
+	            'contractMoney'   => $contractMoney['contractMoney'],    # 合同总金额
180
+	            'receivedMoney'   => $contractMoney['receivablesMoney'], # 回款总金额
181
+	            'unReceivedMoney' => $contractMoney['arrearsMoney']      # 未回款总金额
156
 	        ];         
182
 	        ];         
157
             return $data;
183
             return $data;
158
         }
184
         }
167
 				->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')	
193
 				->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')	
168
 				// ->join('__CRM_RECEIVABLES_PLAN__ plan','contract.contract_id = plan.contract_id','LEFT')	
194
 				// ->join('__CRM_RECEIVABLES_PLAN__ plan','contract.contract_id = plan.contract_id','LEFT')	
169
 				->join('CrmReceivables receivables','receivables.contract_id = contract.contract_id AND receivables.check_status = 2','LEFT')
195
 				->join('CrmReceivables receivables','receivables.contract_id = contract.contract_id AND receivables.check_status = 2','LEFT')
170
-				->where($map)
196
+                ->where($searchWhere)
197
+                ->where($map)
171
 				->where($partMap)
198
 				->where($partMap)
172
 				->where($authMap)
199
 				->where($authMap)
200
+                ->where($dealtWhere)
173
         		->limit($request['offset'], $request['length'])
201
         		->limit($request['offset'], $request['length'])
174
         		->field(array_merge($indexField, [
202
         		->field(array_merge($indexField, [
175
 					'customer.name' => 'customer_name',
203
 					'customer.name' => 'customer_name',
188
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
216
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
189
 			foreach ($userField as $key => $val) {
217
 			foreach ($userField as $key => $val) {
190
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
218
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
191
-                $list[$k][$val] = implode($usernameField, ',');
219
+                $list[$k][$val.'_name'] = implode($usernameField, ',');
192
         	}
220
         	}
193
 			foreach ($structureField as $key => $val) {
221
 			foreach ($structureField as $key => $val) {
194
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
222
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
195
-                $list[$k][$val]     = implode($structureNameField, ',');
223
+                $list[$k][$val.'_name'] = implode($structureNameField, ',');
196
         	}
224
         	}
197
             foreach ($datetimeField as $key => $val) {
225
             foreach ($datetimeField as $key => $val) {
198
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
226
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
243
         $data['list'] = $list;
271
         $data['list'] = $list;
244
         $data['dataCount'] = $dataCount ? : 0;
272
         $data['dataCount'] = $dataCount ? : 0;
245
         $contractMoney = $this->getContractMoney($map, $partMap, $authMap);
273
         $contractMoney = $this->getContractMoney($map, $partMap, $authMap);
246
-        $receivedMoney = $this->getReceivablesMoney($map, $partMap, $authMap);
247
         $data['extraData']['money'] = [
274
         $data['extraData']['money'] = [
248
-            'contractMoney'   => $this->getContractMoney($map, $partMap, $authMap),                        # 合同总金额
249
-            'receivedMoney'   => $this->getReceivablesMoney($map, $partMap, $authMap),                     # 回款总金额
250
-            'unReceivedMoney' => sprintf("%.2f", $contractMoney - $receivedMoney) # 未回款
275
+            'contractMoney'   => $contractMoney['contractMoney'],    # 合同总金额
276
+            'receivedMoney'   => $contractMoney['receivablesMoney'], # 回款总金额
277
+            'unReceivedMoney' => $contractMoney['arrearsMoney']      # 未回款
251
         ];
278
         ];
252
 
279
 
253
         return $data;
280
         return $data;
254
     }
281
     }
255
 
282
 
256
     /**
283
     /**
257
-     * 获取回款总金额
284
+     * 获取合同相关金额
258
      *
285
      *
259
      * @param $map
286
      * @param $map
260
      * @param $partMap
287
      * @param $partMap
261
      * @param $authMap
288
      * @param $authMap
262
-     * @return float|string
289
+     * @author fanqi
290
+     * @date 2021-03-03
291
+     * @return array
263
      */
292
      */
264
-    private function getReceivablesMoney($map, $partMap, $authMap)
293
+    private function getContractMoney($map, $partMap, $authMap)
265
     {
294
     {
266
-        $contractIds = db('crm_contract')
295
+        $contractMoney    = 0.00; # 合同总金额
296
+        $receivablesMoney = 0.00; # 回款总金额
297
+        $arrearsMoney     = 0.00; # 未回款总金额
298
+
299
+        # 过滤审核状态参数,只查询审核成功的数据。
300
+        foreach ($map AS $key => $value) {
301
+            if ($key === 'contract.check_status') unset($map[$key]);
302
+        }
303
+
304
+        $data = db('crm_contract')
267
             ->alias('contract')
305
             ->alias('contract')
268
             ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
306
             ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
269
             ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
307
             ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
270
             ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
308
             ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
271
-            ->where('check_status', 2)->where($map)->where($partMap)->where($authMap)->column('contract.contract_id');
272
-        $contractIds = array_unique($contractIds);
273
-
274
-        $money = db('crm_receivables')->where('check_status', 2)->whereIn('contract_id', $contractIds)->sum('money');
309
+            ->join('__CRM_RECEIVABLES__ receivables','receivables.contract_id = contract.contract_id','LEFT')
310
+            ->where('contract.check_status', 2)
311
+            ->where($map)
312
+            ->where($partMap)
313
+            ->where($authMap)
314
+            ->field(['contract.contract_id', 'contract.money AS contractMoney', 'receivables.money AS receivablesMoney', 'receivables.check_status AS receivablesStatus'])
315
+            ->select();
316
+
317
+        # 将同一合同下的回款进行整合
318
+        $result = [];
319
+        foreach ($data AS $key => $value) {
320
+            # 同属于一个合同下的回款
321
+            if (!empty($result[$value['contract_id']])) {
322
+                if ($value['receivablesStatus'] == 2) $result[$value['contract_id']]['receivablesMoney'] += $value['receivablesMoney'];
323
+                continue;
324
+            }
275
 
325
 
276
-        return !empty($money) ? sprintf("%.2f", $money) : 0.00;
277
-    }
326
+            $result[$value['contract_id']] = [
327
+                'contractMoney'    => $value['contractMoney'],
328
+                'receivablesMoney' => $value['receivablesStatus'] == 2 ? $value['receivablesMoney'] : 0,
329
+            ];
330
+        }
278
 
331
 
332
+        # 统计各金额总和
333
+        foreach ($result AS $key => $value) {
334
+            $contractMoney    += $value['contractMoney'];    # 合同金额
335
+            $receivablesMoney += $value['receivablesMoney']; # 回款金额
279
 
336
 
280
-    /**
281
-     * 获取合同总金额
282
-     *
283
-     * @param $map
284
-     * @param $partMap
285
-     * @param $authMap
286
-     * @return float|string
287
-     */
288
-    private function getContractMoney($map, $partMap, $authMap)
289
-    {
290
-        $money = db('crm_contract')
291
-            ->alias('contract')
292
-            ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
293
-            ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
294
-            ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
295
-            ->where('check_status', 2)->where($map)->where($partMap)->where($authMap)->sum('contract.money');
337
+            # 未回款金额
338
+            if ($value['contractMoney'] > $value['receivablesMoney']) $arrearsMoney += $value['contractMoney'] - $value['receivablesMoney'];
339
+        }
296
 
340
 
297
-        return !empty($money) ? sprintf("%.2f", $money) : 0.00;
341
+        return [
342
+            'contractMoney'    => sprintf("%.2f", $contractMoney),
343
+            'receivablesMoney' => sprintf("%.2f", $receivablesMoney),
344
+            'arrearsMoney'     => sprintf("%.2f", $arrearsMoney)
345
+        ];
298
     }
346
     }
299
 
347
 
300
 	//根据IDs获取数组
348
 	//根据IDs获取数组
383
                 'create_user_id'   => $param['create_user_id'],
431
                 'create_user_id'   => $param['create_user_id'],
384
                 'update_time'      => time(),
432
                 'update_time'      => time(),
385
                 'create_time'      => time(),
433
                 'create_time'      => time(),
386
-                'customer_ids'     => $param['customer_id'],
387
-                'contacts_ids'     => $param['contacts_id'],
388
-                'business_ids'     => $param['business_id']
434
+                'customer_ids'     => ',' . $param['customer_id'] . ',',
435
+                'contacts_ids'     => ',' . $param['contacts_id'] . ',',
436
+                'business_ids'     => ',' . $param['business_id'] . ','
389
             ]);
437
             ]);
390
 
438
 
439
+            # 创建待办事项的关联数据
440
+            $checkUserIds = db('crm_contract')->where('contract_id', $data['contract_id'])->value('check_user_id');
441
+            $checkUserIdArray = stringToArray($checkUserIds);
442
+            $dealtData = [];
443
+            foreach ($checkUserIdArray AS $kk => $vv) {
444
+                $dealtData[] = [
445
+                    'types'    => 'crm_contract',
446
+                    'types_id' => $data['contract_id'],
447
+                    'user_id'  => $vv
448
+                ];
449
+            }
450
+            if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
451
+
391
 			return $data;
452
 			return $data;
392
 		} else {
453
 		} else {
393
 			$this->error = '添加失败';
454
 			$this->error = '添加失败';
456
             }		
517
             }		
457
 			$data = [];
518
 			$data = [];
458
 			$data['contract_id'] = $contract_id;
519
 			$data['contract_id'] = $contract_id;
520
+
521
+			# 删除待办事项的关联数据
522
+            db('crm_dealt_relation')->where(['types' => ['eq', 'crm_contract'], 'types_id' => ['eq', $data['contract_id']]])->delete();
523
+            # 创建待办事项的关联数据
524
+            $checkUserIds = db('crm_contract')->where('contract_id', $data['contract_id'])->value('check_user_id');
525
+            $checkUserIdArray = stringToArray($checkUserIds);
526
+            $dealtData = [];
527
+            foreach ($checkUserIdArray AS $kk => $vv) {
528
+                $dealtData[] = [
529
+                    'types'    => 'crm_contract',
530
+                    'types_id' => $data['contract_id'],
531
+                    'user_id'  => $vv
532
+                ];
533
+            }
534
+            if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
535
+
459
 			return $data;
536
 			return $data;
460
 		} else {
537
 		} else {
461
 			$this->error = '编辑失败';
538
 			$this->error = '编辑失败';

+ 44
- 34
application/crm/model/Customer.php Целия файл

59
     	$is_remind = $request['is_remind'];
59
     	$is_remind = $request['is_remind'];
60
     	$getCount = $request['getCount'];
60
     	$getCount = $request['getCount'];
61
     	$otherMap = $request['otherMap'];
61
     	$otherMap = $request['otherMap'];
62
+    	unset($request['poolId']);
62
     	//需要过滤的参数
63
     	//需要过滤的参数
63
     	$unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap'];
64
     	$unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap'];
64
     	foreach ($unsetRequest as $v) {
65
     	foreach ($unsetRequest as $v) {
79
             }
80
             }
80
         }
81
         }
81
 		$searchMap = [];
82
 		$searchMap = [];
82
-		if ($search) {
83
+		if ($search || $search == '0') {
83
 			//普通筛选
84
 			//普通筛选
84
 			$searchMap = function($query) use ($search){
85
 			$searchMap = function($query) use ($search){
85
 			        $query->where('customer.name',array('like','%'.$search.'%'))
86
 			        $query->where('customer.name',array('like','%'.$search.'%'))
170
 		$userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); //人员类型
171
 		$userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); //人员类型
171
 		$structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); //部门类型
172
 		$structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); //部门类型
172
         $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); //日期时间类型
173
         $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); //日期时间类型
174
+        # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
175
+        $temporaryField = str_replace('_name', '', $order_field);
176
+        if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
177
+            $order_field = $temporaryField;
178
+        }
173
 		//排序
179
 		//排序
174
 		if ($order_type && $order_field) {
180
 		if ($order_type && $order_field) {
175
 			$order = $fieldModel->getOrderByFormtype('crm_customer','customer',$order_field,$order_type);
181
 			$order = $fieldModel->getOrderByFormtype('crm_customer','customer',$order_field,$order_type);
229
 				foreach ($userField as $key => $val) {
235
 				foreach ($userField as $key => $val) {
230
 					if (in_array($val, $field_list)) {
236
 					if (in_array($val, $field_list)) {
231
                         $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
237
                         $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
232
-                        $list[$k][$val] = implode($usernameField, ',');
238
+                        $list[$k][$val.'_name'] = implode($usernameField, ',');
233
 					}
239
 					}
234
 	        	}
240
 	        	}
235
 				foreach ($structureField as $key => $val) {
241
 				foreach ($structureField as $key => $val) {
236
 					if (in_array($val, $field_list)) {
242
 					if (in_array($val, $field_list)) {
237
                         $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
243
                         $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
238
-                        $list[$k][$val]     = implode($structureNameField, ',');
244
+                        $list[$k][$val.'_name'] = implode($structureNameField, ',');
239
 					}
245
 					}
240
 				}
246
 				}
241
                 foreach ($datetimeField as $key => $val) {
247
                 foreach ($datetimeField as $key => $val) {
335
 		foreach ($arrFieldAtt as $k=>$v) {
341
 		foreach ($arrFieldAtt as $k=>$v) {
336
 			$param[$v] = arrayToString($param[$v]);
342
 			$param[$v] = arrayToString($param[$v]);
337
 		}
343
 		}
338
-		if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
344
+
345
+        # 设置今日需联系客户
346
+        if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
347
+
348
+        if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
339
 			//修改记录
349
 			//修改记录
340
 			updateActionLog($param['create_user_id'], 'crm_customer', $this->customer_id, '', '', '创建了客户');			
350
 			updateActionLog($param['create_user_id'], 'crm_customer', $this->customer_id, '', '', '创建了客户');			
341
 			$data = [];
351
 			$data = [];
426
         foreach ($arrFieldAtt as $k=>$v) {
436
         foreach ($arrFieldAtt as $k=>$v) {
427
             $param[$v] = arrayToString($param[$v]);
437
             $param[$v] = arrayToString($param[$v]);
428
         }
438
         }
429
-        $param['follow'] = '已跟进';
439
+
440
+        # 设置今日需联系客户
441
+        if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
442
+
430
         if ($this->update($param, ['customer_id' => $customer_id], true)) {
443
         if ($this->update($param, ['customer_id' => $customer_id], true)) {
431
             //修改记录
444
             //修改记录
432
             updateActionLog($user_id, 'crm_customer', $customer_id, $dataInfo->data, $param);
445
             updateActionLog($user_id, 'crm_customer', $customer_id, $dataInfo->data, $param);
511
 	public function getStatistics($request)
524
 	public function getStatistics($request)
512
     {
525
     {
513
     	$userModel = new \app\admin\model\User();
526
     	$userModel = new \app\admin\model\User();
527
+        $adminModel = new \app\admin\model\Admin();
528
+        $request['start_time']=strtotime($request['start_time']);
529
+        $request['end_time']=strtotime($request['end_time']);
530
+        $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
531
+        $whereArr   = $adminModel->getWhere($request, '', $perUserIds); //统计条件
532
+        $userIds    = $whereArr['userIds'];
514
     	$request = $this->fmtRequest( $request );
533
     	$request = $this->fmtRequest( $request );
515
 		$map = $request['map'] ? : [];
534
 		$map = $request['map'] ? : [];
516
 		unset($map['search']);
535
 		unset($map['search']);
527
             $where_time = " > 0 ";
546
             $where_time = " > 0 ";
528
             $where_date = " != '' ";
547
             $where_date = " != '' ";
529
         }
548
         }
530
-
549
+        
531
 		//员工IDS
550
 		//员工IDS
532
 		$map_user_ids = [];
551
 		$map_user_ids = [];
533
 		if (!empty($map['user_id'])) {
552
 		if (!empty($map['user_id'])) {
535
 		} elseif (!empty($map['structure_id'])) {
554
 		} elseif (!empty($map['structure_id'])) {
536
 		    $map_user_ids = $userModel->getSubUserByStr($map['structure_id'], 2);
555
 		    $map_user_ids = $userModel->getSubUserByStr($map['structure_id'], 2);
537
 		}
556
 		}
538
-
539
-		# 没有传递员工参数并且部门下没员工的情况
540
-		if (empty($map_user_ids)) return [];
541
-
542
-		$perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
543
-		$userIds = $map_user_ids ? array_intersect($map_user_ids, $perUserIds) : $perUserIds; //数组交集
544
-		$userIds = array_values($userIds);
545
-
557
+		
546
 		$prefix = config('database.prefix');
558
 		$prefix = config('database.prefix');
547
 		$count = count($userIds);
559
 		$count = count($userIds);
560
+        $configModel = new \app\crm\model\ConfigData();
561
+        $configInfo = $configModel->getData();
562
+        $follow_day = $configInfo['follow_day'] ? : 0;
563
+        $deal_day = $configInfo['deal_day'] ? : 0;
564
+        //默认公海条件(没有负责人或已经到期)
565
+        $data['follow_time'] = time()-$follow_day*86400;
566
+        $data['deal_time'] = time()-$deal_day*86400;
567
+        $data['deal_status'] = '未成交';
548
 		$sql = '';
568
 		$sql = '';
569
+  
549
 		foreach ($userIds as $key => $user_id) {
570
 		foreach ($userIds as $key => $user_id) {
550
 			$sql .= "
571
 			$sql .= "
551
 				SELECT
572
 				SELECT
573
 				WHERE
594
 				WHERE
574
 					cu.create_time {$where_time}
595
 					cu.create_time {$where_time}
575
 					AND cu.owner_user_id = {$user_id}
596
 					AND cu.owner_user_id = {$user_id}
597
+					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 )
576
 			";
598
 			";
577
 			if ($count > 1 && $key != $count - 1) {
599
 			if ($count > 1 && $key != $count - 1) {
578
 				$sql .= " UNION ALL ";
600
 				$sql .= " UNION ALL ";
579
 			}
601
 			}
580
 		}
602
 		}
581
-
603
+  
582
 		if ($sql == '') {
604
 		if ($sql == '') {
583
 			return [];
605
 			return [];
584
 		}
606
 		}
587
         $dealCustomerCount     = 0; # 成交客户总数
609
         $dealCustomerCount     = 0; # 成交客户总数
588
         $contractMoneyCount    = 0; # 合同总金额
610
         $contractMoneyCount    = 0; # 合同总金额
589
         $receivablesMoneyCount = 0; # 回款总金额
611
         $receivablesMoneyCount = 0; # 回款总金额
612
+       
590
 		$list = queryCache($sql);
613
 		$list = queryCache($sql);
591
 		foreach ($list as &$val) {
614
 		foreach ($list as &$val) {
592
 			$val['deal_customer_num']     = Floor($val['deal_customer_num']);
615
 			$val['deal_customer_num']     = Floor($val['deal_customer_num']);
756
     	$is_lock = $param['is_lock'] ? : 0;
779
     	$is_lock = $param['is_lock'] ? : 0;
757
     	$deal_status = $param['deal_status'] ? : '未成交';
780
     	$deal_status = $param['deal_status'] ? : '未成交';
758
     	$update_time = $param['update_time'];
781
     	$update_time = $param['update_time'];
759
-    	if (strtotime($param['update_time'])) {
782
+    	if (strtotime(date('Y-m-d H:i:s', $param['update_time'])) != $param['update_time']) {
760
     		$update_time = strtotime($param['update_time']);
783
     		$update_time = strtotime($param['update_time']);
761
     	}
784
     	}
762
     	if (!$is_lock && $deal_status !== '已成交') {
785
     	if (!$is_lock && $deal_status !== '已成交') {
809
             //通过提前提醒时间,计算查询时间段
832
             //通过提前提醒时间,计算查询时间段
810
             $remind_follow_day = ($follow_day-$remind_day > 0) ? ($follow_day-$remind_day) : $follow_day-1;
833
             $remind_follow_day = ($follow_day-$remind_day > 0) ? ($follow_day-$remind_day) : $follow_day-1;
811
             $remind_deal_day = ($deal_day-$remind_day > 0) ? ($deal_day-$remind_day) : $deal_day-1;
834
             $remind_deal_day = ($deal_day-$remind_day > 0) ? ($deal_day-$remind_day) : $deal_day-1;
812
-
813
             if (($follow_day > 0) && ($deal_day > 0)) {
835
             if (($follow_day > 0) && ($deal_day > 0)) {
814
 				$follow_between = array(time()-$follow_day*86400,time()-$remind_follow_day*86400);
836
 				$follow_between = array(time()-$follow_day*86400,time()-$remind_follow_day*86400);
815
                 $deal_between = array(time()-$deal_day*86400,time()-$remind_deal_day*86400);
837
                 $deal_between = array(time()-$deal_day*86400,time()-$remind_deal_day*86400);
825
 					                    ->where(['customer.is_lock' => 0])
847
 					                    ->where(['customer.is_lock' => 0])
826
 					                    ->where(['customer.deal_status' => ['neq','已成交']]);
848
 					                    ->where(['customer.deal_status' => ['neq','已成交']]);
827
 									});							
849
 									});							
828
-								};  		
850
+								};
829
 		    	} else {
851
 		    	} else {
830
 					$whereData = function($query) use ($data){
852
 					$whereData = function($query) use ($data){
831
 					        	$query->where(function ($query) use ($data) {
853
 					        	$query->where(function ($query) use ($data) {
1084
         $poolStatus = checkPerByAction('crm', 'customer', 'pool');
1106
         $poolStatus = checkPerByAction('crm', 'customer', 'pool');
1085
 
1107
 
1086
         # 客户
1108
         # 客户
1109
+        $customerAuth = [];
1087
         $customerWhere = [];
1110
         $customerWhere = [];
1088
         if ((!empty($param['type']) && $param['type'] == 2) || !$poolStatus) {
1111
         if ((!empty($param['type']) && $param['type'] == 2) || !$poolStatus) {
1089
             $customerWhere = $this->getWhereByCustomer();
1112
             $customerWhere = $this->getWhereByCustomer();
1113
+            $customerAuth['owner_user_id'] = ['neq', 0];
1090
         }
1114
         }
1091
 
1115
 
1092
         # 公海
1116
         # 公海
1099
             return [];
1123
             return [];
1100
         }
1124
         }
1101
 
1125
 
1102
-        # 基本权限
1103
-//        $auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'index');
1104
-//        $authMapData['auth_user_ids'] = $auth_user_ids;
1105
-//        $authMapData['user_id'] = $apiCommon->userInfo['id'];
1106
-//        $authMap = function($query) use ($authMapData){
1107
-//            $query->where(['customer.owner_user_id' => array('in',$authMapData['auth_user_ids'])])
1108
-//                ->whereOr(function ($query) use ($authMapData) {
1109
-//                    $query->where('FIND_IN_SET("'.$authMapData['user_id'].'", customer.ro_user_id)')->where(['customer.owner_user_id' => array('neq','')]);
1110
-//                })
1111
-//                ->whereOr(function ($query) use ($authMapData) {
1112
-//                    $query->where('FIND_IN_SET("'.$authMapData['user_id'].'", customer.rw_user_id)')->where(['customer.owner_user_id' => array('neq','')]);
1113
-//                });
1114
-//        };
1115
-
1116
         # 附近
1126
         # 附近
1117
         $lngLatRange = $this->getLngLatRange($param['lng'], $param['lat'], $param['distance']);
1127
         $lngLatRange = $this->getLngLatRange($param['lng'], $param['lat'], $param['distance']);
1118
         $lngLatWhere = function ($query) use ($lngLatRange) {
1128
         $lngLatWhere = function ($query) use ($lngLatRange) {
1133
             ->where($customerWhere)
1143
             ->where($customerWhere)
1134
             ->where($poolWhere)
1144
             ->where($poolWhere)
1135
             ->where($lngLatWhere)
1145
             ->where($lngLatWhere)
1136
-//            ->where($authMap)
1146
+            ->where($customerAuth)
1137
             ->field(['customer_id', 'name', 'address', 'detail_address', 'owner_user_id', 'lat', 'lng'])
1147
             ->field(['customer_id', 'name', 'address', 'detail_address', 'owner_user_id', 'lat', 'lng'])
1138
             ->order('update_time', 'desc')
1148
             ->order('update_time', 'desc')
1139
             ->select();
1149
             ->select();
1143
             # todo 暂时将查询写在循环中
1153
             # todo 暂时将查询写在循环中
1144
             $ownerUserInfo = !empty($value['owner_user_id'])    ? $userModel->getUserById($value['owner_user_id']) : [];
1154
             $ownerUserInfo = !empty($value['owner_user_id'])    ? $userModel->getUserById($value['owner_user_id']) : [];
1145
             $ownerUserName = !empty($ownerUserInfo['realname']) ? $ownerUserInfo['realname'] : '';
1155
             $ownerUserName = !empty($ownerUserInfo['realname']) ? $ownerUserInfo['realname'] : '';
1146
-            $list[$key]['owner_user_name'] = $ownerUserName;
1156
+            $list[$key]['owner_user_name'] = !empty($ownerUserName) ? $ownerUserName : '暂无负责人';
1147
             $list[$key]['distance'] = $this->getLngLatDistance($param['lng'], $param['lat'], $value['lng'], $value['lat'], 1, 0);
1157
             $list[$key]['distance'] = $this->getLngLatDistance($param['lng'], $param['lat'], $value['lng'], $value['lat'], 1, 0);
1148
         }
1158
         }
1149
 
1159
 

+ 187
- 183
application/crm/model/Index.php Целия файл

14
 
14
 
15
 class Index extends Common
15
 class Index extends Common
16
 {
16
 {
17
-	/**
18
-	 * 销售简报
19
-	 * @author Michael_xu
20
-	 * @param  
21
-	 * @return                            
22
-	 */	
23
-	public function getSalesData($param)
24
-	{
25
-		$where = array();
26
-		$start_time = $param['start_time'];
27
-		$where['create_time'] = Time::today();
28
-	}
29
-
30
-	public function getQueryRepeat($type, $content)
17
+    /**
18
+     * 销售简报
19
+     * @param
20
+     * @return
21
+     * @author Michael_xu
22
+     */
23
+    public function getSalesData($param)
24
+    {
25
+        $where = array();
26
+        $start_time = $param['start_time'];
27
+        $where['create_time'] = Time::today();
28
+    }
29
+    
30
+    public function getQueryRepeat($type, $content)
31
     {
31
     {
32
-        $result       = [];
32
+        $result = [];
33
         $customerList = [];
33
         $customerList = [];
34
-        $poolList     = [];
35
-        $leadsList    = [];
36
-
34
+        $poolList = [];
35
+        $leadsList = [];
36
+        
37
         # 客户列表
37
         # 客户列表
38
         $customerList = $this->getCustomerList($type, $content);
38
         $customerList = $this->getCustomerList($type, $content);
39
         # 公海列表
39
         # 公海列表
40
         if (count($customerList) < 10) $poolList = $this->getPoolList($type, $content);
40
         if (count($customerList) < 10) $poolList = $this->getPoolList($type, $content);
41
         # 线索列表
41
         # 线索列表
42
         if (count($customerList) + count($poolList) < 10) $leadsList = $this->getLeadsList($type, $content);
42
         if (count($customerList) + count($poolList) < 10) $leadsList = $this->getLeadsList($type, $content);
43
-
44
         # 处理客户列表数据
43
         # 处理客户列表数据
45
-        foreach ($customerList AS $key => $value) {
44
+        foreach ($customerList as $key => $value) {
46
             $ownerUserName = !empty($value['owner_user_id']) ? db('admin_user')->where('id', $value['owner_user_id'])->value('realname') : '';
45
             $ownerUserName = !empty($value['owner_user_id']) ? db('admin_user')->where('id', $value['owner_user_id'])->value('realname') : '';
47
-
48
-            $result[] = [
49
-                'id'              => $value['customer_id'],
50
-                'name'            => $value['name'],
51
-                'create_time'     => date('Y-m-d H:i:s', $value['create_time']),
52
-                'mobile'          => !empty($value['mobile'])    ? $value['mobile'] : '',
53
-                'telephone'       => !empty($value['telephone']) ? $value['telephone'] : '',
54
-                'last_time'       => !empty($value['deal_time']) ? date('Y-m-d H:i:s', $value['deal_time']) : '',
55
-                'owner_user_name' => $ownerUserName,
56
-                'module'          => '客户模块',
57
-                'type'            => 2
58
-            ];
46
+            if (!empty($ownerUserName)) {
47
+                $result[] = [
48
+                    'id' => $value['customer_id'],
49
+                    'name' => $value['name'],
50
+                    'create_time' => date('Y-m-d H:i:s', $value['create_time']),
51
+                    'mobile' => !empty($value['mobile']) ? $value['mobile'] : '',
52
+                    'telephone' => !empty($value['telephone']) ? $value['telephone'] : '',
53
+                    'last_time' => !empty($value['deal_time']) ? date('Y-m-d H:i:s', $value['deal_time']) : '',
54
+                    'owner_user_name' => $ownerUserName,
55
+                    'module' => '客户模块',
56
+                    'type' => 2
57
+                ];
58
+            }
59
         }
59
         }
60
-
61
         # 处理公海列表数据
60
         # 处理公海列表数据
62
-        foreach ($poolList AS $key => $value) {
61
+        foreach ($poolList as $key => $value) {
63
             $ownerUserName = !empty($value['owner_user_id']) ? db('admin_user')->where('id', $value['owner_user_id'])->value('realname') : '';
62
             $ownerUserName = !empty($value['owner_user_id']) ? db('admin_user')->where('id', $value['owner_user_id'])->value('realname') : '';
64
-
63
+            
65
             $result[] = [
64
             $result[] = [
66
-                'id'              => $value['customer_id'],
67
-                'name'            => $value['name'],
68
-                'create_time'     => date('Y-m-d H:i:s', $value['create_time']),
69
-                'mobile'          => !empty($value['mobile'])        ? $value['mobile'] : '',
70
-                'telephone'       => !empty($value['telephone'])     ? $value['telephone'] : '',
71
-                'last_time'       => !empty($value['deal_time'])     ? date('Y-m-d H:i:s', $value['deal_time']) : '',
65
+                'id' => $value['customer_id'],
66
+                'name' => $value['name'],
67
+                'create_time' => date('Y-m-d H:i:s', $value['create_time']),
68
+                'mobile' => !empty($value['mobile']) ? $value['mobile'] : '',
69
+                'telephone' => !empty($value['telephone']) ? $value['telephone'] : '',
70
+                'last_time' => !empty($value['deal_time']) ? date('Y-m-d H:i:s', $value['deal_time']) : '',
72
                 'owner_user_name' => $ownerUserName,
71
                 'owner_user_name' => $ownerUserName,
73
-                'module'          => '公海模块',
74
-                'type'            => 9
72
+                'module' => '公海模块',
73
+                'type' => 9,
74
+                // guogaobo 公海数据权限
75
+                'poolAuthList' => [
76
+                    'receive' => true,
77
+                    'excelexport' => true,
78
+                    'poolId' => $value['customer_id'], // guogaobo 多公海使用 公海类型id
79
+                    'index' => true,
80
+                    'distribute' => true,
81
+                    'delete' => true
82
+                ]
75
             ];
83
             ];
76
         }
84
         }
77
-
78
         # 处理线索模块数据
85
         # 处理线索模块数据
79
-        foreach ($leadsList AS $key => $value) {
86
+        foreach ($leadsList as $key => $value) {
80
             $ownerUserName = !empty($value['owner_user_id']) ? db('admin_user')->where('id', $value['owner_user_id'])->value('realname') : '';
87
             $ownerUserName = !empty($value['owner_user_id']) ? db('admin_user')->where('id', $value['owner_user_id'])->value('realname') : '';
81
-
88
+            
82
             $result[] = [
89
             $result[] = [
83
-                'id'              => $value['leads_id'],
84
-                'name'            => $value['name'],
85
-                'create_time'     => date('Y-m-d H:i:s', $value['create_time']),
86
-                'mobile'          => !empty($value['mobile'])        ? $value['mobile'] : '',
87
-                'telephone'       => !empty($value['telephone'])     ? $value['telephone'] : '',
88
-                'last_time'       => '',
90
+                'id' => $value['leads_id'],
91
+                'name' => $value['name'],
92
+                'create_time' => date('Y-m-d H:i:s', $value['create_time']),
93
+                'mobile' => !empty($value['mobile']) ? $value['mobile'] : '',
94
+                'telephone' => !empty($value['telephone']) ? $value['telephone'] : '',
95
+                'last_time' => '',
89
                 'owner_user_name' => $ownerUserName,
96
                 'owner_user_name' => $ownerUserName,
90
-                'module'          => '线索模块',
91
-                'type'            => 1
92
-
97
+                'module' => '线索模块',
98
+                'type' => 1
93
             ];
99
             ];
94
         }
100
         }
95
-
96
         return $result;
101
         return $result;
97
     }
102
     }
98
-
99
     /**
103
     /**
100
      * 获取客户列表
104
      * 获取客户列表
101
      *
105
      *
107
      * @throws \think\exception\DbException
111
      * @throws \think\exception\DbException
108
      */
112
      */
109
     private function getCustomerList($type, $content)
113
     private function getCustomerList($type, $content)
110
-    {
111
-        # 默认条件
112
-        $customerWhere = $this->getCustomerWhere();
113
-
114
-        # 查询条件
115
-        $searchWhere = $this->getSearchWhere($type, $content);
116
-
117
-        # 查询字段
118
-        $field = ['customer_id', 'name', 'create_time', 'owner_user_id', 'deal_time', 'telephone', 'mobile'];
119
-
120
-        return db('crm_customer')->alias('customer')->field($field)->where($customerWhere)
121
-                ->where($searchWhere)->limit(10)->order('update_time', 'desc')->select();
122
-    }
114
+{
115
+    # 默认条件
116
+    $customerWhere = $this->getCustomerWhere();
117
+    
118
+    # 查询条件
119
+    $searchWhere = $this->getSearchWhere($type, $content);
120
+    
121
+    # 查询字段
122
+    $field = ['customer_id', 'name', 'create_time', 'owner_user_id', 'deal_time', 'telephone', 'mobile'];
123
+    
124
+    return db('crm_customer')->alias('customer')->field($field)->where($customerWhere)
125
+        ->where($searchWhere)->limit(10)->order('update_time', 'desc')->select();
126
+}
123
 
127
 
124
     /**
128
     /**
125
      * 获取公海客户列表
129
      * 获取公海客户列表
132
      * @throws \think\exception\DbException
136
      * @throws \think\exception\DbException
133
      */
137
      */
134
     private function getPoolList($type, $content)
138
     private function getPoolList($type, $content)
135
-    {
136
-        # 公海条件
137
-        $poolWhere = $this->getPoolWhere();
138
-
139
-        # 查询条件
140
-        $searchWhere = $this->getSearchWhere($type, $content);
141
-
142
-        # 查询字段
143
-        $field = ['customer_id', 'name', 'create_time', 'owner_user_id', 'deal_time', 'telephone', 'mobile'];
144
-
145
-        return db('crm_customer')->alias('customer')->field($field)->where($poolWhere)
146
-            ->where($searchWhere)->limit(10)->order('update_time', 'desc')->select();
147
-    }
139
+{
140
+    # 公海条件
141
+    $poolWhere = $this->getPoolWhere();
142
+    
143
+    # 查询条件
144
+    $searchWhere = $this->getSearchWhere($type, $content);
145
+    
146
+    # 查询字段
147
+    $field = ['customer_id', 'name', 'create_time', 'owner_user_id', 'deal_time', 'telephone', 'mobile'];
148
+    
149
+    return db('crm_customer')->alias('customer')->field($field)->where($poolWhere)
150
+        ->where($searchWhere)->limit(10)->order('update_time', 'desc')->select();
151
+}
148
 
152
 
149
     /**
153
     /**
150
      * 获取线索列表
154
      * 获取线索列表
157
      * @throws \think\exception\DbException
161
      * @throws \think\exception\DbException
158
      */
162
      */
159
     private function getLeadsList($type, $content)
163
     private function getLeadsList($type, $content)
160
-    {
161
-        # 查询条件
162
-        $searchWhere = $this->getSearchWhere($type, $content);
163
-
164
-        # 查询字段
165
-        $field = ['leads_id', 'name', 'telephone', 'mobile', 'owner_user_id', 'create_time', 'is_transform'];
166
-
167
-        return db('crm_leads')->field($field)->where($searchWhere)->where('is_transform', 0)->limit(10)
168
-                ->order('update_time', 'desc')->select();
169
-    }
164
+{
165
+    # 查询条件
166
+    $searchWhere = $this->getSearchWhere($type, $content);
167
+    
168
+    # 查询字段
169
+    $field = ['leads_id', 'name', 'telephone', 'mobile', 'owner_user_id', 'create_time', 'is_transform'];
170
+    
171
+    return db('crm_leads')->field($field)->where($searchWhere)->where('is_transform', 0)->limit(10)
172
+        ->order('update_time', 'desc')->select();
173
+}
170
 
174
 
171
     /**
175
     /**
172
      * 获取查询条件
176
      * 获取查询条件
176
      * @return array|\Closure
180
      * @return array|\Closure
177
      */
181
      */
178
     private function getSearchWhere($type, $content)
182
     private function getSearchWhere($type, $content)
179
-    {
180
-        $searchWhere = [];
181
-
182
-        # 查询客户名称
183
-        if ($type == 'name') {
184
-            $searchWhere = function ($query) use ($content) {
185
-                $query->where('name', 'like', '%' . $content . '%');
186
-            };
187
-        }
188
-
189
-        # 查询手机或电话
190
-        if ($type == 'phone') {
191
-            $searchWhere = function ($query) use ($content) {
192
-                $query->where(function ($query) use ($content) {
193
-                    $query->whereOr('telephone', $content);
194
-                    $query->whereOr('mobile',    $content);
195
-                });
196
-            };
197
-        }
198
-
199
-        return $searchWhere;
183
+{
184
+    $searchWhere = [];
185
+    
186
+    # 查询客户名称
187
+    if ($type == 'name') {
188
+        $searchWhere = function ($query) use ($content) {
189
+            $query->where('name', 'like', '%' . $content . '%');
190
+        };
200
     }
191
     }
192
+    
193
+    # 查询手机或电话
194
+    if ($type == 'phone') {
195
+        $searchWhere = function ($query) use ($content) {
196
+            $query->where(function ($query) use ($content) {
197
+                $query->whereOr('telephone', $content);
198
+                $query->whereOr('mobile', $content);
199
+            });
200
+        };
201
+    }
202
+    
203
+    return $searchWhere;
204
+}
201
 
205
 
202
     /**
206
     /**
203
      * [客户公海条件]
207
      * [客户公海条件]
204
-     * @author Michael_xu
205
      * @param
208
      * @param
206
      * @return
209
      * @return
210
+     * @author Michael_xu
207
      */
211
      */
208
     private function getPoolWhere()
212
     private function getPoolWhere()
209
-    {
210
-        $configModel = new \app\crm\model\ConfigData();
211
-        $configInfo = $configModel->getData();
212
-        $config = $configInfo['config'] ? : 0;
213
-        $follow_day = $configInfo['follow_day'] ? : 0;
214
-        $deal_day = $configInfo['deal_day'] ? : 0;
215
-        $whereData = [];
216
-        //启用
217
-        if ($config == 1) {
218
-            //默认公海条件(没有负责人或已经到期)
219
-            $data['follow_time'] = time()-$follow_day*86400;
220
-            $data['deal_time'] = time()-$deal_day*86400;
221
-            $data['deal_status'] = '未成交';
222
-            if ($follow_day < $deal_day) {
223
-                $whereData = function($query) use ($data){
224
-                    $query->where(['customer.owner_user_id'=>0])
225
-                        ->whereOr(function ($query) use ($data) {
226
-                            $query->where(function ($query) use ($data) {
227
-                                $query->where(['customer.update_time' => array('elt',$data['follow_time'])])
228
-                                    ->whereOr(['customer.deal_time' => array('elt',$data['deal_time'])]);
229
-                            })
230
-                                ->where(['customer.is_lock' => 0])
231
-                                ->where(['customer.deal_status' => ['neq','已成交']]);
232
-                        });
233
-                };
234
-            } else {
235
-                $whereData = function($query) use ($data){
236
-                    $query->where(['customer.owner_user_id'=>0])
237
-                        ->whereOr(function ($query) use ($data) {
238
-                            $query->where(function ($query) use ($data) {
239
-                                $query->where(['customer.deal_time' => array('elt',$data['deal_time'])]);
240
-                            })
241
-                                ->where(['customer.is_lock' => 0])
242
-                                ->where(['customer.deal_status' => ['neq','已成交']]);
243
-                        });
244
-                };
245
-            }
213
+{
214
+    $configModel = new \app\crm\model\ConfigData();
215
+    $configInfo = $configModel->getData();
216
+    $config = $configInfo['config'] ?: 0;
217
+    $follow_day = $configInfo['follow_day'] ?: 0;
218
+    $deal_day = $configInfo['deal_day'] ?: 0;
219
+    $whereData = [];
220
+    //启用
221
+    if ($config == 1) {
222
+        //默认公海条件(没有负责人或已经到期)
223
+        $data['follow_time'] = time() - $follow_day * 86400;
224
+        $data['deal_time'] = time() - $deal_day * 86400;
225
+        $data['deal_status'] = '未成交';
226
+        if ($follow_day < $deal_day) {
227
+            $whereData = function ($query) use ($data) {
228
+                $query->where(['customer.owner_user_id' => 0])
229
+                    ->whereOr(function ($query) use ($data) {
230
+                        $query->where(function ($query) use ($data) {
231
+                            $query->where(['customer.update_time' => array('elt', $data['follow_time'])])
232
+                                ->whereOr(['customer.deal_time' => array('elt', $data['deal_time'])]);
233
+                        })
234
+                            ->where(['customer.is_lock' => 0])
235
+                            ->where(['customer.deal_status' => ['neq', '已成交']]);
236
+                    });
237
+            };
246
         } else {
238
         } else {
247
-            $whereData['customer.owner_user_id'] = 0;
239
+            $whereData = function ($query) use ($data) {
240
+                $query->where(['customer.owner_user_id' => 0])
241
+                    ->whereOr(function ($query) use ($data) {
242
+                        $query->where(function ($query) use ($data) {
243
+                            $query->where(['customer.deal_time' => array('elt', $data['deal_time'])]);
244
+                        })
245
+                            ->where(['customer.is_lock' => 0])
246
+                            ->where(['customer.deal_status' => ['neq', '已成交']]);
247
+                    });
248
+            };
248
         }
249
         }
249
-        return $whereData ? : [];
250
+    } else {
251
+        $whereData['customer.owner_user_id'] = 0;
250
     }
252
     }
253
+    return $whereData ?: [];
254
+}
251
 
255
 
252
     /**
256
     /**
253
      * [客户默认条件]
257
      * [客户默认条件]
254
-     * @author Michael_xu
255
      * @param
258
      * @param
256
      * @return
259
      * @return
260
+     * @author Michael_xu
257
      */
261
      */
258
     private function getCustomerWhere()
262
     private function getCustomerWhere()
259
-    {
260
-        $configModel = new \app\crm\model\ConfigData();
261
-        $configInfo  = $configModel->getData();
262
-        $config      = $configInfo['config'] ? : 0;
263
-        $follow_day  = $configInfo['follow_day'] ? : 0;
264
-        $deal_day    = $configInfo['deal_day'] ? : 0;
265
-        //默认条件(没有到期或已锁定)
266
-        $data['follow_time'] = time()-$follow_day*86400;
267
-        $data['deal_time'] = time()-$deal_day*86400;
268
-        if ($config == 1) {
269
-            if ($follow_day < $deal_day) {
270
-                $whereData = function($query) use ($data){
271
-                    $query->where(function ($query) use ($data) {
272
-                        $query->where(['customer.update_time' => array('gt',$data['follow_time']),'customer.deal_time' => array('gt',$data['deal_time'])]);
273
-                    })
274
-                        ->whereOr(['customer.deal_status' => '已成交'])
275
-                        ->whereOr(['customer.is_lock' => 1]);
276
-                };
277
-            } else {
278
-                $whereData = function($query) use ($data){
279
-                    $query->where(function ($query) use ($data) {
280
-                        $query->where(['customer.deal_time' => array('gt',$data['deal_time'])]);
281
-                    })
282
-                        ->whereOr(['customer.deal_status' => '已成交'])
283
-                        ->whereOr(['customer.is_lock' => 1]);
284
-                };
285
-            }
263
+{
264
+    $configModel = new \app\crm\model\ConfigData();
265
+    $configInfo = $configModel->getData();
266
+    $config = $configInfo['config'] ?: 0;
267
+    $follow_day = $configInfo['follow_day'] ?: 0;
268
+    $deal_day = $configInfo['deal_day'] ?: 0;
269
+    //默认条件(没有到期或已锁定)
270
+    $data['follow_time'] = time() - $follow_day * 86400;
271
+    $data['deal_time'] = time() - $deal_day * 86400;
272
+    if ($config == 1) {
273
+        if ($follow_day < $deal_day) {
274
+            $whereData = function ($query) use ($data) {
275
+                $query->where(function ($query) use ($data) {
276
+                    $query->where(['customer.update_time' => array('gt', $data['follow_time']), 'customer.deal_time' => array('gt', $data['deal_time'])]);
277
+                })
278
+                    ->whereOr(['customer.deal_status' => '已成交'])
279
+                    ->whereOr(['customer.is_lock' => 1]);
280
+            };
281
+        } else {
282
+            $whereData = function ($query) use ($data) {
283
+                $query->where(function ($query) use ($data) {
284
+                    $query->where(['customer.deal_time' => array('gt', $data['deal_time'])]);
285
+                })
286
+                    ->whereOr(['customer.deal_status' => '已成交'])
287
+                    ->whereOr(['customer.is_lock' => 1]);
288
+            };
286
         }
289
         }
287
-        return $whereData ? : [];
288
     }
290
     }
291
+    return $whereData ?: [];
292
+}
289
 }
293
 }

+ 15
- 5
application/crm/model/Leads.php Целия файл

67
             }
67
             }
68
         }
68
         }
69
         $searchMap = [];
69
         $searchMap = [];
70
-        if ($search) {
70
+        if ($search || $search == '0') {
71
             //普通筛选
71
             //普通筛选
72
             $searchMap = function ($query) use ($search) {
72
             $searchMap = function ($query) use ($search) {
73
                 $query->where('leads.name', array('like', '%' . $search . '%'))
73
                 $query->where('leads.name', array('like', '%' . $search . '%'))
105
         $userField = $fieldModel->getFieldByFormType('crm_leads', 'user'); //人员类型
105
         $userField = $fieldModel->getFieldByFormType('crm_leads', 'user'); //人员类型
106
         $structureField = $fieldModel->getFieldByFormType('crm_leads', 'structure');  //部门类型
106
         $structureField = $fieldModel->getFieldByFormType('crm_leads', 'structure');  //部门类型
107
         $datetimeField = $fieldModel->getFieldByFormType('crm_leads', 'datetime'); //日期时间类型
107
         $datetimeField = $fieldModel->getFieldByFormType('crm_leads', 'datetime'); //日期时间类型
108
-
108
+        # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
109
+        $temporaryField = str_replace('_name', '', $order_field);
110
+        if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
111
+            $order_field = $temporaryField;
112
+        }
109
         //排序
113
         //排序
110
         if ($order_type && $order_field) {
114
         if ($order_type && $order_field) {
111
             $order = $fieldModel->getOrderByFormtype('crm_leads', 'leads', $order_field, $order_type);
115
             $order = $fieldModel->getOrderByFormtype('crm_leads', 'leads', $order_field, $order_type);
141
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
145
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
142
             foreach ($userField as $key => $val) {
146
             foreach ($userField as $key => $val) {
143
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
147
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
144
-                $list[$k][$val] = implode($usernameField, ',');
148
+                $list[$k][$val.'_name'] = implode($usernameField, ',');
145
             }
149
             }
146
             foreach ($structureField as $key => $val) {
150
             foreach ($structureField as $key => $val) {
147
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
151
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
148
-                $list[$k][$val]     = implode($structureNameField, ',');
152
+                $list[$k][$val.'_name'] = implode($structureNameField, ',');
149
             }
153
             }
150
             foreach ($datetimeField as $key => $val) {
154
             foreach ($datetimeField as $key => $val) {
151
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
155
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
214
             $param[$v] = arrayToString($param[$v]);
218
             $param[$v] = arrayToString($param[$v]);
215
         }
219
         }
216
 
220
 
221
+        # 设置今日需联系线索
222
+        if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
223
+
217
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
224
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
218
             //修改记录
225
             //修改记录
219
             updateActionLog($param['create_user_id'], 'crm_leads', $this->leads_id, '', '', '创建了线索');
226
             updateActionLog($param['create_user_id'], 'crm_leads', $this->leads_id, '', '', '创建了线索');
282
         foreach ($arrFieldAtt as $k => $v) {
289
         foreach ($arrFieldAtt as $k => $v) {
283
             $param[$v] = arrayToString($param[$v]);
290
             $param[$v] = arrayToString($param[$v]);
284
         }
291
         }
285
-        $param['follow'] = '已跟进';
292
+
293
+        # 设置今日需联系线索
294
+        if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
295
+
286
         if ($this->update($param, ['leads_id' => $leads_id], true)) {
296
         if ($this->update($param, ['leads_id' => $leads_id], true)) {
287
             //修改记录
297
             //修改记录
288
             updateActionLog($param['user_id'], 'crm_leads', $leads_id, $dataInfo, $param);
298
             updateActionLog($param['user_id'], 'crm_leads', $leads_id, $dataInfo, $param);

+ 9
- 5
application/crm/model/Product.php Целия файл

64
 			//默认场景
64
 			//默认场景
65
 			$sceneMap = $sceneModel->getDefaultData('crm_product', $user_id) ? : [];
65
 			$sceneMap = $sceneModel->getDefaultData('crm_product', $user_id) ? : [];
66
 		}
66
 		}
67
-		if ($search) {
67
+		if ($search || $search == '0') {
68
 			//普通筛选
68
 			//普通筛选
69
 			$sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '产品名称'];
69
 			$sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '产品名称'];
70
 		}
70
 		}
103
 		$userField = $fieldModel->getFieldByFormType('crm_product', 'user'); //人员类型
103
 		$userField = $fieldModel->getFieldByFormType('crm_product', 'user'); //人员类型
104
 		$structureField = $fieldModel->getFieldByFormType('crm_product', 'structure');  //部门类型
104
 		$structureField = $fieldModel->getFieldByFormType('crm_product', 'structure');  //部门类型
105
         $datetimeField = $fieldModel->getFieldByFormType('crm_product', 'datetime'); //日期时间类型
105
         $datetimeField = $fieldModel->getFieldByFormType('crm_product', 'datetime'); //日期时间类型
106
-		
106
+        # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
107
+        $temporaryField = str_replace('_name', '', $order_field);
108
+        if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
109
+            $order_field = $temporaryField;
110
+        }
107
 		//排序
111
 		//排序
108
 		if ($order_type && $order_field) {
112
 		if ($order_type && $order_field) {
109
 			$order = $fieldModel->getOrderByFormtype('crm_product','product',$order_field,$order_type);
113
 			$order = $fieldModel->getOrderByFormtype('crm_product','product',$order_field,$order_type);
133
         	$list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
137
         	$list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
134
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
138
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
135
         	foreach ($userField as $key => $val) {
139
         	foreach ($userField as $key => $val) {
136
-                $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
137
-                $list[$k][$val] = implode($usernameField, ',');
140
+                $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
141
+                $list[$k][$val.'_name'] = implode($usernameField, ',');
138
         	}
142
         	}
139
 			foreach ($structureField as $key => $val) {
143
 			foreach ($structureField as $key => $val) {
140
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
144
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
141
-                $list[$k][$val]     = implode($structureNameField, ',');
145
+                $list[$k][$val.'_name'] = implode($structureNameField, ',');
142
         	}
146
         	}
143
             foreach ($datetimeField as $key => $val) {
147
             foreach ($datetimeField as $key => $val) {
144
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
148
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;

+ 65
- 17
application/crm/model/Receivables.php Целия файл

45
 		$order_field = $request['order_field'];
45
 		$order_field = $request['order_field'];
46
     	$order_type = $request['order_type'];
46
     	$order_type = $request['order_type'];
47
         $getCount = $request['getCount'];
47
         $getCount = $request['getCount'];
48
+        $receivablesIdArray = $request['receivablesIdArray']; // 待办事项提醒参数
48
 		unset($request['scene_id']);
49
 		unset($request['scene_id']);
49
 		unset($request['search']);
50
 		unset($request['search']);
50
 		unset($request['user_id']);
51
 		unset($request['user_id']);
51
 		unset($request['order_field']);
52
 		unset($request['order_field']);
52
 		unset($request['order_type']);
53
 		unset($request['order_type']);
53
         unset($request['getCount']);
54
         unset($request['getCount']);
55
+        unset($request['receivablesIdArray']);
54
 
56
 
55
         $request = $this->fmtRequest( $request );
57
         $request = $this->fmtRequest( $request );
56
         $requestMap = $request['map'] ? : [];
58
         $requestMap = $request['map'] ? : [];
67
                 $sceneMap = $sceneModel->getDefaultData('crm_receivables', $user_id) ? : [];
69
                 $sceneMap = $sceneModel->getDefaultData('crm_receivables', $user_id) ? : [];
68
             }
70
             }
69
         }
71
         }
70
-		if ($search) {
71
-			//普通筛选
72
-			$sceneMap['number'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '回款编号'];
72
+        $searchWhere = [];
73
+		if (!empty($search) || $search == '0') {
74
+            //普通筛选
75
+            $searchWhere = function ($query) use ($search) {
76
+                $query->where(function ($query) use ($search){
77
+                    $query->whereLike('customer.name', '%' . $search . '%');
78
+                })->whereOr(function ($query) use ($search) {
79
+                    $query->whereLike('receivables.number', '%' . $search . '%');
80
+                });
81
+            };
82
+//            if (db('crm_customer')->whereLike('name', '%' . $search . '%')->value('customer_id')) {
83
+//                $sceneMap['customer_name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '客户名称'];
84
+//            } else {
85
+//                $sceneMap['number'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '回款编号'];
86
+//            }
73
 		}
87
 		}
74
 		//优先级:普通筛选>高级筛选>场景
88
 		//优先级:普通筛选>高级筛选>场景
75
 		$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
89
 		$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
99
 		$userField = $fieldModel->getFieldByFormType('crm_receivables', 'user');
113
 		$userField = $fieldModel->getFieldByFormType('crm_receivables', 'user');
100
 		$structureField = $fieldModel->getFieldByFormType('crm_receivables', 'structure');  //部门类型
114
 		$structureField = $fieldModel->getFieldByFormType('crm_receivables', 'structure');  //部门类型
101
         $datetimeField = $fieldModel->getFieldByFormType('crm_receivables', 'datetime'); //日期时间类型
115
         $datetimeField = $fieldModel->getFieldByFormType('crm_receivables', 'datetime'); //日期时间类型
102
-
103
-		if ($request['order_type'] && $request['order_field']) {
104
-			$order = $fieldModel->getOrderByFormtype('crm_receivables','receivables',$order_field,$order_type);
105
-		} else {
106
-			$order = 'receivables.update_time desc';
107
-		}
116
+        # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
117
+        $temporaryField = str_replace('_name', '', $order_field);
118
+        if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
119
+            $order_field = $temporaryField;
120
+        }
108
 		//排序
121
 		//排序
109
 		if ($order_type && $order_field) {
122
 		if ($order_type && $order_field) {
110
 			$order = $fieldModel->getOrderByFormtype('crm_receivables','receivables',$order_field, $order_type);
123
 			$order = $fieldModel->getOrderByFormtype('crm_receivables','receivables',$order_field, $order_type);
111
 		} else {
124
 		} else {
112
 			$order = 'receivables.update_time desc';
125
 			$order = 'receivables.update_time desc';
113
-		}		
126
+		}
127
+
128
+        # 待办事项查询参数
129
+        $dealtWhere = [];
130
+        if (!empty($receivablesIdArray)) $dealtWhere['receivables.receivables_id'] = ['in', $receivablesIdArray];
114
 
131
 
115
 		$readAuthIds = $userModel->getUserByPer('crm', 'receivables', 'read');
132
 		$readAuthIds = $userModel->getUserByPer('crm', 'receivables', 'read');
116
         $updateAuthIds = $userModel->getUserByPer('crm', 'receivables', 'update');
133
         $updateAuthIds = $userModel->getUserByPer('crm', 'receivables', 'update');
119
             ->alias('receivables')
136
             ->alias('receivables')
120
             ->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT')
137
             ->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT')
121
             ->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT')
138
             ->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT')
122
-            ->where($map)->where($authMap)->count('receivables_id');
139
+            ->where($searchWhere)->where($map)->where($authMap)->where($dealtWhere)->count('receivables_id');
123
         if (!empty($getCount) && $getCount == 1) {
140
         if (!empty($getCount) && $getCount == 1) {
124
             $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
141
             $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
125
             $data['extraData']['money'] = ['receivablesMoney' => $this->getReceivablesMoney($map, $authMap)];
142
             $data['extraData']['money'] = ['receivablesMoney' => $this->getReceivablesMoney($map, $authMap)];
131
 		$list = db('crm_receivables')
148
 		$list = db('crm_receivables')
132
 				->alias('receivables')
149
 				->alias('receivables')
133
 				->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT')		
150
 				->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT')		
134
-				->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT')		
151
+				->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT')
152
+                ->where($searchWhere)
135
 				->where($map)
153
 				->where($map)
136
 				->where($authMap)
154
 				->where($authMap)
155
+                ->where($dealtWhere)
137
         		->limit($request['offset'], $request['length'])
156
         		->limit($request['offset'], $request['length'])
138
 				->field('receivables.*,customer.name as customer_name,contract.name as contract_name,contract.num as contract_num,contract.money as contract_money')
157
 				->field('receivables.*,customer.name as customer_name,contract.name as contract_name,contract.num as contract_num,contract.money as contract_money')
139
 				->orderRaw($order)
158
 				->orderRaw($order)
151
         	$list[$k]['contract_id_info']['money'] = $v['contract_money'] ? : '0.00';
170
         	$list[$k]['contract_id_info']['money'] = $v['contract_money'] ? : '0.00';
152
         	$list[$k]['contract_money'] = $v['contract_money'] ? : '0.00';  
171
         	$list[$k]['contract_money'] = $v['contract_money'] ? : '0.00';  
153
 			foreach ($userField as $key => $val) {
172
 			foreach ($userField as $key => $val) {
154
-                $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
155
-                $list[$k][$val] = implode($usernameField, ',');
173
+                $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
174
+                $list[$k][$val.'_name'] = implode($usernameField, ',');
156
         	}
175
         	}
157
 			foreach ($structureField as $key => $val) {
176
 			foreach ($structureField as $key => $val) {
158
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
177
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
159
-                $list[$k][$val]     = implode($structureNameField, ',');
178
+                $list[$k][$val.'_name'] = implode($structureNameField, ',');
160
         	}
179
         	}
161
             foreach ($datetimeField as $key => $val) {
180
             foreach ($datetimeField as $key => $val) {
162
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
181
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
283
                 'create_user_id'   => $param['create_user_id'],
302
                 'create_user_id'   => $param['create_user_id'],
284
                 'update_time'      => time(),
303
                 'update_time'      => time(),
285
                 'create_time'      => time(),
304
                 'create_time'      => time(),
286
-                'customer_ids'     => $param['customer_id'],
287
-                'contract_ids'     => $param['contract_id']
305
+                'customer_ids'     => ',' . $param['customer_id'] . ',',
306
+                'contract_ids'     => ',' . $param['contract_id'] . ','
288
             ]);
307
             ]);
289
 
308
 
309
+            # 创建待办事项的关联数据
310
+            $checkUserIds = db('crm_receivables')->where('receivables_id', $data['receivables_id'])->value('check_user_id');
311
+            $checkUserIdArray = stringToArray($checkUserIds);
312
+            $dealtData = [];
313
+            foreach ($checkUserIdArray AS $kk => $vv) {
314
+                $dealtData[] = [
315
+                    'types'    => 'crm_receivables',
316
+                    'types_id' => $data['receivables_id'],
317
+                    'user_id'  => $vv
318
+                ];
319
+            }
320
+            if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
321
+
290
 			return $data;
322
 			return $data;
291
 		} else {
323
 		} else {
292
 			$this->error = '添加失败';
324
 			$this->error = '添加失败';
376
 
408
 
377
 			$data = [];
409
 			$data = [];
378
 			$data['receivables_id'] = $receivables_id;
410
 			$data['receivables_id'] = $receivables_id;
411
+
412
+            # 删除待办事项的关联数据
413
+            db('crm_dealt_relation')->where(['types' => ['eq', 'crm_receivables'], 'types_id' => ['eq', $data['receivables_id']]])->delete();
414
+            # 创建待办事项的关联数据
415
+            $checkUserIds = db('crm_receivables')->where('receivables_id', $data['receivables_id'])->value('check_user_id');
416
+            $checkUserIdArray = stringToArray($checkUserIds);
417
+            $dealtData = [];
418
+            foreach ($checkUserIdArray AS $kk => $vv) {
419
+                $dealtData[] = [
420
+                    'types'    => 'crm_receivables',
421
+                    'types_id' => $data['receivables_id'],
422
+                    'user_id'  => $vv
423
+                ];
424
+            }
425
+            if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
426
+
379
 			return $data;
427
 			return $data;
380
 		} else {
428
 		} else {
381
 			$this->error = '编辑失败';
429
 			$this->error = '编辑失败';

+ 19
- 9
application/crm/model/ReceivablesPlan.php Целия файл

33
      * @return    [array]                    [description]
33
      * @return    [array]                    [description]
34
      */		
34
      */		
35
 	public function getDataList($request)
35
 	public function getDataList($request)
36
-    {  	
36
+    {
37
     	$userModel = new \app\admin\model\User();
37
     	$userModel = new \app\admin\model\User();
38
 		$search = $request['search'];
38
 		$search = $request['search'];
39
     	$user_id = $request['user_id'];
39
     	$user_id = $request['user_id'];
42
     	$types = $request['types'];
42
     	$types = $request['types'];
43
         $getCount = $request['getCount'];
43
         $getCount = $request['getCount'];
44
         $status = isset($request['status']) ? $request['status'] : 1;
44
         $status = isset($request['status']) ? $request['status'] : 1;
45
+        $dealt = $request['dealt']; # 待办事项
45
 		unset($request['scene_id']);
46
 		unset($request['scene_id']);
46
 		unset($request['search']);
47
 		unset($request['search']);
47
 		unset($request['user_id']);	    	
48
 		unset($request['user_id']);	    	
49
 		unset($request['types']);
50
 		unset($request['types']);
50
         unset($request['getCount']);
51
         unset($request['getCount']);
51
         unset($request['status']);
52
         unset($request['status']);
53
+        unset($request['dealt']);
52
 
54
 
53
         $request = $this->fmtRequest( $request );
55
         $request = $this->fmtRequest( $request );
54
         $map = $request['map'] ? : [];
56
         $map = $request['map'] ? : [];
81
 		// @ymob 2019-12-11 17:51:54
83
 		// @ymob 2019-12-11 17:51:54
82
 		// 修改回款时,回款计划选项列表应该包含该回款对应的回款计划 不能过滤
84
 		// 修改回款时,回款计划选项列表应该包含该回款对应的回款计划 不能过滤
83
 		// 将types改为status,status:可用的回款计划 fanqi
85
 		// 将types改为status,status:可用的回款计划 fanqi
84
-		if ($request['map']['receivables_id']) {
85
-		    if (!empty($request['map']['contract_id'])) {
86
-                $map = " 
86
+        if (empty($dealt)) { # 不是待办事项
87
+            if ($request['map']['receivables_id']) {
88
+                if (!empty($request['map']['contract_id'])) {
89
+                    $map = " 
87
                     (`receivables_plan`.`contract_id` = {$request['map']['contract_id']} AND `receivables_plan`.`receivables_id` = {$request['map']['receivables_id']}) 
90
                     (`receivables_plan`.`contract_id` = {$request['map']['contract_id']} AND `receivables_plan`.`receivables_id` = {$request['map']['receivables_id']}) 
88
                     OR 
91
                     OR 
89
                     (`receivables_plan`.`contract_id` = {$request['map']['contract_id']} AND `receivables_plan`.`receivables_id` = 0)
92
                     (`receivables_plan`.`contract_id` = {$request['map']['contract_id']} AND `receivables_plan`.`receivables_id` = 0)
90
                 ";
93
                 ";
91
-            } else {
92
-                $map = " (`receivables_plan`.`receivables_id` = 0 )";
94
+                } else {
95
+                    $map = " (`receivables_plan`.`receivables_id` = 0 )";
96
+                }
97
+            } elseif ($status == 0) {
98
+                $map['receivables_plan.receivables_id'] = 0;
93
             }
99
             }
94
-		} elseif ($status == 0) {
95
-			$map['receivables_plan.receivables_id'] = 0;
96
-		}
100
+        }
101
+
102
+        # 待办事项-待回款提醒-已回款
103
+        if (!empty($dealt)) {
104
+            $map = " (`receivables_plan`.`receivables_id` > ".$request['map']['receivables_id'][1]." )";
105
+        }
106
+
97
 
107
 
98
         $dataCount = db('crm_receivables_plan')
108
         $dataCount = db('crm_receivables_plan')
99
             ->alias('receivables_plan')
109
             ->alias('receivables_plan')

+ 25
- 1
application/crm/traits/AutoNumberTrait.php Целия файл

29
         $number = '';
29
         $number = '';
30
         $data   = [];
30
         $data   = [];
31
 
31
 
32
-        $info = Db::name('crm_number_sequence')->where('number_type', $type)->where('status', 0)->select();
32
+        # 根据设置重置编号(不想改下面的代码,在这里在写一个,多公海版本出来后,用定时来做)
33
+        $list = Db::name('crm_number_sequence')->where('number_type', $type)->where('status', 0)->select();
34
+        foreach ($list AS $key => $value) {
35
+            if ($value['type'] == 3 && $value['reset'] != 0) {
36
+                # 1:每天;2:每月;3:每年;
37
+                $currentDate = [
38
+                    1 => date('Y-m-d'),
39
+                    2 => date('Y-m'),
40
+                    3 => date('Y')
41
+                ];
42
+                $lastDate = [
43
+                    1 => date('Y-m-d', $value['last_date']),
44
+                    2 => date('Y-m',   $value['last_date']),
45
+                    3 => date('Y',     $value['last_date'])
46
+                ];
47
+                
48
+                if ($currentDate[$value['reset']] != $lastDate[$value['reset']]) {
49
+                    Db::name('crm_number_sequence')->where('number_sequence_id', $value['number_sequence_id'])->update([
50
+                        'last_number' => 1
51
+                    ]);
52
+                }
53
+            }
54
+        }
55
+
56
+        $info = Db::name('crm_number_sequence')->where('number_type', $type)->order('sort', 'asc')->where('status', 0)->select();
33
 
57
 
34
         foreach ($info AS $key => $value) {
58
         foreach ($info AS $key => $value) {
35
             # 文本
59
             # 文本

+ 153
- 0
application/crm/traits/SearchConditionTrait.php Целия файл

1
+<?php
2
+/**
3
+ * 客户模块查询条件
4
+ *
5
+ * @author fanqi
6
+ * @date 2021-03-09
7
+ */
8
+
9
+namespace app\crm\traits;
10
+
11
+trait SearchConditionTrait
12
+{
13
+    /**
14
+     * 联系人tab列表查询条件(权限)
15
+     *
16
+     * @param $userId 当前登录ID
17
+     * @author fanqi
18
+     * @date 2021-03-09
19
+     * @return \Closure
20
+     */
21
+    public function getContactsSearchWhere($userId)
22
+    {
23
+        $userModel = new \app\admin\model\User();
24
+
25
+        $authUserIds = $userModel->getUserByPer('crm', 'contacts', 'index');
26
+
27
+        $authMapData['auth_user_ids'] = $authUserIds;
28
+        $authMapData['user_id']       = $userId;
29
+
30
+        return $this->getSearchAuthWhere($authMapData);
31
+    }
32
+
33
+    /**
34
+     * 商机tab列表查询条件(权限)
35
+     *
36
+     * @param $userId 当前登录ID
37
+     * @author fanqi
38
+     * @date 2021-03-09
39
+     * @return \Closure
40
+     */
41
+    public function getBusinessSearchWhere($userId)
42
+    {
43
+        $userModel = new \app\admin\model\User();
44
+
45
+        $authUserIds = $userModel->getUserByPer('crm', 'business', 'index');
46
+
47
+        $authMapData['auth_user_ids'] = $authUserIds;
48
+        $authMapData['user_id']       = $userId;
49
+
50
+        return $this->getSearchAuthWhere($authMapData);
51
+    }
52
+
53
+    /**
54
+     * 合同tab列表查询条件(权限)
55
+     *
56
+     * @param $userId 当前登录ID
57
+     * @author fanqi
58
+     * @date 2021-03-09
59
+     * @return \Closure
60
+     */
61
+    public function getContractSearchWhere($userId)
62
+    {
63
+        $userModel = new \app\admin\model\User();
64
+
65
+        $authUserIds = $userModel->getUserByPer('crm', 'contract', 'index');
66
+
67
+        $authMapData['auth_user_ids'] = $authUserIds;
68
+        $authMapData['user_id']       = $userId;
69
+
70
+        return $this->getSearchAuthWhere($authMapData);
71
+    }
72
+
73
+    /**
74
+     * 回访tab列表查询条件(权限)
75
+     *
76
+     * @param $userId
77
+     * @author fanqi
78
+     * @date 2021-03-09
79
+     * @return \Closure
80
+     */
81
+    public function getVisitSearchWhere($userId)
82
+    {
83
+        $userModel = new \app\admin\model\User();
84
+
85
+        $authUserIds = $userModel->getUserByPer('crm', 'visit', 'index');
86
+
87
+        $authMapData['auth_user_ids'] = $authUserIds;
88
+        $authMapData['user_id']       = $userId;
89
+
90
+        return $this->getSearchAuthWhere($authMapData);
91
+    }
92
+
93
+    /**
94
+     * 回款tab列表查询条件(权限)
95
+     *
96
+     * @author fanqi
97
+     * @date 2021-03-10
98
+     * @return array[]
99
+     */
100
+    public function getReceivablesSearchWhere()
101
+    {
102
+        $userModel = new \app\admin\model\User();
103
+
104
+        return $userModel->getUserByPer('crm', 'receivables', 'index');
105
+    }
106
+
107
+    /**
108
+     * 发票tab列表查询条件
109
+     *
110
+     * @author fanqi
111
+     * @date 2021-03-11
112
+     * @return array|false|string
113
+     */
114
+    public function getInvoiceSearchWhere()
115
+    {
116
+        $userModel = new \app\admin\model\User();
117
+
118
+        return $userModel->getUserByPer('crm', 'invoice', 'index');
119
+    }
120
+
121
+    /**
122
+     * 产品tab列表查询条件
123
+     *
124
+     * @author fanqi
125
+     * @date 2021-03-11
126
+     * @return array|false|string
127
+     */
128
+    public function getProductSearchWhere()
129
+    {
130
+        $userModel = new \app\admin\model\User();
131
+
132
+        return $userModel->getUserByPer('crm', 'product', 'index');
133
+    }
134
+
135
+    /**
136
+     * 查询权限条件
137
+     *
138
+     * @param $authMapData 权限范围内的ID
139
+     * @return \Closure
140
+     */
141
+    private function getSearchAuthWhere($authMapData)
142
+    {
143
+        return function($query) use ($authMapData) {
144
+            $query->where(['owner_user_id' => ['in', $authMapData['auth_user_ids']]])
145
+                ->whereOr(function ($query) use ($authMapData) {
146
+                    $query->where('FIND_IN_SET("'.$authMapData['user_id'].'", ro_user_id)')->where(['owner_user_id' => ['neq', '']]);
147
+                })
148
+                ->whereOr(function ($query) use ($authMapData) {
149
+                    $query->where('FIND_IN_SET("'.$authMapData['user_id'].'", rw_user_id)')->where(['owner_user_id' => ['neq', '']]);
150
+                });
151
+        };
152
+    }
153
+}

+ 19
- 0
application/oa/controller/Task.php Целия файл

380
         }
380
         }
381
         $taskInfo = Db::name('Task')->where(['task_id' => $param['task_id']])->find();
381
         $taskInfo = Db::name('Task')->where(['task_id' => $param['task_id']])->find();
382
         $det = Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->find();
382
         $det = Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->find();
383
+        $activityUpdate = [];
383
         if ($param['type'] == '1') {
384
         if ($param['type'] == '1') {
384
             $newstr = str_replace(',' . $param['id'] . ',', ',', $det['customer_ids']);
385
             $newstr = str_replace(',' . $param['id'] . ',', ',', $det['customer_ids']);
385
             $newdata['customer_ids'] = $newstr;
386
             $newdata['customer_ids'] = $newstr;
387
+            # 删除活动关联
388
+            $customerIds = db('crm_activity')->where(['activity_type' => 11, 'activity_type_id' => $param['task_id']])->value('customer_ids');
389
+            $activityUpdate['customer_ids'] = str_replace(',' . $param['id'] . ',', ',', $customerIds);
390
+            if ($activityUpdate['customer_ids'] == ',') $activityUpdate['customer_ids'] = '';
386
         } elseif ($param['type'] == '2') {
391
         } elseif ($param['type'] == '2') {
387
             $newstr = str_replace(',' . $param['id'] . ',', ',', $det['contacts_ids']);
392
             $newstr = str_replace(',' . $param['id'] . ',', ',', $det['contacts_ids']);
388
             $newdata['contacts_ids'] = $newstr;
393
             $newdata['contacts_ids'] = $newstr;
394
+            # 删除活动关联
395
+            $contactsIds = db('crm_activity')->where(['activity_type' => 11, 'activity_type_id' => $param['task_id']])->value('contacts_ids');
396
+            $activityUpdate['contacts_ids'] = str_replace(',' . $param['id'] . ',', ',', $contactsIds);
397
+            if ($activityUpdate['contacts_ids'] == ',') $activityUpdate['contacts_ids'] = '';
389
         } elseif ($param['type'] == '3') {
398
         } elseif ($param['type'] == '3') {
390
             $newstr = str_replace(',' . $param['id'] . ',', ',', $det['business_ids']);
399
             $newstr = str_replace(',' . $param['id'] . ',', ',', $det['business_ids']);
391
             $newdata['business_ids'] = $newstr;
400
             $newdata['business_ids'] = $newstr;
401
+            # 删除活动关联
402
+            $businessIds = db('crm_activity')->where(['activity_type' => 11, 'activity_type_id' => $param['task_id']])->value('business_ids');
403
+            $activityUpdate['business_ids'] = str_replace(',' . $param['id'] . ',', ',', $businessIds);
404
+            if ($activityUpdate['business_ids'] == ',') $activityUpdate['business_ids'] = '';
392
         } elseif ($param['type'] == '4') {
405
         } elseif ($param['type'] == '4') {
393
             $newstr = str_replace(',' . $param['id'] . ',', ',', $det['contract_ids']);
406
             $newstr = str_replace(',' . $param['id'] . ',', ',', $det['contract_ids']);
394
             $newdata['contract_ids'] = $newstr;
407
             $newdata['contract_ids'] = $newstr;
408
+            # 删除活动关联
409
+            $contractIds = db('crm_activity')->where(['activity_type' => 11, 'activity_type_id' => $param['task_id']])->value('contract_ids');
410
+            $activityUpdate['contract_ids'] = str_replace(',' . $param['id'] . ',', ',', $contractIds);
411
+            if ($activityUpdate['contract_ids'] == ',') $activityUpdate['contract_ids'] = '';
395
         }
412
         }
396
         $flag = Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->update($newdata);
413
         $flag = Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->update($newdata);
414
+        # 取消活动关联
415
+        db('crm_activity')->where(['activity_type' => 11, 'activity_type_id' => $param['task_id']])->update($activityUpdate);
397
         if ($flag) {
416
         if ($flag) {
398
             if (!$taskInfo['pid']) {
417
             if (!$taskInfo['pid']) {
399
                 actionLog($taskInfo['task_id'], $taskInfo['owner_user_id'], $taskInfo['structure_ids'], '编辑关联关系');
418
                 actionLog($taskInfo['task_id'], $taskInfo['owner_user_id'], $taskInfo['structure_ids'], '编辑关联关系');

+ 18
- 2
application/oa/logic/LogLogic.php Целия файл

242
         $between_time = [$start_time['start_time'], $start_time['end_time']];
242
         $between_time = [$start_time['start_time'], $start_time['end_time']];
243
         $map['owner_user_id'] = $user_id;
243
         $map['owner_user_id'] = $user_id;
244
         $map['create_time'] = array('between', $between_time);
244
         $map['create_time'] = array('between', $between_time);
245
+        $map1['update_time'] = array('between', $between_time);
245
         $customerNum = Db::name('CrmCustomer')
246
         $customerNum = Db::name('CrmCustomer')
246
-            ->where($map)
247
+            ->where($map1)
247
             ->count();
248
             ->count();
248
         $businessNum = Db::name('CrmBusiness')
249
         $businessNum = Db::name('CrmBusiness')
249
             ->where($map)
250
             ->where($map)
307
         switch ($type) {
308
         switch ($type) {
308
             case '1':
309
             case '1':
309
                 if ($search) $map['customer.name'] = array('like', '%' . $search . '%');
310
                 if ($search) $map['customer.name'] = array('like', '%' . $search . '%');
310
-                $map['customer.create_time'] = array('between', $between_time);
311
+                $map['customer.update_time'] = array('between', $between_time);
311
                 $activityData = Db::name('CrmCustomer')
312
                 $activityData = Db::name('CrmCustomer')
312
                     ->alias('customer')
313
                     ->alias('customer')
313
                     ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
314
                     ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
316
                     ->where($customerMap)
317
                     ->where($customerMap)
317
                     ->order('customer.customer_id desc')
318
                     ->order('customer.customer_id desc')
318
                     ->field('customer.customer_id,customer.name,customer.deal_status,customer.create_time,user.realname as owner_user_name,customer.last_time')
319
                     ->field('customer.customer_id,customer.name,customer.deal_status,customer.create_time,user.realname as owner_user_name,customer.last_time')
320
+                    ->page($param['page'],$param['limit'])
319
                     ->select();
321
                     ->select();
320
                 $dataCount = Db::name('CrmCustomer')
322
                 $dataCount = Db::name('CrmCustomer')
321
                     ->alias('customer')
323
                     ->alias('customer')
335
                     ->where($map)
337
                     ->where($map)
336
                     ->where($map2)
338
                     ->where($map2)
337
                     ->order('business.business_id desc')
339
                     ->order('business.business_id desc')
340
+                    ->page($param['page'],$param['limit'])
338
                     ->field('business.business_id,business.name,status.name as status_name,business.create_time,user.realname as owner_user_name,business.last_time')
341
                     ->field('business.business_id,business.name,status.name as status_name,business.create_time,user.realname as owner_user_name,business.last_time')
339
                     ->select();
342
                     ->select();
340
                 $dataCount = Db::name('CrmBusiness')
343
                 $dataCount = Db::name('CrmBusiness')
354
                     ->where($map)
357
                     ->where($map)
355
                     ->where($map3)
358
                     ->where($map3)
356
                     ->order('contract.contract_id desc')
359
                     ->order('contract.contract_id desc')
360
+                    ->page($param['page'],$param['limit'])
357
                     ->field('contract.contract_id,contract.name,contract.create_time,contract.check_status,u.realname as order_user_name')
361
                     ->field('contract.contract_id,contract.name,contract.create_time,contract.check_status,u.realname as order_user_name')
358
                     ->select();
362
                     ->select();
359
                 $dataCount = Db::name('CrmContract')
363
                 $dataCount = Db::name('CrmContract')
372
                     ->field('receivables.receivables_id,receivables.number,receivables.return_time,user.realname as owner_user_name')
376
                     ->field('receivables.receivables_id,receivables.number,receivables.return_time,user.realname as owner_user_name')
373
                     ->where($map)
377
                     ->where($map)
374
                     ->where($map4)
378
                     ->where($map4)
379
+                    ->page($param['page'],$param['limit'])
375
                     ->order('receivables.receivables_id desc')
380
                     ->order('receivables.receivables_id desc')
376
                     ->select();
381
                     ->select();
377
                 $dataCount = Db::name('CrmReceivables')
382
                 $dataCount = Db::name('CrmReceivables')
929
                 $imgList[] = $val;
934
                 $imgList[] = $val;
930
             }
935
             }
931
         }
936
         }
937
+        $is_update = 0;
938
+        $is_delete = 0;
939
+        //创建人或负责人或管理员有撤销权限
940
+        if ($item['create_user_id'] == $param['user_id']) {
941
+            $is_update = 1;
942
+            $is_delete = 1;
943
+        }
932
         $param['type_id'] = $item['log_id'];
944
         $param['type_id'] = $item['log_id'];
933
         $param['type'] = 'oa_log';
945
         $param['type'] = 'oa_log';
934
         $item['replyList'] = $commonModel->read($param);
946
         $item['replyList'] = $commonModel->read($param);
935
         $item['fileList'] = $fileList ?: [];
947
         $item['fileList'] = $fileList ?: [];
936
         $item['imgList'] = $imgList ?: [];
948
         $item['imgList'] = $imgList ?: [];
949
+      
950
+        $permission['is_delete'] = $is_update;
951
+        $permission['is_update'] = $is_delete;
952
+        $item['permission'] = $permission;
937
         //相关业务
953
         //相关业务
938
         $relationArr = $recordModel->getListByRelationId('log', $item['log_id']);
954
         $relationArr = $recordModel->getListByRelationId('log', $item['log_id']);
939
         $item['businessList'] = $relationArr['businessList'];
955
         $item['businessList'] = $relationArr['businessList'];

+ 75
- 34
application/oa/logic/TaskLogic.php Целия файл

16
         $taskModel = new TaskModel();
16
         $taskModel = new TaskModel();
17
         $recordModel = new \app\admin\model\Record();
17
         $recordModel = new \app\admin\model\Record();
18
         $str = ',' . $param['user_id'] . ',';
18
         $str = ',' . $param['user_id'] . ',';
19
-        
20
         //自定义时间
19
         //自定义时间
21
         $map['t.stop_time'] = $param['dueDate'] ? strtotime($param['dueDate'] . ' +1 month -1 day') : ['>=', 0];
20
         $map['t.stop_time'] = $param['dueDate'] ? strtotime($param['dueDate'] . ' +1 month -1 day') : ['>=', 0];
22
         $search = $param['search'];
21
         $search = $param['search'];
35
             $where['t.status'] = [['=', 1], ['=', 5], 'OR'];
34
             $where['t.status'] = [['=', 1], ['=', 5], 'OR'];
36
         }
35
         }
37
         
36
         
38
-        if ($param['main_user_id']) {
39
-            $where['t.main_user_id'] = $param['main_user_id'];
40
-        }
41
         //项目id
37
         //项目id
42
         $priority = ($param['priority'] || $param['priority'] == '0') ? $param['priority'] : ['in', [0, 1, 2, 3]];
38
         $priority = ($param['priority'] || $param['priority'] == '0') ? $param['priority'] : ['in', [0, 1, 2, 3]];
43
         $where['t.priority'] = $priority;
39
         $where['t.priority'] = $priority;
44
         
40
         
45
-        if ($param['work_id'] != 0) {
46
-            $where['t.work_id'] = $param['work_id'];
41
+        if (!empty($param['work_id'])) {
42
+            $where = [];
43
+            $where['ishidden'] = 0;
44
+            $where['pid'] = 0;
45
+            $where['work_id'] = $param['work_id'];
46
+            if (!empty($param['search'])) {
47
+                $taskSearch = ' (task.name like "%' . $param['search'] . '%" OR task.description like "%' . $param['search'] . '%")';
48
+            }
49
+            # 成员
50
+            if (!empty($param['owner_user_id']) && is_array($param['owner_user_id'])) {
51
+                $whereStr = '';
52
+                foreach ($param['owner_user_id'] as $key => $value) {
53
+                    $whereStr .= '(  task.owner_user_id like "%,' . $value . ',%") OR ';
54
+                }
55
+                if (!empty($whereStr)) $whereStr = '(' . rtrim($whereStr, 'OR ') . ')';
56
+            }
57
+            # 截止日期
58
+            $timeWhere = $this->getTimeParam($param['time_type']);
59
+            # 标签
60
+            $labelWhere = '';
61
+            if (!empty($param['label_id']) && is_array($param['label_id'])) {
62
+                foreach ($param['label_id'] as $key => $value) {
63
+                    $labelWhere .= '(  task.lable_id like "%,' . $value . ',%") OR ';
64
+                }
65
+                if (!empty($labelWhere)) $labelWhere = '(' . rtrim($labelWhere, 'OR ') . ')';
66
+            }
67
+            if ($param['owner_user_id']) {
68
+                foreach ($param['owner_user_id'] as $key => $value) {
69
+                    $logWhere.= '( task.owner_user_id like "%,' . $value . ',%") OR ';
70
+                }
71
+                if (!empty($logWhere)) $logWhere = '(' . rtrim($logWhere, 'OR ') . ')';
72
+            }
47
             $taskList = db('task')
73
             $taskList = db('task')
48
-                ->alias('t')
49
-                ->join('AdminUser u', 'u.id = t.main_user_id', 'LEFT')
50
-                ->field('t.task_id,t.name as task_name,t.main_user_id,t.description,t.priority,t.stop_time,t.create_time,t.owner_user_id,t.start_time,t.create_user_id,u.realname as main_user_name,t.class_id')
74
+                ->alias('task')
75
+                ->join('AdminUser u', 'u.id = task.main_user_id', 'LEFT')
76
+                ->field('task.task_id,task.name as task_name,task.main_user_id,task.description,task.priority,task.stop_time,task.create_time,task.owner_user_id,
77
+                    task.start_time,task.create_user_id,u.realname as main_user_name,task.class_id,task.work_id,task.lable_id')
51
                 ->where($where)
78
                 ->where($where)
52
-                ->order('t.task_id desc')
79
+                ->where($timeWhere)
80
+                ->where($labelWhere)
81
+                ->where($whereStr)
82
+                ->where($labelWhere)
83
+                ->where($taskSearch)
84
+                ->order('task.task_id desc')
53
                 ->select();
85
                 ->select();
54
         } else {
86
         } else {
55
-            if ($param['is_top'] == 5) {
87
+            if ($param['is_top'] > 0 ) {
56
                 $where = [];
88
                 $where = [];
57
                 $where['ishidden'] = 0;
89
                 $where['ishidden'] = 0;
58
                 $where['pid'] = 0;
90
                 $where['pid'] = 0;
59
-                $where['whereStr'] = ' ( task.create_user_id =' . $param['user_id'] . ' or (  task.owner_user_id like "%,' . $param['user_id'] . ',%") or ( task.main_user_id = ' . $param['user_id'] . ' ) )';
60
                 if (!empty($this->param['search'])) {
91
                 if (!empty($this->param['search'])) {
61
-                    $where['taskSearch'] = ' and (task.name like "%' . $this->param['search'] . '%" OR task.description like "%' . $this->param['search'] . '%")';
92
+                    $taskSearch = ' (task.name like "%' . $this->param['search'] . '%" OR task.description like "%' . $this->param['search'] . '%")';
93
+                }
94
+                # 成员
95
+                if (!empty($param['owner_user_id']) && is_array($param['owner_user_id'])) {
96
+                    $whereStr = '';
97
+                    foreach ($param['owner_user_id'] as $key => $value) {
98
+                        $whereStr .= '(  task.owner_user_id like "%,' . $value . ',%") OR ';
99
+                    }
100
+                    if (!empty($whereStr)) $whereStr = '(' . rtrim($whereStr, 'OR ') . ')';
62
                 }
101
                 }
63
                 # 截止日期
102
                 # 截止日期
64
                 $timeWhere = $this->getTimeParam($param['time_type']);
103
                 $timeWhere = $this->getTimeParam($param['time_type']);
70
                     }
109
                     }
71
                     if (!empty($labelWhere)) $labelWhere = '(' . rtrim($labelWhere, 'OR ') . ')';
110
                     if (!empty($labelWhere)) $labelWhere = '(' . rtrim($labelWhere, 'OR ') . ')';
72
                 }
111
                 }
73
-                $where = $this->where($param);
74
                 $taskList = db('task')
112
                 $taskList = db('task')
75
-                    ->alias('t')
76
-                    ->join('AdminUser u', 'u.id = t.main_user_id', 'LEFT')
77
-                    ->field('t.task_id,t.name as task_name,t.main_user_id,t.description,t.priority,t.stop_time,t.create_time,t.owner_user_id,t.start_time,t.create_user_id,u.realname as main_user_name,t.is_top')
113
+                    ->alias('task')
114
+                    ->join('AdminUser u', 'u.id = task.main_user_id', 'LEFT')
115
+                    ->field('task.task_id,task.name as task_name,task.main_user_id,task.description,task.priority,task.stop_time,task.create_time,task.owner_user_id,
116
+                    task.start_time,task.create_user_id,u.realname as main_user_name,task.is_top')
78
                     ->where($where)
117
                     ->where($where)
79
                     ->where($timeWhere)
118
                     ->where($timeWhere)
80
                     ->where($labelWhere)
119
                     ->where($labelWhere)
81
-                    ->order('t.task_id desc')
120
+                    ->where($whereStr)
121
+                    ->where($taskSearch)
122
+                    ->where($labelWhere)
123
+                    ->order('task.task_id desc')
82
                     ->select();
124
                     ->select();
83
-                
84
             } else {
125
             } else {
85
                 ///下属任务
126
                 ///下属任务
86
                 if ($param['mold'] == 1) {
127
                 if ($param['mold'] == 1) {
127
                         ->select();
168
                         ->select();
128
                 } else {
169
                 } else {
129
                     $map['t.pid'] = 0;
170
                     $map['t.pid'] = 0;
130
-                    // $map['t.work_id'] = 0;
131
                     if ($type != 0) {
171
                     if ($type != 0) {
132
                         switch ($type) {
172
                         switch ($type) {
133
                             case '1' :
173
                             case '1' :
162
             $taskList[$key]['work'] = '';
202
             $taskList[$key]['work'] = '';
163
             if ($param['work_id'] != 0) {
203
             if ($param['work_id'] != 0) {
164
                 $work = db('work_task_class')->where('class_id', $value['class_id'])->find();
204
                 $work = db('work_task_class')->where('class_id', $value['class_id'])->find();
165
-                $taskList[$key]['work'] = $work['name'];
205
+                $taskList[$key]['work'] = $work['name']?:'未分组';
166
             }
206
             }
167
             if ($param['is_top'] != 0) {
207
             if ($param['is_top'] != 0) {
168
                 switch ($value['is_top']) {
208
                 switch ($value['is_top']) {
207
             $relationArr = $recordModel->getListByRelationId('task', $value['task_id']);
247
             $relationArr = $recordModel->getListByRelationId('task', $value['task_id']);
208
             $lableArr = $recordModel->getListByLableId('task', $value['task_id']);
248
             $lableArr = $recordModel->getListByLableId('task', $value['task_id']);
209
             $taskList[$key]['owner_user_name'] = arrayToString(array_column($userModel->getListByStr($value['owner_user_id']), 'realname'));
249
             $taskList[$key]['owner_user_name'] = arrayToString(array_column($userModel->getListByStr($value['owner_user_id']), 'realname'));
210
-            $taskList[$key]['work_name'] = arrayToString(array_column($lableArr['lable'], 'name')) . ' ';
211
-            $taskList[$key]['relation'] = arrayToString(array_column($relationArr['businessList'], 'name')) . ' ' .
250
+            $taskList[$key]['owner_user_name'] = trim($taskList[$key]['owner_user_name'],',');
251
+            $taskList[$key]['work_name'] = trim(arrayToString(array_column($lableArr['lable'], 'name')),','). ' ';
252
+            $taskList[$key]['relation'] = trim(arrayToString(array_column($relationArr['businessList'], 'name')) . ' ' .
212
                 arrayToString(array_column($relationArr['contactsList'], 'name')) . ' ' .
253
                 arrayToString(array_column($relationArr['contactsList'], 'name')) . ' ' .
213
                 arrayToString(array_column($relationArr['contractList'], 'name')) . ' ' .
254
                 arrayToString(array_column($relationArr['contractList'], 'name')) . ' ' .
214
-                arrayToString(array_column($relationArr['customerList'], 'name'));
255
+                arrayToString(array_column($relationArr['customerList'], 'name')),',');
215
         }
256
         }
216
         return $taskList;
257
         return $taskList;
217
     }
258
     }
222
      */
263
      */
223
     public function excelExport($param)
264
     public function excelExport($param)
224
     {
265
     {
225
-        
226
         $data = $this->getDataList($param);
266
         $data = $this->getDataList($param);
267
+        p($data);
227
         $excelModel = new \app\admin\model\Excel();
268
         $excelModel = new \app\admin\model\Excel();
228
         if ($param['work_id'] != 0) {
269
         if ($param['work_id'] != 0) {
229
             $file_name = 'work_task';
270
             $file_name = 'work_task';
289
         $work_id = $param['work_id'] ?: '';
330
         $work_id = $param['work_id'] ?: '';
290
         
331
         
291
         if ($param['main_user_id']) {
332
         if ($param['main_user_id']) {
292
-            $map['t.main_user_id'] = ['in', $param['main_user_id']];
333
+            $map['task.main_user_id'] = ['in', $param['main_user_id']];
293
         }
334
         }
294
-        
335
+       
295
         //截止时间
336
         //截止时间
296
         if ($param['stop_time_type']) {
337
         if ($param['stop_time_type']) {
297
             if ($param['stop_time_type'] == '5') { //没有截至日期
338
             if ($param['stop_time_type'] == '5') { //没有截至日期
298
-                $map['t.stop_time'] = '0';
339
+                $map['task.stop_time'] = '0';
299
             } elseif ($param['stop_time_type'] == '6') { //延期的
340
             } elseif ($param['stop_time_type'] == '6') { //延期的
300
-                $map['t.stop_time'] = ['between', [1, time()]];
301
-                $map['t.status'] = 1;
341
+                $map['task.stop_time'] = ['between', [1, time()]];
342
+                $map['task.status'] = 1;
302
             } elseif ($param['stop_time_type'] == '7') { //今日更新
343
             } elseif ($param['stop_time_type'] == '7') { //今日更新
303
                 $timeAry = getTimeByType('today');
344
                 $timeAry = getTimeByType('today');
304
-                $map['t.update_time'] = ['between', [$timeAry[0], $timeAry[1]]];
345
+                $map['task.update_time'] = ['between', [$timeAry[0], $timeAry[1]]];
305
             } else {
346
             } else {
306
                 switch ($param['stop_time_type']) {
347
                 switch ($param['stop_time_type']) {
307
                     case '1': //今天到期
348
                     case '1': //今天到期
321
                     default:
362
                     default:
322
                         break;
363
                         break;
323
                 }
364
                 }
324
-                $map['t.stop_time'] = ['between', [$timeAry[0], $timeAry[1]]];
365
+                $map['task.stop_time'] = ['between', [$timeAry[0], $timeAry[1]]];
325
             }
366
             }
326
         }
367
         }
327
         
368
         
345
                     $task_ids = $task_id;
386
                     $task_ids = $task_id;
346
                 }
387
                 }
347
             }
388
             }
348
-            $map['t.task_id'] = ['in', $task_ids];
389
+            $map['task.task_id'] = ['in', $task_ids];
349
         } else {
390
         } else {
350
             
391
             
351
-            $map['t.task_id'] = $work_id;
392
+            $map['task.task_id'] = $work_id;
352
         }
393
         }
353
         return $map;
394
         return $map;
354
     }
395
     }

+ 1
- 0
application/oa/model/Announcement.php Целия файл

203
 		}
203
 		}
204
 		$userModel = new \app\admin\model\User();
204
 		$userModel = new \app\admin\model\User();
205
 		$dataInfo['create_user_info'] = $userModel->getUserById($dataInfo['create_user_id']);
205
 		$dataInfo['create_user_info'] = $userModel->getUserById($dataInfo['create_user_id']);
206
+        $dataInfo['create_time'] = $dataInfo['create_time']?date('Y-m-d H:i:s',$dataInfo['create_time']):null;
206
 		$structureModel = new \app\admin\model\Structure();
207
 		$structureModel = new \app\admin\model\Structure();
207
 		$dataInfo['structureList'] = $structureModel->getDataByStr($dataInfo['structure_ids'])?:array();
208
 		$dataInfo['structureList'] = $structureModel->getDataByStr($dataInfo['structure_ids'])?:array();
208
 		$dataInfo['announcement_id'] = $announcement_id;
209
 		$dataInfo['announcement_id'] = $announcement_id;

+ 1
- 0
application/oa/model/Event.php Целия файл

631
         foreach ($event_date as $k => $v) {
631
         foreach ($event_date as $k => $v) {
632
             $event_date[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : null;
632
             $event_date[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : null;
633
             $event_date[$k]['last_time'] = $v['last_time'] ? date('Y-m-d H:i:s', $v['last_time']) : null;
633
             $event_date[$k]['last_time'] = $v['last_time'] ? date('Y-m-d H:i:s', $v['last_time']) : null;
634
+            $event_date[$k]['next_time'] = $v['next_time'] ? date('Y-m-d H:i:s', $v['next_time']) : null;
634
         }
635
         }
635
         $data = [];
636
         $data = [];
636
         $data['list'] = $event_date;
637
         $data['list'] = $event_date;

+ 20
- 14
application/oa/model/Examine.php Целия файл

68
                 if (!isSuperAdministrators($user_id)) {
68
                 if (!isSuperAdministrators($user_id)) {
69
                     $map_str = "(( check_user_id LIKE '%," . $user_id . ",%' OR check_user_id = " . $user_id . " ) OR ( flow_user_id LIKE '%," . $user_id . ",%'  OR `flow_user_id` = " . $user_id . " ) )";
69
                     $map_str = "(( check_user_id LIKE '%," . $user_id . ",%' OR check_user_id = " . $user_id . " ) OR ( flow_user_id LIKE '%," . $user_id . ",%'  OR `flow_user_id` = " . $user_id . " ) )";
70
                 }
70
                 }
71
+                $map['examine.create_user_id'] = ['<>',$user_id];
71
                 break;
72
                 break;
72
             case '1' :
73
             case '1' :
73
                 $map['check_user_id'] = [['like', '%,' . $user_id . ',%']];
74
                 $map['check_user_id'] = [['like', '%,' . $user_id . ',%']];
356
                         'create_user_id' => $param['create_user_id'],
357
                         'create_user_id' => $param['create_user_id'],
357
                         'update_time' => time(),
358
                         'update_time' => time(),
358
                         'create_time' => time(),
359
                         'create_time' => time(),
359
-                        'customer_ids' => !empty($rdata['customer_ids']) ? trim($rdata['customer_ids'], ',') : '',
360
-                        'contacts_ids' => !empty($rdata['contacts_ids']) ? trim($rdata['contacts_ids'], ',') : '',
361
-                        'business_ids' => !empty($rdata['business_ids']) ? trim($rdata['business_ids'], ',') : '',
362
-                        'contract_ids' => !empty($rdata['contract_ids']) ? trim($rdata['contract_ids'], ',') : '',
360
+                        'customer_ids' => !empty($rdata['customer_ids']) ? $rdata['customer_ids'] : '',
361
+                        'contacts_ids' => !empty($rdata['contacts_ids']) ? $rdata['contacts_ids'] : '',
362
+                        'business_ids' => !empty($rdata['business_ids']) ? $rdata['business_ids'] : '',
363
+                        'contract_ids' => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : '',
363
                     ]);
364
                     ]);
364
                 }
365
                 }
365
                 
366
                 
447
                         $send_user_id
448
                         $send_user_id
448
                     );
449
                     );
449
                 }
450
                 }
450
-                
451
+
451
                 //相关业务
452
                 //相关业务
453
+                Db::name('OaExamineRelation')->where('examine_id', $examine_id)->delete(); // 先删除在添加
452
                 $rdata = [];
454
                 $rdata = [];
453
-                $rdata['customer_ids'] = $param['oaExamineRelation']['customer_ids'] ? arrayToString($param['oaExamineRelation']['customer_ids']) : [];
454
-                $rdata['contacts_ids'] = $param['oaExamineRelation']['contacts_ids'] ? arrayToString($param['oaExamineRelation']['contacts_ids']) : [];
455
-                $rdata['business_ids'] = $param['oaExamineRelation']['business_ids'] ? arrayToString($param['oaExamineRelation']['business_ids']) : [];
456
-                $rdata['contract_ids'] = $param['oaExamineRelation']['contract_ids'] ? arrayToString($param['oaExamineRelation']['contract_ids']) : [];
457
-                Db::name('OaExamineRelation')->where('examine_id = ' . $examine_id)->update($rdata);
455
+                $rdata['examine_id']   = $examine_id;
456
+                $rdata['status']       = 1;
457
+                $rdata['create_time']  = time();
458
+                $rdata['customer_ids'] = $param['oaExamineRelation']['customer_ids'] ? arrayToString($param['oaExamineRelation']['customer_ids']) : '';
459
+                $rdata['contacts_ids'] = $param['oaExamineRelation']['contacts_ids'] ? arrayToString($param['oaExamineRelation']['contacts_ids']) : '';
460
+                $rdata['business_ids'] = $param['oaExamineRelation']['business_ids'] ? arrayToString($param['oaExamineRelation']['business_ids']) : '';
461
+                $rdata['contract_ids'] = $param['oaExamineRelation']['contract_ids'] ? arrayToString($param['oaExamineRelation']['contract_ids']) : '';
462
+                Db::name('OaExamineRelation')->insert($rdata);
458
                 
463
                 
459
                 //处理差旅相关
464
                 //处理差旅相关
460
                 $resTravel = true;
465
                 $resTravel = true;
493
                         'create_user_id' => $create_user_id,
498
                         'create_user_id' => $create_user_id,
494
                         'update_time' => time(),
499
                         'update_time' => time(),
495
                         'create_time' => time(),
500
                         'create_time' => time(),
496
-                        'customer_ids' => !empty($rdata['customer_ids']) ? trim($rdata['customer_ids'], ',') : '',
497
-                        'contacts_ids' => !empty($rdata['contacts_ids']) ? trim($rdata['contacts_ids'], ',') : '',
498
-                        'business_ids' => !empty($rdata['business_ids']) ? trim($rdata['business_ids'], ',') : '',
499
-                        'contract_ids' => !empty($rdata['contract_ids']) ? trim($rdata['contract_ids'], ',') : '',
501
+                        'customer_ids' => !empty($rdata['customer_ids']) ? $rdata['customer_ids'] : '',
502
+                        'contacts_ids' => !empty($rdata['contacts_ids']) ? $rdata['contacts_ids'] : '',
503
+                        'business_ids' => !empty($rdata['business_ids']) ? $rdata['business_ids'] : '',
504
+                        'contract_ids' => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : '',
500
                     ]);
505
                     ]);
501
                 }
506
                 }
502
                 
507
                 
581
                 }
586
                 }
582
                 $travelList[$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
587
                 $travelList[$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
583
                 $travelList[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
588
                 $travelList[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
589
+                $travelList[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
584
                 $travelList[$k]['fileList'] = $fileList ?: [];
590
                 $travelList[$k]['fileList'] = $fileList ?: [];
585
                 $travelList[$k]['imgList'] = $imgList ?: [];
591
                 $travelList[$k]['imgList'] = $imgList ?: [];
586
             }
592
             }

+ 10
- 10
application/oa/model/Log.php Целия файл

73
         $dataWhere['structure_id'] = $request['structure_id'];
73
         $dataWhere['structure_id'] = $request['structure_id'];
74
         $dataWhere['auth_user_ids'] = $auth_user_ids;
74
         $dataWhere['auth_user_ids'] = $auth_user_ids;
75
         $logMap = '';
75
         $logMap = '';
76
-        if ($request['send_user_id'] != '') {
77
-            $map['log.create_user_id'] = ['in', trim(arrayToString($request['send_user_id']), ',')];
76
+        if ($request['create_user_id'] != '') {
77
+            $map['log.create_user_id'] = ['in', trim(arrayToString($request['create_user_id']), ',')];
78
         }
78
         }
79
         switch ($by) {
79
         switch ($by) {
80
             case 'me' :
80
             case 'me' :
282
                     'create_user_id' => $param['create_user_id'],
282
                     'create_user_id' => $param['create_user_id'],
283
                     'update_time' => time(),
283
                     'update_time' => time(),
284
                     'create_time' => time(),
284
                     'create_time' => time(),
285
-                    'customer_ids' => !empty($rdata['customer_ids']) ? trim($rdata['customer_ids'], ',') : '',
286
-                    'contacts_ids' => !empty($rdata['contacts_ids']) ? trim($rdata['contacts_ids'], ',') : '',
287
-                    'business_ids' => !empty($rdata['business_ids']) ? trim($rdata['business_ids'], ',') : '',
288
-                    'contract_ids' => !empty($rdata['contract_ids']) ? trim($rdata['contract_ids'], ',') : '',
285
+                    'customer_ids' => !empty($rdata['customer_ids']) ? $rdata['customer_ids'] : '',
286
+                    'contacts_ids' => !empty($rdata['contacts_ids']) ? $rdata['contacts_ids'] : '',
287
+                    'business_ids' => !empty($rdata['business_ids']) ? $rdata['business_ids'] : '',
288
+                    'contract_ids' => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : '',
289
                 ]);
289
                 ]);
290
             }
290
             }
291
             
291
             
361
                     'create_user_id' => $param['user_id'],
361
                     'create_user_id' => $param['user_id'],
362
                     'update_time' => time(),
362
                     'update_time' => time(),
363
                     'create_time' => time(),
363
                     'create_time' => time(),
364
-                    'customer_ids' => !empty($rdata['customer_ids']) ? trim($rdata['customer_ids'], ',') : '',
365
-                    'contacts_ids' => !empty($rdata['contacts_ids']) ? trim($rdata['contacts_ids'], ',') : '',
366
-                    'business_ids' => !empty($rdata['business_ids']) ? trim($rdata['business_ids'], ',') : '',
367
-                    'contract_ids' => !empty($rdata['contract_ids']) ? trim($rdata['contract_ids'], ',') : ''
364
+                    'customer_ids' => !empty($rdata['customer_ids']) ? $rdata['customer_ids'] : '',
365
+                    'contacts_ids' => !empty($rdata['contacts_ids']) ? $rdata['contacts_ids'] : '',
366
+                    'business_ids' => !empty($rdata['business_ids']) ? $rdata['business_ids'] : '',
367
+                    'contract_ids' => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : ''
368
                 ]);
368
                 ]);
369
             }
369
             }
370
             return $data;
370
             return $data;

+ 377
- 277
application/work/controller/Task.php
Файловите разлики са ограничени, защото са твърде много
Целия файл


+ 16
- 18
application/work/controller/Work.php Целия файл

45
                 'grouplist',
45
                 'grouplist',
46
                 'addusergroup',
46
                 'addusergroup',
47
                 'update',
47
                 'update',
48
-                'follow'
48
+                'follow',
49
+                'updateWorkOrder'
49
             ]
50
             ]
50
         ];
51
         ];
51
         Hook::listen('check_auth',$action);
52
         Hook::listen('check_auth',$action);
632
 
633
 
633
         return resultArray(['data' => '操作成功!']);
634
         return resultArray(['data' => '操作成功!']);
634
     }
635
     }
635
-    
636
+
636
     /**
637
     /**
637
-     * 项目排序
638
+     * 项目列表排序
638
      *
639
      *
639
-     * @author      alvin guogaobo
640
-     * @version     1.0 版本号
641
-     * @since       2021/2/23 0023 15:27
640
+     * @author fanqi
641
+     * @date 2021-03-11
642
+     * @param WorkLogic $workLogic
642
      */
643
      */
643
-//    public function workStart(){
644
-//        $param=$this->param;
645
-//        $userInfo=$this->userInfo;
646
-//        $param['work']=serialize($param);
647
-//        $param['user_id']=$userInfo['id'];
648
-//        $workStart=new WorkLogic();
649
-//        $res=$workStart->workStart($param);
650
-//        if(!$res){
651
-//            return resultArray(['error'=>'操作失败']);
652
-//        }
653
-//        return resultArray(['data'=>'操作成功']);
654
-//    }
644
+    public function updateWorkOrder(WorkLogic $workLogic)
645
+    {
646
+        $workIds  = $this->param['workIds'];
647
+        $userInfo = $this->userInfo;
648
+
649
+        $workLogic->setWorkOrder($workIds, $userInfo['id']);
650
+
651
+        return resultArray(['data' => '操作成功!']);
652
+    }
655
 }
653
 }
656
  
654
  

+ 96
- 122
application/work/logic/WorkLogic.php Целия файл

18
     public function index($param)
18
     public function index($param)
19
     {
19
     {
20
         # 排序
20
         # 排序
21
-        $orderField = 'work_id';
21
+        $orderField = 'w.work_id';
22
         $orderSort = 'asc';
22
         $orderSort = 'asc';
23
         if (!empty($param['sort_type']) && $param['sort_type'] == 1) {
23
         if (!empty($param['sort_type']) && $param['sort_type'] == 1) {
24
-            $orderField = 'work_id';
24
+            $orderField = 'w.work_id';
25
             $orderSort = 'asc';
25
             $orderSort = 'asc';
26
         }
26
         }
27
         if (!empty($param['sort_type']) && $param['sort_type'] == 2) {
27
         if (!empty($param['sort_type']) && $param['sort_type'] == 2) {
28
-            $orderField = 'work_id';
28
+            $orderField = 'w.work_id';
29
             $orderSort = 'desc';
29
             $orderSort = 'desc';
30
         }
30
         }
31
         if (!empty($param['sort_type']) && $param['sort_type'] == 3) {
31
         if (!empty($param['sort_type']) && $param['sort_type'] == 3) {
32
-            $orderField = 'update_time';
32
+            $orderField = 'w.update_time';
33
             $orderSort = 'desc';
33
             $orderSort = 'desc';
34
         }
34
         }
35
-        
35
+        if (!empty($param['sort_type']) && $param['sort_type'] == 4) {
36
+            $orderField = 'o.order';
37
+            $orderSort = 'asc';
38
+        }
39
+
36
         # 搜索
40
         # 搜索
37
         $searchWhere = '';
41
         $searchWhere = '';
38
         $dateWhere = [];
42
         $dateWhere = [];
51
         switch ($type) {
55
         switch ($type) {
52
             case 1 :
56
             case 1 :
53
                 # 今天
57
                 # 今天
54
-                $dateWhere['update_time'][] = ['egt', strtotime(date('Y-m-d 00:00:00'))];
55
-                $dateWhere['update_time'][] = ['elt', strtotime(date('Y-m-d 23:59:59'))];
58
+                $dateWhere['w.update_time'][] = ['egt', strtotime(date('Y-m-d 00:00:00'))];
59
+                $dateWhere['w.update_time'][] = ['elt', strtotime(date('Y-m-d 23:59:59'))];
56
                 break;
60
                 break;
57
             case 2 :
61
             case 2 :
58
                 # 上周
62
                 # 上周
59
-                $dateWhere['update_time'][] = ['egt', strtotime('last week monday')];
60
-                $dateWhere['update_time'][] = ['elt', strtotime(date('Y-m-d 23:59:59', strtotime('last week sunday')))];
63
+                $dateWhere['w.update_time'][] = ['egt', strtotime('last week monday')];
64
+                $dateWhere['w.update_time'][] = ['elt', strtotime(date('Y-m-d 23:59:59', strtotime('last week sunday')))];
61
                 break;
65
                 break;
62
             case 3 :
66
             case 3 :
63
                 # 上月
67
                 # 上月
64
-                $dateWhere['update_time'][] = ['egt', strtotime(date('Y-m-01 00:00:00', strtotime('last month')))];
65
-                $dateWhere['update_time'][] = ['elt', strtotime(date('Y-m-d 23:59:59', strtotime('Last day of last month')))];
68
+                $dateWhere['w.update_time'][] = ['egt', strtotime(date('Y-m-01 00:00:00', strtotime('last month')))];
69
+                $dateWhere['w.update_time'][] = ['elt', strtotime(date('Y-m-d 23:59:59', strtotime('Last day of last month')))];
66
                 break;
70
                 break;
67
             case 4 :
71
             case 4 :
68
                 # 去年
72
                 # 去年
69
-                $dateWhere['update_time'][] = ['egt', strtotime(date('Y-01-01 00:00:00', strtotime('last year')))];
70
-                $dateWhere['update_time'][] = ['elt', strtotime(date('Y-12-31 23:59:59', strtotime('last year')))];
73
+                $dateWhere['w.update_time'][] = ['egt', strtotime(date('Y-01-01 00:00:00', strtotime('last year')))];
74
+                $dateWhere['w.update_time'][] = ['elt', strtotime(date('Y-12-31 23:59:59', strtotime('last year')))];
71
         }
75
         }
72
         
76
         
73
         # 时间区间
77
         # 时间区间
74
-        if (!empty($startTime)) $dateWhere['update_time'] = ['egt', strtotime($startTime . '00:00:00')];
75
-        if (!empty($endTime)) $dateWhere['update_time'] = ['elt', strtotime($endTime . '23:59:59')];
78
+        if (!empty($startTime)) $dateWhere['w.update_time'] = ['egt', strtotime($startTime . '00:00:00')];
79
+        if (!empty($endTime)) $dateWhere['w.update_time'] = ['elt', strtotime($endTime . '23:59:59')];
76
         
80
         
77
         # 搜索内容
81
         # 搜索内容
78
-        if ($search) $searchWhere = '(name like "%' . $search . '%") OR (description like "%' . $search . '%")';
82
+        if ($search) $searchWhere = '(w.name like "%' . $search . '%") OR (w.description like "%' . $search . '%")';
79
         
83
         
80
         # 成员
84
         # 成员
81
         if (!empty($ownerUserId)) {
85
         if (!empty($ownerUserId)) {
82
             $userIds = Db::name('work_user')->whereIn('user_id', $ownerUserId)->column('work_id');
86
             $userIds = Db::name('work_user')->whereIn('user_id', $ownerUserId)->column('work_id');
83
-            $userWhere['work_id'] = ['in', $userIds];
87
+            $userWhere['w.work_id'] = ['in', $userIds];
84
         }
88
         }
85
         
89
         
86
         $userModel = new \app\admin\model\User();
90
         $userModel = new \app\admin\model\User();
87
         $perUserIds = $userModel->getUserByPer('work', 'work', 'index');
91
         $perUserIds = $userModel->getUserByPer('work', 'work', 'index');
88
         $authUser = array_unique(array_merge([$param['user_id']], $perUserIds));
92
         $authUser = array_unique(array_merge([$param['user_id']], $perUserIds));
89
-        
90
-        $data = Db::name('work')
91
-            ->where(function ($query) {
92
-                $query->where('status', 1);
93
-                $query->where('ishidden', 0);
94
-            })
95
-            ->where(function ($query) use ($param, $authUser) {
96
-                $query->whereOr(['create_user_id' => ['in', $authUser]]);
97
-                $query->whereOr('is_open', 1);
98
-                $query->whereOr(function ($query) use ($param) {
99
-                    $query->where('is_open', 0);
100
-                    $query->where('owner_user_id', 'like', '%' . $param['user_id'] . '%');
101
-                });
102
-            })
103
-            ->where($searchWhere)
104
-            ->where($dateWhere)
105
-            ->where($userWhere)
106
-            ->order($orderField, $orderSort)->select();
93
+
94
+        if ($param['sort_type'] == 4 && db('work_order')->where('user_id', $param['user_id'])->count() > 0) {
95
+            # 选择了按手动拖动排序,并且手动排过序。
96
+            $data = Db::name('work')->alias('w')
97
+                    ->field('w.*')
98
+                    ->join('__WORK_ORDER__ o', 'o.work_id = w.work_id', 'left')
99
+                    ->where(function ($query) {
100
+                        $query->where('status', 1);
101
+                        $query->where('ishidden', 0);
102
+                    })
103
+                    ->where(function ($query) use ($param, $authUser) {
104
+                        $query->whereOr(['create_user_id' => ['in', $authUser]]);
105
+                        $query->whereOr('is_open', 1);
106
+                        $query->whereOr(function ($query) use ($param) {
107
+                            $query->where('is_open', 0);
108
+                            $query->where('owner_user_id', 'like', '%' . $param['user_id'] . '%');
109
+                        });
110
+                    })
111
+                    ->where('o.user_id', $param['user_id'])
112
+                    ->where($searchWhere)
113
+                    ->where($dateWhere)
114
+                    ->where($userWhere)
115
+                    ->order($orderField, $orderSort)->select();
116
+        } else {
117
+            # 未手动排过序,如果选择了手动排序选项
118
+            if ($param['sort_type'] == 4) {
119
+                $orderField = 'w.work_id';
120
+                $orderSort = 'asc';
121
+            }
122
+
123
+            $data = Db::name('work')->alias('w')
124
+                    ->field('w.*')
125
+                    ->where(function ($query) {
126
+                        $query->where('status', 1);
127
+                        $query->where('ishidden', 0);
128
+                    })
129
+                    ->where(function ($query) use ($param, $authUser) {
130
+                        $query->whereOr(['create_user_id' => ['in', $authUser]]);
131
+                        $query->whereOr('is_open', 1);
132
+                        $query->whereOr(function ($query) use ($param) {
133
+                            $query->where('is_open', 0);
134
+                            $query->where('owner_user_id', 'like', '%' . $param['user_id'] . '%');
135
+                        });
136
+                    })
137
+                    ->where($searchWhere)
138
+                    ->where($dateWhere)
139
+                    ->where($userWhere)
140
+                    ->order($orderField, $orderSort)->select();
141
+        }
107
 
142
 
108
         foreach ($data as $key => $value) {
143
         foreach ($data as $key => $value) {
109
             $data[$key]['authList']['project'] = $this->getRuleList($value['work_id'], $param['user_id'], $value['group_id']);
144
             $data[$key]['authList']['project'] = $this->getRuleList($value['work_id'], $param['user_id'], $value['group_id']);
111
         
146
         
112
         return $data;
147
         return $data;
113
     }
148
     }
114
-    
149
+
115
     /**
150
     /**
116
-     * @param $param work 排序数组值 user_id用户
151
+     * 手动设置项目顺序
117
      *
152
      *
118
-     * @author      alvin guogaobo
119
-     * @version     1.0 版本号
120
-     * @since       2021/2/23 15:42
153
+     * @param $workIds 项目ID数组
154
+     * @param $userId 当前用户ID
155
+     * @author fanqi
156
+     * @date 2021-03-11
157
+     * @return bool
121
      */
158
      */
122
-//    public function workStart($param)
123
-//    {
124
-//        $item = Db::name('workStart')->where('user_id', $param['user_id'])->find();
125
-//        $data = [];
126
-//        $data['datas'] = $param['work'];
127
-//        $data['user_id'] = $param['user_id'];
128
-//        if (!$item) {
129
-//            return Db::name('workStart')->insertGetId($data);
130
-//        } else {
131
-//            return Db::name('workStart')->where('user_id', $param['user_id'])->update([$data]);
132
-//        }
133
-//    }
134
-    
135
-    /**
136
-     * 根据数组指定键名排序数组
137
-     * @param $array array  被排序数组
138
-     * @param $key_name string 数组键名
139
-     * @param $sort   string  desc|asc  升序或者降序
140
-     * @return array 返回排序后的数组
141
-     */
142
-//    function gw_sort($array, $param)
143
-//    {
144
-//        $whilr = array
145
-//        (
146
-//            [0] => ['work_id' => 5,
147
-//                'name' => 222,
148
-//                'status' => 1,
149
-//                'create_time' => 1613628469,
150
-//                'create_user_id' => 7,
151
-//                'description' => 222,
152
-//                'color' => '#53D397',
153
-//                'is_open' => 1,
154
-//                'owner_user_id' => ',1,2,3,4,5,7,',
155
-//                'ishidden' => 0,
156
-//                'archive_time' => 0,
157
-//                'group_id' => 12,
158
-//                'cover_url' => 'http://192.168.1.31/72crm-php/public/uploads/20210218/12ece02733c8684ce987f207062173b5.png',
159
-//                'update_time' => 1613629916,
160
-//                'is_follow' => 0,
161
-//                'is_system_cover' => 0,],
162
-//
163
-//            [1] => [
164
-//
165
-//                'work_id' => 7,
166
-//                'name' => '啊啊',
167
-//                'status' => 1,
168
-//                'create_time' => 1614059388,
169
-//                'create_user_id' => 1,
170
-//                'description' => '',
171
-//                'color' => '#53D397',
172
-//                'is_open' => 0,
173
-//                'owner_user_id' => ',1,3,',
174
-//                'ishidden' => 0,
175
-//                'archive_time' => 0,
176
-//                'group_id' => 12,
177
-//                'cover_url' => 'https://file.72crm.com/static/pc/images/pm/project-cover-1.jpg',
178
-//                'update_time' => 1614059926,
179
-//                'is_follow' => 0,
180
-//                'is_system_cover' => 1,
181
-//            ]
182
-//
183
-//        );
184
-//        $item = Db::name('workStart')->where('user_id', $param['user_id'])->find();
185
-//        $key_name_array = array();//保存被排序数组键名
186
-//        foreach ($whilr as $key => $val) {
187
-//            foreach ($item as $v){
188
-//                $key_name_array[] = array_merge(array_flip($val), $v);
189
-//            }
190
-//        }
191
-//        $key_name_array = array_flip($key_name_array);//反转键名和值得到数组排序后的位置
192
-//        $result = array();
193
-//        foreach($array as $k=>$v){
194
-//            foreach ($item as $vall){
195
-//                $this_key_name_value = $v[$vall];//当前数组键名值依次是20,10,30
196
-//                $save_position = $key_name_array[$this_key_name_value];//获取20,10,30排序后存储位置
197
-//                $result[$save_position] = $v;//当前项存储到数组指定位置
198
-//            }
199
-//        }
200
-//        ksort($result);
201
-//
202
-//        return $result;
203
-//    }
159
+    public function setWorkOrder($workIds, $userId)
160
+    {
161
+        $data = [];
162
+
163
+        foreach ($workIds AS $key => $value) {
164
+            $data[] = [
165
+                'work_id' => $value,
166
+                'user_id' => $userId,
167
+                'order'   => $key + 1
168
+            ];
169
+        }
170
+
171
+        if (!empty($data)) {
172
+            if (db('work_order')->where('user_id', $userId)->delete() === false) return false;
173
+            if (db('work_order')->insertAll($data) === false) return false;
174
+        }
175
+
176
+        return true;
177
+    }
204
 }
178
 }

+ 18
- 15
application/work/model/Task.php Целия файл

138
             $map['is_archive'] = 0;
138
             $map['is_archive'] = 0;
139
             $map['main_user_id']=$request['main_user_id'];
139
             $map['main_user_id']=$request['main_user_id'];
140
             $taskList = [];
140
             $taskList = [];
141
+            $map['search']=$request['search'];
141
             $resTaskList = $this->getTaskList($map);
142
             $resTaskList = $this->getTaskList($map);
142
             $data[$key]['count'] = $resTaskList['count'];
143
             $data[$key]['count'] = $resTaskList['count'];
143
             $data[$key]['list'] = $resTaskList['list'];
144
             $data[$key]['list'] = $resTaskList['list'];
449
                         'title' => $param['name'],
450
                         'title' => $param['name'],
450
                         'action_id' => $task_id
451
                         'action_id' => $task_id
451
                     ],
452
                     ],
452
-                    trim(',',$param['owner_user_id'])
453
+                    stringToArray($param['owner_user_id'])
453
                 );
454
                 );
454
             }
455
             }
455
 
456
 
463
                     'create_user_id' => $param['create_user_id'],
464
                     'create_user_id' => $param['create_user_id'],
464
                     'update_time' => time(),
465
                     'update_time' => time(),
465
                     'create_time' => time(),
466
                     'create_time' => time(),
466
-                    'customer_ids' => !empty($rdata['customer_ids']) ? trim($rdata['customer_ids'], ',') : '',
467
-                    'contacts_ids' => !empty($rdata['contacts_ids']) ? trim($rdata['contacts_ids'], ',') : '',
468
-                    'business_ids' => !empty($rdata['business_ids']) ? trim($rdata['business_ids'], ',') : '',
469
-                    'contract_ids' => !empty($rdata['contract_ids']) ? trim($rdata['contract_ids'], ',') : ''
467
+                    'customer_ids' => !empty($rdata['customer_ids']) ? $rdata['customer_ids'] : '',
468
+                    'contacts_ids' => !empty($rdata['contacts_ids']) ? $rdata['contacts_ids'] : '',
469
+                    'business_ids' => !empty($rdata['business_ids']) ? $rdata['business_ids'] : '',
470
+                    'contract_ids' => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : ''
470
                 ]);
471
                 ]);
471
             }
472
             }
472
 
473
 
679
                 }
680
                 }
680
             }
681
             }
681
             # 删除活动记录
682
             # 删除活动记录
682
-            Db::name('crm_activity')->where(['activity_type' => 8, 'activity_type_id' => $param['task_id']])->delete();
683
+            Db::name('crm_activity')->where(['activity_type' => 11, 'activity_type_id' => $param['task_id']])->delete();
683
             # 添加活动记录
684
             # 添加活动记录
684
             if (!empty($rdata['customer_ids']) || !empty($rdata['contacts_ids']) || !empty($rdata['business_ids']) || !empty($rdata['contract_ids'])) {
685
             if (!empty($rdata['customer_ids']) || !empty($rdata['contacts_ids']) || !empty($rdata['business_ids']) || !empty($rdata['contract_ids'])) {
685
                 Db::name('crm_activity')->insert([
686
                 Db::name('crm_activity')->insert([
690
                     'create_user_id'   => $createUserId,
691
                     'create_user_id'   => $createUserId,
691
                     'update_time'      => time(),
692
                     'update_time'      => time(),
692
                     'create_time'      => time(),
693
                     'create_time'      => time(),
693
-                    'customer_ids'     => !empty($rdata['customer_ids']) ? trim($rdata['customer_ids'], ',') : '',
694
-                    'contacts_ids'     => !empty($rdata['contacts_ids']) ? trim($rdata['contacts_ids'], ',') : '',
695
-                    'business_ids'     => !empty($rdata['business_ids']) ? trim($rdata['business_ids'], ',') : '',
696
-                    'contract_ids'     => !empty($rdata['contract_ids']) ? trim($rdata['contract_ids'], ',') : ''
694
+                    'customer_ids'     => !empty($rdata['customer_ids']) ? $rdata['customer_ids'] : '',
695
+                    'contacts_ids'     => !empty($rdata['contacts_ids']) ? $rdata['contacts_ids'] : '',
696
+                    'business_ids'     => !empty($rdata['business_ids']) ? $rdata['business_ids'] : '',
697
+                    'contract_ids'     => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : ''
697
                 ]);
698
                 ]);
698
             }
699
             }
699
             return true;
700
             return true;
785
             if (!$taskInfo['pid']) {
786
             if (!$taskInfo['pid']) {
786
                 actionLog($taskInfo['task_id'], $taskInfo['owner_user_id'], $taskInfo['structure_ids'], '删除了任务');
787
                 actionLog($taskInfo['task_id'], $taskInfo['owner_user_id'], $taskInfo['structure_ids'], '删除了任务');
787
             }
788
             }
789
+            # 删除任务的活动记录
790
+            db('crm_activity')->where(['type' => 2, 'activity_type' => 11, 'activity_type_id' => $param['task_id']])->delete();
788
             return true;
791
             return true;
789
         } else {
792
         } else {
790
             $this->error = '删除失败';
793
             $this->error = '删除失败';
906
         $main_user_id = $request['main_user_id'] ?: '';
909
         $main_user_id = $request['main_user_id'] ?: '';
907
         $taskSearch = !empty($request['taskSearch']) ? $request['taskSearch'] : '';
910
         $taskSearch = !empty($request['taskSearch']) ? $request['taskSearch'] : '';
908
         $isArchive = !empty($request['is_archive']) ? $request['is_archive'] : 0;
911
         $isArchive = !empty($request['is_archive']) ? $request['is_archive'] : 0;
909
-//        unset($request['search']);
910
-//        unset($request['whereStr']);
911
-//        unset($request['lable_id']);
912
+        unset($request['search']);
913
+        unset($request['whereStr']);
914
+        unset($request['lable_id']);
912
         unset($request['main_user_id']);
915
         unset($request['main_user_id']);
913
         $request = $this->fmtRequest($request);
916
         $request = $this->fmtRequest($request);
914
         $requestMap = $request['map'] ?: [];
917
         $requestMap = $request['map'] ?: [];
916
         $lableModel = new \app\work\model\WorkLable();
919
         $lableModel = new \app\work\model\WorkLable();
917
         $map = $requestMap;
920
         $map = $requestMap;
918
         $map['ishidden'] = $requestMap['ishidden'] ?: 0;
921
         $map['ishidden'] = $requestMap['ishidden'] ?: 0;
922
+        $map = where_arr($map, 'work', 'task', 'index');
919
         if ($search) {
923
         if ($search) {
920
             //普通筛选
924
             //普通筛选
921
-            $map['name'] = ['like', '%' . $search . '%'];
925
+            $map['task.name'] = ['like', '%' . $search . '%'];
922
         }
926
         }
923
-        $map = where_arr($map, 'work', 'task', 'index');
924
         if ($lable_id) {
927
         if ($lable_id) {
925
             $map['task.lable_id'] = array('like', '%' . $lable_id . '%');
928
             $map['task.lable_id'] = array('like', '%' . $lable_id . '%');
926
         }
929
         }

+ 12
- 11
config/config.php Целия файл

14
     // 应用命名空间
14
     // 应用命名空间
15
     'app_namespace'          => 'app',
15
     'app_namespace'          => 'app',
16
     // 应用调试模式
16
     // 应用调试模式
17
-    'app_debug'              => false,
17
+    'app_debug'              => true,
18
     // 应用Trace
18
     // 应用Trace
19
     'app_trace'              => false,
19
     'app_trace'              => false,
20
     // 应用模式状态
20
     // 应用模式状态
181
 
181
 
182
     'cache'                  => [
182
     'cache'                  => [
183
         // 驱动方式
183
         // 驱动方式
184
-        'type'   => 'File',
184
+        'type'   => 'redis',
185
         // 缓存保存目录
185
         // 缓存保存目录
186
         'path'   => CACHE_PATH,
186
         'path'   => CACHE_PATH,
187
         // 缓存前缀
187
         // 缓存前缀
190
         'expire' => 86400*30,
190
         'expire' => 86400*30,
191
         // 禁用缓存子目录
191
         // 禁用缓存子目录
192
         'cache_subdir' => false,
192
         'cache_subdir' => false,
193
-        'redis' => [
194
-            'type' => 'redis',
195
-            'host' => '127.0.0.1', // 全局缓存有效期(0为永久有效)
196
-            'expire'=> 0,
197
-        // 缓存前缀
198
-            'prefix'=> 'think',
199
-
200
-        ],
193
+        // 密码
194
+        'password' => ''
201
     ],
195
     ],
202
 
196
 
203
     // +----------------------------------------------------------------------
197
     // +----------------------------------------------------------------------
266
     'bi_cache_time' => 1800,
260
     'bi_cache_time' => 1800,
267
     // 商业智能慢查询查询时间(查询超过该时间进行数据缓存)(毫秒)
261
     // 商业智能慢查询查询时间(查询超过该时间进行数据缓存)(毫秒)
268
     'bi_slow_query_time' => 500,
262
     'bi_slow_query_time' => 500,
269
-    'public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkqKFcAQtIp4rlkB5LOMnViyVY/hhA6x0R9ftwtEXsAFu4hBZrm9txdEvxSrDCUsx3Zwv/gdimeOzTtfSKffdoE/DwllNP9Zu6nsr2kGRgPrRwjtlO+j2FOM0b9UY1SQ/bWE+a9oQL2jL9xMSbtX1xG/+HcMo1bT+pa6FNQzs3egmvMt75/jaxINPSraj4kgNFawSBk7qDBEqDYiQwtPTuaNW1YZIs++/gZHsCRgGs/JrAbxNpl7+v/+Z503I3I2rs/8eUM5d16NXR8M7vtobUDCTIiQOgRahO8WMadgFlwavyVCYhy/TBXyj5RUfWaS26LrEN3vkj4TjoJu5m9LQ5QIDAQAB',  
263
+    // 导入缓存时间(秒)
264
+    'import_cache_time' => 1800,
265
+    // 导出缓存时间(秒)
266
+    'export_cache_time' => 1800,
267
+    // 商机状态组列表缓存时间(秒)
268
+    'business_status_cache_time' => 1800,
269
+
270
+    'public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkqKFcAQtIp4rlkB5LOMnViyVY/hhA6x0R9ftwtEXsAFu4hBZrm9txdEvxSrDCUsx3Zwv/gdimeOzTtfSKffdoE/DwllNP9Zu6nsr2kGRgPrRwjtlO+j2FOM0b9UY1SQ/bWE+a9oQL2jL9xMSbtX1xG/+HcMo1bT+pa6FNQzs3egmvMt75/jaxINPSraj4kgNFawSBk7qDBEqDYiQwtPTuaNW1YZIs++/gZHsCRgGs/JrAbxNpl7+v/+Z503I3I2rs/8eUM5d16NXR8M7vtobUDCTIiQOgRahO8WMadgFlwavyVCYhy/TBXyj5RUfWaS26LrEN3vkj4TjoJu5m9LQ5QIDAQAB',
270
 ];
271
 ];

+ 5
- 1
config/route_admin.php Целия файл

16
     'admin/install/step3' => ['admin/install/step3', ['method' => 'GET']],
16
     'admin/install/step3' => ['admin/install/step3', ['method' => 'GET']],
17
  	'admin/install/step4' => ['admin/install/step4', ['method' => 'POST|AJAX']],
17
  	'admin/install/step4' => ['admin/install/step4', ['method' => 'POST|AJAX']],
18
     'admin/install/step5' => ['admin/install/step5', ['method' => 'GET']],
18
     'admin/install/step5' => ['admin/install/step5', ['method' => 'GET']],
19
- 	'admin/install/progress' => ['admin/install/progress', ['method' => 'POST']], 	
19
+    'admin/install/step6' => ['admin/install/step6', ['method' => 'GET']],
20
+ 	'admin/install/progress' => ['admin/install/progress', ['method' => 'POST']],
21
+
22
+    // 升级公告
23
+    'admin/adminUser/readNotice' => ['admin/index/readNotice', ['method' => 'POST']],
20
 
24
 
21
     //子部门列表
25
     //子部门列表
22
     'admin/structures/subIndex' => ['admin/structures/subIndex', ['method' => 'POST']],
26
     'admin/structures/subIndex' => ['admin/structures/subIndex', ['method' => 'POST']],

+ 4
- 2
config/route_work.php Целия файл

47
 	//【项目】删除参与人
47
 	//【项目】删除参与人
48
 	'work/work/ownerDel' => ['work/work/ownerDel', ['method' => 'POST']],	
48
 	'work/work/ownerDel' => ['work/work/ownerDel', ['method' => 'POST']],	
49
 	//【项目】参与人列表
49
 	//【项目】参与人列表
50
-	'work/work/ownerList' => ['work/work/ownerList', ['method' => 'POST']],	
50
+	'work/work/ownerList' => ['work/work/ownerList', ['method' => 'POST']],
51
+    //【项目】项目列表排序
52
+    'work/work/updateWorkOrder' => ['work/work/updateWorkOrder', ['method' => 'POST']],
51
 
53
 
52
 	//【我的任务】查看我的任务
54
 	//【我的任务】查看我的任务
53
 	'work/task/myTask'  => ['work/task/myTask', ['method' => 'POST']],
55
 	'work/task/myTask'  => ['work/task/myTask', ['method' => 'POST']],
108
     //【任务】导入
110
     //【任务】导入
109
     'work/task/excelImport'  => ['work/task/excelImport', ['method' => 'POST']],
111
     'work/task/excelImport'  => ['work/task/excelImport', ['method' => 'POST']],
110
     // 【任务】导入模板下载
112
     // 【任务】导入模板下载
111
-    'work/task/excelDownload' => ['crm/customer/excelDownload', ['method' => 'GET']],
113
+    'work/task/excelDownload' => ['work/task/excelDownload', ['method' => 'GET']],
112
 
114
 
113
 	//【标签】编辑
115
 	//【标签】编辑
114
 	'work/tasklable/update' => ['work/tasklable/update', ['method' => 'POST']],		
116
 	'work/tasklable/update' => ['work/tasklable/update', ['method' => 'POST']],		

+ 2
- 2
config/version.php Целия файл

1
 <?php
1
 <?php
2
 return array(
2
 return array(
3
-'VERSION'=>'11.0.1',
4
-'RELEASE'=>'20210227',
3
+'VERSION'=>'11.0.2',
4
+'RELEASE'=>'20210316',
5
 );
5
 );

+ 47
- 17
public/sql/5kcrm.sql Целия файл

311
   `record_id` int(11) NOT NULL AUTO_INCREMENT,
311
   `record_id` int(11) NOT NULL AUTO_INCREMENT,
312
   `types` varchar(50) NOT NULL COMMENT '关联类型',
312
   `types` varchar(50) NOT NULL COMMENT '关联类型',
313
   `types_id` int(11) NOT NULL COMMENT '类型ID',
313
   `types_id` int(11) NOT NULL COMMENT '类型ID',
314
-  `content` varchar(1000) NOT NULL COMMENT '跟进内容',
314
+  `content` varchar(1024) DEFAULT NULL COMMENT '跟进内容',
315
   `category` varchar(30) NOT NULL DEFAULT '' COMMENT '跟进类型',
315
   `category` varchar(30) NOT NULL DEFAULT '' COMMENT '跟进类型',
316
   `next_time` int(11) NOT NULL DEFAULT '0' COMMENT '下次联系时间',
316
   `next_time` int(11) NOT NULL DEFAULT '0' COMMENT '下次联系时间',
317
   `business_ids` varchar(255) NOT NULL DEFAULT '' COMMENT '商机ID',
317
   `business_ids` varchar(255) NOT NULL DEFAULT '' COMMENT '商机ID',
502
   `authkey` varchar(32) NOT NULL DEFAULT '' COMMENT '验证信息',
502
   `authkey` varchar(32) NOT NULL DEFAULT '' COMMENT '验证信息',
503
   `authkey_time` int(11) NOT NULL DEFAULT '0' COMMENT '验证失效时间',
503
   `authkey_time` int(11) NOT NULL DEFAULT '0' COMMENT '验证失效时间',
504
   `type` tinyint(2) NOT NULL COMMENT '1系统用户 0非系统用户',
504
   `type` tinyint(2) NOT NULL COMMENT '1系统用户 0非系统用户',
505
+  `is_read_notice` tinyint(1) NOT NULL DEFAULT 0 COMMENT '用户是否已读升级公告:1已读;0未读',
505
   PRIMARY KEY (`id`)
506
   PRIMARY KEY (`id`)
506
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';
507
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';
507
 
508
 
558
   `rw_user_id` varchar(500) NOT NULL DEFAULT '' COMMENT '读写权限',
559
   `rw_user_id` varchar(500) NOT NULL DEFAULT '' COMMENT '读写权限',
559
   `create_time` int(11) NOT NULL COMMENT '创建时间',
560
   `create_time` int(11) NOT NULL COMMENT '创建时间',
560
   `update_time` int(11) NOT NULL COMMENT '更新时间',
561
   `update_time` int(11) NOT NULL COMMENT '更新时间',
562
+  `is_dealt` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否已经处理(待办事项):1已处理;0未处理;',
561
   PRIMARY KEY (`business_id`)
563
   PRIMARY KEY (`business_id`)
562
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商机表';
564
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商机表';
563
 
565
 
738
   `next_time` int(11) NOT NULL DEFAULT '0' COMMENT '下次联系时间',
740
   `next_time` int(11) NOT NULL DEFAULT '0' COMMENT '下次联系时间',
739
   `create_time` int(11) NOT NULL COMMENT '创建时间',
741
   `create_time` int(11) NOT NULL COMMENT '创建时间',
740
   `update_time` int(11) NOT NULL COMMENT '更新时间',
742
   `update_time` int(11) NOT NULL COMMENT '更新时间',
743
+  `is_dealt` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否已经处理(待办事项):1已处理;0未处理;',
744
+  `is_allocation` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否是分配给我的线索:1是;0不是',
741
   PRIMARY KEY (`customer_id`)
745
   PRIMARY KEY (`customer_id`)
742
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='客户表';
746
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='客户表';
743
 
747
 
765
   `next_time` int(11) DEFAULT '0' COMMENT '下次联系时间',
769
   `next_time` int(11) DEFAULT '0' COMMENT '下次联系时间',
766
   `create_time` int(11) NOT NULL COMMENT '创建时间',
770
   `create_time` int(11) NOT NULL COMMENT '创建时间',
767
   `update_time` int(11) NOT NULL COMMENT '更新时间',
771
   `update_time` int(11) NOT NULL COMMENT '更新时间',
772
+  `is_dealt` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否已经处理(待办事项):1已处理;0未处理;',
773
+  `is_allocation` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否是分配给我的线索:1是;0不是',
768
   PRIMARY KEY (`leads_id`)
774
   PRIMARY KEY (`leads_id`)
769
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='线索表';
775
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='线索表';
770
 
776
 
848
   `create_time` int(11) NOT NULL COMMENT '创建时间',
854
   `create_time` int(11) NOT NULL COMMENT '创建时间',
849
   `update_time` int(11) NOT NULL COMMENT '更新时间',
855
   `update_time` int(11) NOT NULL COMMENT '更新时间',
850
   `file` varchar(500) NOT NULL DEFAULT '' COMMENT '附件',
856
   `file` varchar(500) NOT NULL DEFAULT '' COMMENT '附件',
857
+  `is_dealt` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否已经处理(待办事项):1已处理;0未处理;',
851
   PRIMARY KEY (`plan_id`)
858
   PRIMARY KEY (`plan_id`)
852
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='回款计划表';
859
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='回款计划表';
853
 
860
 
1674
 ALTER TABLE `5kcrm_oa_event_notice` MODIFY COLUMN `noticetype` tinyint(4) unsigned DEFAULT NULL COMMENT '1分 2时 3天';
1681
 ALTER TABLE `5kcrm_oa_event_notice` MODIFY COLUMN `noticetype` tinyint(4) unsigned DEFAULT NULL COMMENT '1分 2时 3天';
1675
 ALTER TABLE `5kcrm_oa_event_notice` ADD COLUMN `number` tinyint(4) NOT NULL DEFAULT 0  COMMENT '根据noticetype来决定提前多久提醒';
1682
 ALTER TABLE `5kcrm_oa_event_notice` ADD COLUMN `number` tinyint(4) NOT NULL DEFAULT 0  COMMENT '根据noticetype来决定提前多久提醒';
1676
 ALTER TABLE `5kcrm_admin_field` ADD COLUMN `is_hidden` tinyint(1) NOT NULL DEFAULT 0  COMMENT '是否隐藏:1隐藏;0不隐藏';
1683
 ALTER TABLE `5kcrm_admin_field` ADD COLUMN `is_hidden` tinyint(1) NOT NULL DEFAULT 0  COMMENT '是否隐藏:1隐藏;0不隐藏';
1677
-INSERT INTO `5kcrm_admin_field` VALUES (NULL, 'crm_customer', 0, 'email', '邮箱', 'text', '', 0, 0, 0, '', '', 9, 1, 1553788800, 1611144298, 2, '', 0);
1684
+INSERT INTO `5kcrm_admin_field` VALUES (NULL, 'crm_customer', 0, 'email', '邮箱', 'email', '', 0, 0, 0, '', '', 9, 1, 1553788800, 1611144298, 2, '', 0);
1678
 ALTER TABLE `5kcrm_crm_leads` ADD COLUMN `last_time` int(10) unsigned DEFAULT NULL COMMENT '最后跟进时间';
1685
 ALTER TABLE `5kcrm_crm_leads` ADD COLUMN `last_time` int(10) unsigned DEFAULT NULL COMMENT '最后跟进时间';
1679
 ALTER TABLE `5kcrm_crm_leads` ADD COLUMN `last_record` varchar(512) DEFAULT NULL COMMENT '最后跟进记录';
1686
 ALTER TABLE `5kcrm_crm_leads` ADD COLUMN `last_record` varchar(512) DEFAULT NULL COMMENT '最后跟进记录';
1680
 ALTER TABLE `5kcrm_admin_config` MODIFY COLUMN `controller` varchar(50) DEFAULT NULL COMMENT '控制器';
1687
 ALTER TABLE `5kcrm_admin_config` MODIFY COLUMN `controller` varchar(50) DEFAULT NULL COMMENT '控制器';
1713
 INSERT INTO `5kcrm_admin_field` ( `types`, `types_id`, `field`, `name`, `form_type`, `default_value`, `max_length`, `is_unique`, `is_null`, `input_tips`, `setting`, `order_id`, `operating`, `create_time`, `update_time`, `type`, `relevant`, `is_hidden`) VALUES ( 'crm_visit', '0', 'customer_id', '客户名称', 'customer', '', '0', '0', '1', '', '', '5', '1', '1553788800', '1553788800', '0', '', '0');
1720
 INSERT INTO `5kcrm_admin_field` ( `types`, `types_id`, `field`, `name`, `form_type`, `default_value`, `max_length`, `is_unique`, `is_null`, `input_tips`, `setting`, `order_id`, `operating`, `create_time`, `update_time`, `type`, `relevant`, `is_hidden`) VALUES ( 'crm_visit', '0', 'customer_id', '客户名称', 'customer', '', '0', '0', '1', '', '', '5', '1', '1553788800', '1553788800', '0', '', '0');
1714
 INSERT INTO `5kcrm_admin_field` ( `types`, `types_id`, `field`, `name`, `form_type`, `default_value`, `max_length`, `is_unique`, `is_null`, `input_tips`, `setting`, `order_id`, `operating`, `create_time`, `update_time`, `type`, `relevant`, `is_hidden`) VALUES ( 'crm_visit', '0', 'contacts_id', '联系人', 'contacts', '', '0', '0', '0', '', '', '6', '3', '1553788800', '1553788800', '0', '', '0');
1721
 INSERT INTO `5kcrm_admin_field` ( `types`, `types_id`, `field`, `name`, `form_type`, `default_value`, `max_length`, `is_unique`, `is_null`, `input_tips`, `setting`, `order_id`, `operating`, `create_time`, `update_time`, `type`, `relevant`, `is_hidden`) VALUES ( 'crm_visit', '0', 'contacts_id', '联系人', 'contacts', '', '0', '0', '0', '', '', '6', '3', '1553788800', '1553788800', '0', '', '0');
1715
 INSERT INTO `5kcrm_admin_field` ( `types`, `types_id`, `field`, `name`, `form_type`, `default_value`, `max_length`, `is_unique`, `is_null`, `input_tips`, `setting`, `order_id`, `operating`, `create_time`, `update_time`, `type`, `relevant`, `is_hidden`) VALUES ( 'crm_visit', '0', 'contract_id', '合同编号', 'contract', '', '0', '0', '1', '', '', '7', '1', '1553788800', '1553788800', '0', '', '0');
1722
 INSERT INTO `5kcrm_admin_field` ( `types`, `types_id`, `field`, `name`, `form_type`, `default_value`, `max_length`, `is_unique`, `is_null`, `input_tips`, `setting`, `order_id`, `operating`, `create_time`, `update_time`, `type`, `relevant`, `is_hidden`) VALUES ( 'crm_visit', '0', 'contract_id', '合同编号', 'contract', '', '0', '0', '1', '', '', '7', '1', '1553788800', '1553788800', '0', '', '0');
1716
-INSERT INTO `5kcrm_admin_field` ( `types`, `types_id`, `field`, `name`, `form_type`, `default_value`, `max_length`, `is_unique`, `is_null`, `input_tips`, `setting`, `order_id`, `operating`, `create_time`, `update_time`, `type`, `relevant`, `is_hidden`) VALUES ('crm_visit', '0', 'satisfaction', '客户满意度', 'select', '', '0', '0', '0', '', '很满意\r\n满意\r\n一般不满意\r\n很不满意', '8', '1', '1553788800', '1553788800', '0', NULL, '0');
1723
+INSERT INTO `5kcrm_admin_field` ( `types`, `types_id`, `field`, `name`, `form_type`, `default_value`, `max_length`, `is_unique`, `is_null`, `input_tips`, `setting`, `order_id`, `operating`, `create_time`, `update_time`, `type`, `relevant`, `is_hidden`) VALUES ('crm_visit', '0', 'satisfaction', '客户满意度', 'select', '', '0', '0', '0', '', '很满意\r\n满意\r\n一般\r\n不满意\r\n很不满意', '8', '1', '1553788800', '1553788800', '0', NULL, '0');
1717
 INSERT INTO `5kcrm_admin_field` ( `types`, `types_id`, `field`, `name`, `form_type`, `default_value`, `max_length`, `is_unique`, `is_null`, `input_tips`, `setting`, `order_id`, `operating`, `create_time`, `update_time`, `type`, `relevant`, `is_hidden`) VALUES ( 'crm_visit', '0', 'feedback', '客户反馈', 'textarea', '', '0', '0', '0', '', '', '9', '1', '1553788800', '1553788800', '0', '', '0');
1724
 INSERT INTO `5kcrm_admin_field` ( `types`, `types_id`, `field`, `name`, `form_type`, `default_value`, `max_length`, `is_unique`, `is_null`, `input_tips`, `setting`, `order_id`, `operating`, `create_time`, `update_time`, `type`, `relevant`, `is_hidden`) VALUES ( 'crm_visit', '0', 'feedback', '客户反馈', 'textarea', '', '0', '0', '0', '', '', '9', '1', '1553788800', '1553788800', '0', '', '0');
1718
 
1725
 
1719
 DROP TABLE IF EXISTS `5kcrm_crm_number_sequence`;
1726
 DROP TABLE IF EXISTS `5kcrm_crm_number_sequence`;
1734
   PRIMARY KEY (`number_sequence_id`) USING BTREE
1741
   PRIMARY KEY (`number_sequence_id`) USING BTREE
1735
 ) ENGINE=InnoDB AUTO_INCREMENT=1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT=Dynamic COMMENT='编号规则';
1742
 ) ENGINE=InnoDB AUTO_INCREMENT=1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT=Dynamic COMMENT='编号规则';
1736
 
1743
 
1737
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('1', '0', '1', 'HT', null, null, null, null, '1607356800', '1', null, '0', '1');
1738
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('2', '1', '2', 'yyyyMMdd', null, null, null, null, '1607356800', '1', null, '0', '1');
1739
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('3', '2', '3', '1', '1', '1', '43', '1612578239', '1607356800', '1', null, '0', '1');
1740
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('4', '1', '1', 'HK', null, null, null, null, '1611627355', '7', null, '0', '2');
1741
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('5', '1', '2', 'yyyyMMdd', null, null, null, null, '1611627355', '7', null, '0', '2');
1742
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('6', '1', '3', '1', '1', '4', '21', '1612578487', '1611627355', '7', null, '0', '2');
1743
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('7', '1', '1', 'HF', null, null, null, null, '1611627355', '7', null, '0', '3');
1744
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('8', '1', '2', 'yyyyMMdd', null, null, null, null, '1611627355', '7', null, '0', '3');
1745
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('9', '1', '3', '1', '1', '4', '13', '1612519628', '1611627355', '7', null, '0', '3');
1746
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('10', '1', '2', 'yyyyMMdd', null, null, null, null, '1612505697', '8', null, '0', '4');
1747
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('11', '1', '1', 'FP', null, null, null, null, '1612505750', '8', null, '0', '4');
1748
-INSERT INTO `5kcrm_crm_number_sequence` VALUES ('12', '2', '3', '1', '1', '4', '4', '1612581183', '1612505750', '8', null, '0', '4');
1744
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('1', '1', '1', 'HT', null, null, null, null, '1615737600', '1', null, '0', '1');
1745
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('2', '2', '2', 'yyyyMMdd', null, null, null, null, '1615737600', '1', null, '0', '1');
1746
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('3', '3', '3', '1', '1', '1', '1', '1615737600', '1615737600', '1', null, '0', '1');
1747
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('4', '1', '1', 'HK', null, null, null, null, '1615737600', '7', null, '0', '2');
1748
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('5', '2', '2', 'yyyyMMdd', null, null, null, null, '1615737600', '7', null, '0', '2');
1749
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('6', '3', '3', '1', '1', '1', '1', '1615737600', '1615737600', '7', null, '0', '2');
1750
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('7', '1', '1', 'HF', null, null, null, null, '1615737600', '7', null, '0', '3');
1751
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('8', '2', '2', 'yyyyMMdd', null, null, null, null, '1615737600', '7', null, '0', '3');
1752
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('9', '3', '3', '1', '1', '1', '1', '1615737600', '1615737600', '7', null, '0', '3');
1753
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('10', '1', '2', 'yyyyMMdd', null, null, null, null, '1615737600', '8', null, '0', '4');
1754
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('11', '2', '1', 'FP', null, null, null, null, '1615737600', '8', null, '0', '4');
1755
+INSERT INTO `5kcrm_crm_number_sequence` VALUES ('12', '3', '3', '1', '1', '1', '1', '1615737600', '1615737600', '8', null, '0', '4');
1749
 
1756
 
1750
 DROP TABLE IF EXISTS `5kcrm_crm_visit`;
1757
 DROP TABLE IF EXISTS `5kcrm_crm_visit`;
1751
 CREATE TABLE `5kcrm_crm_visit` (
1758
 CREATE TABLE `5kcrm_crm_visit` (
1926
   PRIMARY KEY (`id`) USING BTREE
1933
   PRIMARY KEY (`id`) USING BTREE
1927
 ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '日报规则表' ROW_FORMAT = Dynamic;
1934
 ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '日报规则表' ROW_FORMAT = Dynamic;
1928
 
1935
 
1936
+INSERT INTO `5kcrm_admin_oalog_rule` VALUES (1, 4, NULL, NULL, NULL, NULL, 1, 'a:3:{i:0;s:27:\"每一天都是崭新的!\";i:1;s:63:\"蓝天是宁静的,空气是清新的,阳光是明媚的!\";i:2;s:93:\"以下内容为系统默认欢迎语,在日志随机展示,可自定义更改欢迎语。\";}');
1937
+INSERT INTO `5kcrm_admin_oalog_rule` VALUES (2, 1, '3,4,10', '1,2,3,4,5,7,6', '08:00', '21:00', 1, NULL);
1938
+INSERT INTO `5kcrm_admin_oalog_rule` VALUES (3, 2, '3,4', NULL, '1', '3', 1, NULL);
1939
+INSERT INTO `5kcrm_admin_oalog_rule` VALUES (4, 3, '3', NULL, '3', '8', 1, NULL);
1940
+
1929
 ALTER TABLE `5kcrm_crm_business_type` ADD COLUMN `is_display` tinyint(1) unsigned NOT NULL DEFAULT 1 COMMENT '软删除:1显示0不显示';
1941
 ALTER TABLE `5kcrm_crm_business_type` ADD COLUMN `is_display` tinyint(1) unsigned NOT NULL DEFAULT 1 COMMENT '软删除:1显示0不显示';
1930
 
1942
 
1931
 DROP TABLE IF EXISTS `5kcrm_admin_operation_log`;
1943
 DROP TABLE IF EXISTS `5kcrm_admin_operation_log`;
1956
   PRIMARY KEY (`r_id`) USING BTREE
1968
   PRIMARY KEY (`r_id`) USING BTREE
1957
 ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '回款附件表' ROW_FORMAT = Dynamic;
1969
 ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '回款附件表' ROW_FORMAT = Dynamic;
1958
 
1970
 
1959
-INSERT INTO `5kcrm_crm_config` (`name`, `value`, `description`) VALUES ('activity_phrase', 'a:5:{i:0;s:18:\\\"电话无人接听\\\";i:1;s:15:\\\"客户无意向\\\";i:2;s:42:\\\"客户意向度适中,后续继续跟进\\\";i:3;s:42:\\\"客户意向度较强,成交几率较大\\\";i:4;s:3:\\\"312\\\";}', '跟进记录常用语');
1971
+INSERT INTO `5kcrm_crm_config` (`name`, `value`, `description`) VALUES ('activity_phrase', 'a:4:{i:0;s:18:"电话无人接听";i:1;s:15:"客户无意向";i:2;s:42:"客户意向度适中,后续继续跟进";i:3;s:42:"客户意向度较强,成交几率较大";}', '跟进记录常用语');
1960
 INSERT INTO `5kcrm_crm_config` (`name`, `value`, `description`) VALUES ('visit_config', '1', '是否开启回访提醒:1开启;0不开启');
1972
 INSERT INTO `5kcrm_crm_config` (`name`, `value`, `description`) VALUES ('visit_config', '1', '是否开启回访提醒:1开启;0不开启');
1961
-INSERT INTO `5kcrm_crm_config` (`name`, `value`, `description`) VALUES ('visit_day', '10', '客户回访提醒天数');
1973
+INSERT INTO `5kcrm_crm_config` (`name`, `value`, `description`) VALUES ('visit_day', '10', '客户回访提醒天数');
1974
+
1975
+DROP TABLE IF EXISTS `5kcrm_crm_dealt_relation`;
1976
+CREATE TABLE `5kcrm_crm_dealt_relation`  (
1977
+  `dealt_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
1978
+  `types` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '类型:crm_contract;crm_invoice;crm_receivables',
1979
+  `types_id` int(10) UNSIGNED NOT NULL COMMENT '类型ID',
1980
+  `user_id` int(10) UNSIGNED NOT NULL COMMENT '用户ID',
1981
+  PRIMARY KEY (`dealt_id`) USING BTREE
1982
+) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '待办事项关联表' ROW_FORMAT = Dynamic;
1983
+
1984
+DROP TABLE IF EXISTS `5kcrm_work_order`;
1985
+CREATE TABLE `5kcrm_work_order`  (
1986
+  `order_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
1987
+  `work_id` int(10) UNSIGNED NOT NULL,
1988
+  `user_id` int(10) UNSIGNED NOT NULL,
1989
+  `order` int(10) UNSIGNED NOT NULL DEFAULT 1,
1990
+  PRIMARY KEY (`order_id`) USING BTREE
1991
+) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '项目排序表' ROW_FORMAT = Dynamic;

+ 31
- 0
public/sql/update_sql_20210316.sql Целия файл

1
+ALTER TABLE `5kcrm_crm_leads` ADD COLUMN `is_dealt` tinyint(1) NOT NULL DEFAULT 1  COMMENT '是否已经处理(待办事项):1已处理;0未处理;';
2
+ALTER TABLE `5kcrm_crm_customer` ADD COLUMN `is_dealt` tinyint(1) NOT NULL DEFAULT 1  COMMENT '是否已经处理(待办事项):1已处理;0未处理;';
3
+ALTER TABLE `5kcrm_crm_business` ADD COLUMN `is_dealt` tinyint(1) NOT NULL DEFAULT 1  COMMENT '是否已经处理(待办事项):1已处理;0未处理;';
4
+ALTER TABLE `5kcrm_crm_receivables_plan` ADD COLUMN `is_dealt` tinyint(1) NOT NULL DEFAULT 0  COMMENT '是否已经处理(待办事项):1已处理;0未处理;';
5
+
6
+DROP TABLE IF EXISTS `5kcrm_crm_dealt_relation`;
7
+CREATE TABLE `5kcrm_crm_dealt_relation`  (
8
+  `dealt_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
9
+  `types` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '类型:crm_contract;crm_invoice;crm_receivables',
10
+  `types_id` int(10) UNSIGNED NOT NULL COMMENT '类型ID',
11
+  `user_id` int(10) UNSIGNED NOT NULL COMMENT '用户ID',
12
+  PRIMARY KEY (`dealt_id`) USING BTREE
13
+) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '待办事项关联表' ROW_FORMAT = Dynamic;
14
+
15
+DROP TABLE IF EXISTS `5kcrm_work_order`;
16
+CREATE TABLE `5kcrm_work_order`  (
17
+  `order_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
18
+  `work_id` int(10) UNSIGNED NOT NULL,
19
+  `user_id` int(10) UNSIGNED NOT NULL,
20
+  `order` int(10) UNSIGNED NOT NULL DEFAULT 1,
21
+  PRIMARY KEY (`order_id`) USING BTREE
22
+) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '项目排序表' ROW_FORMAT = Dynamic;
23
+
24
+UPDATE `5kcrm_admin_field` SET `form_type`='email' WHERE `types` = 'crm_customer' AND `field` = 'email';
25
+
26
+ALTER TABLE `5kcrm_crm_leads` ADD COLUMN `is_allocation` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否是分配给我的线索:1是;0不是';
27
+ALTER TABLE `5kcrm_crm_customer` ADD COLUMN `is_allocation` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否是分配给我的线索:1是;0不是';
28
+
29
+ALTER TABLE `5kcrm_admin_user` ADD COLUMN `is_read_notice` tinyint(1) NOT NULL DEFAULT 0 COMMENT '用户是否已读升级公告:1已读;0未读';
30
+
31
+ALTER TABLE `5kcrm_crm_activity` MODIFY COLUMN `content` varchar(1024) DEFAULT NULL COMMENT '跟进内容';

+ 14
- 8
public/static/js/step2.js Целия файл

70
   var result = checkForm();
70
   var result = checkForm();
71
   // console.log('result---', result, forms);
71
   // console.log('result---', result, forms);
72
   if (result) {
72
   if (result) {
73
-    
73
+
74
     $('#cover').css('display', 'block');//显示遮罩层
74
     $('#cover').css('display', 'block');//显示遮罩层
75
     setTimeout(()=>{
75
     setTimeout(()=>{
76
       $.ajax({
76
       $.ajax({
81
         data: {
81
         data: {
82
           form: forms
82
           form: forms
83
         },
83
         },
84
-        async: false,
84
+        async: true,
85
+        timeout: 20000,
85
         success: function (result) {
86
         success: function (result) {
86
           if (result.code == '200') {
87
           if (result.code == '200') {
88
+            localStorage.clear();
87
             window.location = 'step5.html';
89
             window.location = 'step5.html';
88
           } else if (result.code == '400') {
90
           } else if (result.code == '400') {
89
-            $('#cover').css('display', 'none');
90
-            alert(result.error); //失败
91
-            return false;
91
+            window.location.href = '/admin/install/step6';
92
+            // $('#cover').css('display', 'none');
93
+            // alert(result.error); //失败
94
+            // return false;
92
             // window.location = 'step3.html'
95
             // window.location = 'step3.html'
93
           } else {
96
           } else {
94
-            window.location = 'step3.html'
95
-            alert('安装失败');
97
+            window.location.href = '/admin/install/step6';
98
+            // window.location = 'step3.html';
99
+            // alert('安装失败');
96
           }
100
           }
101
+        },
102
+        error: function (xhr) {
103
+          window.location.href = '/admin/install/step6';
97
         }
104
         }
98
-        // getRes();
99
       }); 
105
       }); 
100
     })   
106
     })   
101
   }
107
   }