Bladeren bron

v11.1.0-20210625

Michael_xu 5 jaren geleden
bovenliggende
commit
26b0e8466b
100 gewijzigde bestanden met toevoegingen van 13130 en 5521 verwijderingen
  1. 0
    2
      application/admin/controller/ApiCommon.php
  2. 0
    43
      application/admin/controller/Base.php
  3. 0
    1
      application/admin/controller/ExamineFlow.php
  4. 146
    46
      application/admin/controller/Field.php
  5. 4
    1
      application/admin/controller/Groups.php
  6. 4
    1
      application/admin/controller/Index.php
  7. 15
    5
      application/admin/controller/Install.php
  8. 131
    1
      application/admin/controller/Rules.php
  9. 19
    3
      application/admin/controller/Setting.php
  10. 2
    1
      application/admin/controller/Structures.php
  11. 28
    25
      application/admin/controller/System.php
  12. 115
    9
      application/admin/controller/UpdateSql.php
  13. 71
    3
      application/admin/controller/Users.php
  14. 6
    5
      application/admin/controller/Work.php
  15. 55
    1
      application/admin/logic/FieldGrantLogic.php
  16. 24
    38
      application/admin/logic/InitializeLogic.php
  17. 2
    2
      application/admin/logic/LogLogic.php
  18. 2
    2
      application/admin/logic/MessageLogic.php
  19. 38
    15
      application/admin/logic/PoolConfigLogic.php
  20. 5
    7
      application/admin/logic/WorkLogic.php
  21. 1
    1
      application/admin/model/ActionRecord.php
  22. 310
    306
      application/admin/model/Common.php
  23. 226
    268
      application/admin/model/Excel.php
  24. 621
    208
      application/admin/model/Field.php
  25. 5
    7
      application/admin/model/Group.php
  26. 7
    1
      application/admin/model/Message.php
  27. 24
    23
      application/admin/model/Scene.php
  28. 2
    4
      application/admin/model/Structure.php
  29. 1028
    988
      application/admin/model/User.php
  30. 262
    0
      application/admin/traits/FieldVerificationTrait.php
  31. 2
    40
      application/admin/view/install/step6.html
  32. 1
    0
      application/command.php
  33. 867
    284
      application/common.php
  34. 102
    100
      application/common/command/PoolCommand.php
  35. 153
    0
      application/common/command/Team.php
  36. 112
    32
      application/crm/common.php
  37. 132
    140
      application/crm/controller/Activity.php
  38. 6
    1
      application/crm/controller/Business.php
  39. 4
    2
      application/crm/controller/BusinessStatus.php
  40. 34
    35
      application/crm/controller/Contacts.php
  41. 3
    1
      application/crm/controller/Contract.php
  42. 31
    38
      application/crm/controller/Customer.php
  43. 141
    106
      application/crm/controller/CustomerPool.php
  44. 8
    5
      application/crm/controller/Index.php
  45. 430
    147
      application/crm/controller/Invoice.php
  46. 19
    33
      application/crm/controller/Leads.php
  47. 137
    273
      application/crm/controller/Message.php
  48. 19
    29
      application/crm/controller/Product.php
  49. 4
    2
      application/crm/controller/ProductCategory.php
  50. 12
    2
      application/crm/controller/Receivables.php
  51. 4
    0
      application/crm/controller/ReceivablesPlan.php
  52. 150
    54
      application/crm/controller/Setting.php
  53. 7
    5
      application/crm/logic/ActivityLogic.php
  54. 106
    47
      application/crm/logic/CommonLogic.php
  55. 99
    53
      application/crm/logic/CustomerPoolLogic.php
  56. 89
    100
      application/crm/logic/IndexLogic.php
  57. 244
    137
      application/crm/logic/InvoiceLogic.php
  58. 272
    0
      application/crm/logic/MessageLogic.php
  59. 5
    2
      application/crm/logic/PrintingLogic.php
  60. 208
    20
      application/crm/logic/VisitLogic.php
  61. 219
    33
      application/crm/model/Business.php
  62. 7
    13
      application/crm/model/BusinessStatus.php
  63. 509
    300
      application/crm/model/Contacts.php
  64. 233
    49
      application/crm/model/Contract.php
  65. 370
    219
      application/crm/model/Customer.php
  66. 1
    3
      application/crm/model/CustomerConfig.php
  67. 0
    1
      application/crm/model/Invoice.php
  68. 235
    24
      application/crm/model/Leads.php
  69. 213
    27
      application/crm/model/Product.php
  70. 13
    18
      application/crm/model/ProductCategory.php
  71. 717
    511
      application/crm/model/Receivables.php
  72. 213
    21
      application/crm/model/ReceivablesPlan.php
  73. 46
    11
      application/crm/model/Setting.php
  74. 1
    1
      application/crm/traits/AutoNumberTrait.php
  75. 0
    188
      application/oa/controller/Addresslist.php
  76. 6
    0
      application/oa/controller/Examine.php
  77. 19
    1
      application/oa/controller/Log.php
  78. 49
    12
      application/oa/logic/LogLogic.php
  79. 0
    1
      application/oa/logic/UserLogic.php
  80. 3
    0
      application/oa/model/Event.php
  81. 45
    24
      application/oa/model/Examine.php
  82. 1
    3
      application/oa/model/ExamineCategory.php
  83. 19
    10
      application/oa/model/ExamineData.php
  84. 33
    18
      application/oa/model/Log.php
  85. 13
    11
      application/work/controller/Work.php
  86. 10
    23
      application/work/model/Task.php
  87. 20
    22
      application/work/model/Work.php
  88. 2
    6
      application/work/model/WorkClass.php
  89. 2882
    0
      composer.lock
  90. 8
    4
      config/config.php
  91. 39
    0
      config/database_template.php
  92. 23
    1
      config/route_admin.php
  93. 26
    5
      config/route_crm.php
  94. 5
    2
      config/route_oa.php
  95. 2
    2
      config/version.php
  96. BIN
      favicon.ico
  97. 1
    0
      index.html
  98. 4
    0
      nginx.htaccess
  99. 589
    252
      public/sql/5kcrm.sql
  100. 0
    0
      public/sql/5kcrm_all.sql

+ 0
- 2
application/admin/controller/ApiCommon.php Bestand weergeven

28
         $paramArr = $request->param();
28
         $paramArr = $request->param();
29
         $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
29
         $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
30
         $cache = Cache::get('Auth_'.$authKey.$platform);
30
         $cache = Cache::get('Auth_'.$authKey.$platform);
31
-//        $cache = cache('Auth_'.$authKey.$platform);
32
-//        dump($request->action());die;
33
         // 校验sessionid和authKey
31
         // 校验sessionid和authKey
34
         if (empty($sessionId) || empty($authKey) || empty($cache)) {
32
         if (empty($sessionId) || empty($authKey) || empty($cache)) {
35
             header('Content-Type:application/json; charset=utf-8');
33
             header('Content-Type:application/json; charset=utf-8');

+ 0
- 43
application/admin/controller/Base.php Bestand weergeven

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

+ 0
- 1
application/admin/controller/ExamineFlow.php Bestand weergeven

259
             $content='启用了:';
259
             $content='启用了:';
260
         }
260
         }
261
         $dataInfo=db('admin_examine_flow')->where('flow_id',$param['flow_id'])->find();
261
         $dataInfo=db('admin_examine_flow')->where('flow_id',$param['flow_id'])->find();
262
-//        p(3333);
263
         SystemActionLog($userInfo['id'], 'admin_examine','approval', $param['flow_id'], 'update', $dataInfo['name'], '', '',$content.$dataInfo['name']);
262
         SystemActionLog($userInfo['id'], 'admin_examine','approval', $param['flow_id'], 'update', $dataInfo['name'], '', '',$content.$dataInfo['name']);
264
         return resultArray(['data' => '操作成功']);         
263
         return resultArray(['data' => '操作成功']);         
265
     }
264
     }

+ 146
- 46
application/admin/controller/Field.php Bestand weergeven

56
         }         
56
         }         
57
         $param = $this->param;
57
         $param = $this->param;
58
         $types_arr = [
58
         $types_arr = [
59
-            ['types' => 'crm_leads','name' => '线索管理'],
60
-            ['types' => 'crm_customer','name' => '客户管理'],
61
-            ['types' => 'crm_contacts','name' => '联系人管理'],
62
-            ['types' => 'crm_product','name' => '产品管理'],
63
-            ['types' => 'crm_business','name' => '商机管理'],
64
-            ['types' => 'crm_contract','name' => '合同管理'],
65
-            ['types' => 'crm_receivables','name' => '回款管理'],
66
-            ['types' => 'crm_visit','name' => '客户回访管理'],
59
+            ['types' => 'crm_leads',            'name' => '线索管理'],
60
+            ['types' => 'crm_customer',         'name' => '客户管理'],
61
+            ['types' => 'crm_contacts',         'name' => '联系人管理'],
62
+            ['types' => 'crm_business',         'name' => '商机管理'],
63
+            ['types' => 'crm_contract',         'name' => '合同管理'],
64
+            ['types' => 'crm_receivables',      'name' => '回款管理'],
65
+            ['types' => 'crm_receivables_plan', 'name' => '回款计划管理'],
66
+            ['types' => 'crm_invoice',          'name' => '发票管理'],
67
+            ['types' => 'crm_visit',            'name' => '回访管理'],
68
+            ['types' => 'crm_product',          'name' => '产品管理'],
67
         ];
69
         ];
68
         $examine_types_arr = [];    
70
         $examine_types_arr = [];    
69
         switch ($param['type']) {
71
         switch ($param['type']) {
99
      */
101
      */
100
     public function update()
102
     public function update()
101
     {
103
     {
102
-        # 权限判断 todo 允许有相应权限的普通员工操作,暂时注释代码,后期修改权限验证。
103
-//        if (!checkPerByAction('admin', 'crm', 'field')) {
104
-//            header('Content-Type:application/json; charset=utf-8');
105
-//            exit(json_encode(['code'=>102,'error'=>'无权操作']));
106
-//        }
107
         # 系统审批类型暂不支持编辑
104
         # 系统审批类型暂不支持编辑
108
         if ($this->param['types'] == 'oa_examine' && $this->param['types_id'] < 7) {
105
         if ($this->param['types'] == 'oa_examine' && $this->param['types_id'] < 7) {
109
             return resultArray(['error' => '系统审批类型暂不支持编辑']);
106
             return resultArray(['error' => '系统审批类型暂不支持编辑']);
114
         $param      = $this->param;
111
         $param      = $this->param;
115
         $types      = $param['types'];
112
         $types      = $param['types'];
116
         $types_id   = $param['types_id'] ? : 0;
113
         $types_id   = $param['types_id'] ? : 0;
117
-//        $data['types'] = $param['types'];
118
 
114
 
119
         $data         = $param['data'];
115
         $data         = $param['data'];
120
         $saveParam    = []; # 新增数据
116
         $saveParam    = []; # 新增数据
132
                 break;
128
                 break;
133
             }
129
             }
134
 
130
 
131
+            # 验证数字范围
132
+            if (!empty($v['max_num_restrict']) && !empty($v['min_num_restrict']) && $v['min_num_restrict'] > $v['max_num_restrict']) {
133
+                $errorMessage = '数字范围错误!';
134
+                break;
135
+            }
136
+
137
+            # 验证百分数小数位
138
+            if ($v['form_type'] == 'percent' && !empty($v['precisions']) && ($v['precisions'] < 1 || $v['precisions'] > 5)) {
139
+                $errorMessage = '百分数字段类型的小数配置错误!';
140
+                break;
141
+            }
142
+
143
+            # 验证数字小数位
144
+            if ($v['form_type'] == 'number' && !empty($v['precisions']) && ($v['precisions'] < 1 || $v['precisions'] > 14)) {
145
+                $errorMessage = '数字字段类型的小数配置错误!';
146
+                break;
147
+            }
148
+
135
             if ($v['field_id']) {
149
             if ($v['field_id']) {
136
                 if (isset($v['is_deleted']) && $v['is_deleted'] == '1') {
150
                 if (isset($v['is_deleted']) && $v['is_deleted'] == '1') {
137
                     # 删除
151
                     # 删除
160
         foreach ($deleteIds AS $key => $value) {
174
         foreach ($deleteIds AS $key => $value) {
161
             if (!in_array($value, $delParam)) $delParam[] = $value;
175
             if (!in_array($value, $delParam)) $delParam[] = $value;
162
         }
176
         }
163
-        $recordModules = [
164
-            'crm_leads'       => '线索',
165
-            'crm_customer'    => '客户',
166
-            'crm_pool'        => '客户公海',
167
-            'crm_contacts'    => '联系人',
168
-            'crm_product'     => '产品',
169
-            'crm_business'    => '商机',
170
-            'crm_contract'    => '合同',
171
-            'crm_receivables' => '回款',
172
-            'crm_visit'       => '回访',
173
-            'crm_invoice'     => '回款',
174
-            'oa_log'          => '办公日志',
175
-            'oa_examine'      => '办公审批',
176
-        ];
177
+
177
         # 新增
178
         # 新增
178
         if (!empty($saveParam)) {
179
         if (!empty($saveParam)) {
179
             if (!$data = $fieldModel->createData($types, $saveParam)) {
180
             if (!$data = $fieldModel->createData($types, $saveParam)) {
180
                 $errorMessage[] = $fieldModel->getError();
181
                 $errorMessage[] = $fieldModel->getError();
181
-            }            
182
+            }
182
         }
183
         }
184
+        
183
         # 编辑
185
         # 编辑
184
         if (!empty($updateParam)) {
186
         if (!empty($updateParam)) {
185
             if (!$data = $fieldModel->updateDataById($updateParam, $types)) {
187
             if (!$data = $fieldModel->updateDataById($updateParam, $types)) {
215
                 'oa_log'          => '办公日志',
217
                 'oa_log'          => '办公日志',
216
                 'oa_examine'      => '办公审批',
218
                 'oa_examine'      => '办公审批',
217
             ];
219
             ];
218
-            if($types !== 'oa_examine'){
219
-                $systemModules='customer';
220
-            }else{
221
-                $systemModules='approval';
220
+            if ($types !== 'oa_examine') {
221
+                $systemModules = 'customer';
222
+            } else {
223
+                $systemModules = 'approval';
222
             }
224
             }
223
             SystemActionLog($userInfo['id'], $types,$systemModules, 1,  'update', $recordModules[$types], '','','编辑了自定义字段:'.$recordModules[$types]);
225
             SystemActionLog($userInfo['id'], $types,$systemModules, 1,  'update', $recordModules[$types], '','','编辑了自定义字段:'.$recordModules[$types]);
224
             return resultArray(['data' => '修改成功']);
226
             return resultArray(['data' => '修改成功']);
242
         $controller = trim($param['controller']);
244
         $controller = trim($param['controller']);
243
         $action = trim($param['action']);
245
         $action = trim($param['action']);
244
         $system = !empty($param['system']) ? $param['system'] : 0;
246
         $system = !empty($param['system']) ? $param['system'] : 0;
247
+        $format = !empty($param['format']) ? $param['format'] : 1; // 设置返回数据的格式类型:1 还是之前的二维数组格式,兼容移动端、 2 三维数组,新版自定义字段的分组排序。
245
         unset($param['system']);
248
         unset($param['system']);
246
         
249
         
247
         if (!$module || !$controller || !$action) {
250
         if (!$module || !$controller || !$action) {
260
                     case 'crm_customer' : 
263
                     case 'crm_customer' : 
261
                         $customerModel = new \app\crm\model\Customer();
264
                         $customerModel = new \app\crm\model\Customer();
262
                         $dataInfo = $customerModel->getDataById(intval($param['action_id']));
265
                         $dataInfo = $customerModel->getDataById(intval($param['action_id']));
263
-                        // 公海
264
-                        if (!empty($param['pool_id'])) {
265
-                            $data = $fieldModel->getPoolFieldData($param['pool_id'], $dataInfo);
266
-                            return resultArray(['data' => $data]);
267
-                        }
268
                         //判断权限
266
                         //判断权限
269
                         $auth_user_ids = $userModel->getUserByPer('crm', 'customer', $param['action']);
267
                         $auth_user_ids = $userModel->getUserByPer('crm', 'customer', $param['action']);
270
                         //读写权限
268
                         //读写权限
327
                     case 'crm_product' : 
325
                     case 'crm_product' : 
328
                         $productModel = new \app\crm\model\Product();
326
                         $productModel = new \app\crm\model\Product();
329
                         $dataInfo = $productModel->getDataById(intval($param['action_id']));
327
                         $dataInfo = $productModel->getDataById(intval($param['action_id']));
328
+
329
+                        //判断权限
330
+                        $auth_user_ids = $userModel->getUserByPer('crm', 'product', $param['action']);
331
+                        if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
332
+                            header('Content-Type:application/json; charset=utf-8');
333
+                            exit(json_encode(['code'=>102,'error'=>'无权操作']));
334
+                        }
330
                         break;
335
                         break;
331
                     case 'crm_receivables' : 
336
                     case 'crm_receivables' : 
332
                         $receivablesModel = new \app\crm\model\Receivables();
337
                         $receivablesModel = new \app\crm\model\Receivables();
368
                         //读写权限
373
                         //读写权限
369
                         $roPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'read');
374
                         $roPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'read');
370
                         $rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
375
                         $rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
371
-                        if (!in_array($user_id, stringToArray($dataInfo['owner_user_id'])) && !in_array($user_id,$auth_user_ids) && !$roPre && !$rwPre) {
376
+                        if (!in_array($dataInfo['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
377
+                            header('Content-Type:application/json; charset=utf-8');
378
+                            exit(json_encode(['code'=>102,'error'=>'无权操作']));
379
+                        }
380
+                        break;
381
+                    case 'crm_invoice' :
382
+                        $visit = new \app\crm\model\Invoice();
383
+                        $dataInfo = $visit->getDataById(intval($param['action_id']));
384
+                        $fieldModel = new \app\admin\model\Field();
385
+                        $datetimeField = $fieldModel->getFieldByFormType('crm_invoice', 'datetime'); //日期时间类型
386
+                        foreach ($datetimeField as $key => $val) {
387
+                            $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
388
+                        }
389
+                        //判断权限
390
+                        $auth_user_ids = $userModel->getUserByPer('crm', 'invoice', $param['action']);
391
+                       
392
+                        if (!in_array($user_id, stringToArray($dataInfo['owner_user_id'])) && !in_array($user_id,$auth_user_ids) ) {
372
                             header('Content-Type:application/json; charset=utf-8');
393
                             header('Content-Type:application/json; charset=utf-8');
373
                             exit(json_encode(['code'=>102,'error'=>'无权操作']));
394
                             exit(json_encode(['code'=>102,'error'=>'无权操作']));
374
                         }
395
                         }
380
         $action_id = $param['action_id'] ? : '';
401
         $action_id = $param['action_id'] ? : '';
381
         $data = $fieldModel->field($param, $dataInfo) ? : [];
402
         $data = $fieldModel->field($param, $dataInfo) ? : [];
382
 
403
 
404
+        # 多公海数据详情
405
+        if (!empty($param['pool_id']) && $param['action'] == 'read') {
406
+            $data = $this->setPoolDetailData($data, $param['pool_id'], $param['action_id']);
407
+        }
408
+
383
         # 回访模块下,负责人名称变更为回访人
409
         # 回访模块下,负责人名称变更为回访人
384
         if ($param['types'] == 'crm_visit') {
410
         if ($param['types'] == 'crm_visit') {
385
             foreach ($data AS $key => $value) {
411
             foreach ($data AS $key => $value) {
446
                 }
472
                 }
447
             }
473
             }
448
         }
474
         }
475
+        # 发票自动编号设置
476
+        if ($param['types'] == 'crm_invoice') {
477
+            foreach ($data AS $key => $value) {
478
+                if ($value['field'] == 'invoice_apple_number') {
479
+                    if ($this->getAutoNumberStatus(4)) {
480
+                        $data[$key]['is_null']   = 0;
481
+                        $data[$key]['is_unique'] = 0;
482
+                    }
483
+                    $data[$key]['autoGeneNumber'] = $this->getAutoNumberStatus(4) ? 1 : 0;
484
+                }
485
+            }
486
+        }
449
 
487
 
450
         # 隐藏回款计划中的附件
488
         # 隐藏回款计划中的附件
451
         if ($param['types'] == 'crm_receivables_plan') {
489
         if ($param['types'] == 'crm_receivables_plan') {
490
                 case 'crm_customer' :
528
                 case 'crm_customer' :
491
                     $customerModel = new Customer();
529
                     $customerModel = new Customer();
492
                     $customerData  = $customerModel->getSystemInfo($action_id);
530
                     $customerData  = $customerModel->getSystemInfo($action_id);
493
-                    $customerArray = ['obtain_time' => '负责人获取客户时间', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间', 'last_record' => '最后跟进记录', 'deal_status' => '成交状态'];
531
+                    $customerArray = ['obtain_time' => '负责人获取客户时间', 'owner_user_id' => '负责人', 'create_user_id' => '创建人', 'create_time' => '创建时间', 'update_time' => '更新时间', 'last_time' => '最后跟进时间', 'last_record' => '最后跟进记录', 'deal_status' => '成交状态'];
494
 
532
 
495
                     foreach ($customerData AS $key => $value) {
533
                     foreach ($customerData AS $key => $value) {
496
-                        if (empty($customerArray[$key])) continue;
534
+                        if (empty($customerArray[$key]) || (!empty($param['pool_id']) && in_array($key, ['obtain_time', 'owner_user_id']))) continue;
497
 
535
 
498
                         $data[] = [
536
                         $data[] = [
499
                             'field'     => $key,
537
                             'field'     => $key,
606
                         ];
644
                         ];
607
                     }
645
                     }
608
                     break;
646
                     break;
647
+                case 'crm_invoice' :
648
+                    $invoiceData = db('crm_invoice')->field(['create_user_id', 'owner_user_id', 'create_time', 'update_time'])->where('invoice_id', $action_id)->find();
649
+                    $createUserName = db('admin_user')->where('id', $invoiceData['create_user_id'])->value('realname');
650
+                    $ownerUserName = db('admin_user')->where('id', $invoiceData['owner_user_id'])->value('realname');
651
+                    $data[] = ['field' => 'create_user_id', 'name' => '创建人', 'form_type' => 'user', 'value' => $createUserName, 'system' => 1];
652
+                    $data[] = ['field' => 'create_user_id', 'name' => '负责人', 'form_type' => 'user', 'value' => $ownerUserName, 'system' => 1];
653
+                    $data[] = ['field' => 'create_time', 'name' => '创建时间', 'form_type' => 'datetime', 'value' => date('Y-m-d H:i:s', $invoiceData['create_time']), 'system' => 1];
654
+                    $data[] = ['field' => 'update_time', 'name' => '更新时间', 'form_type' => 'datetime', 'value' => date('Y-m-d H:i:s', $invoiceData['update_time']), 'system' => 1];
609
             }
655
             }
610
         }
656
         }
611
 
657
 
658
+        # 处理自定义字段别名、权限
612
         $data = $fieldModel->resetField($user_id, $param['types'], $param['action'], $data);
659
         $data = $fieldModel->resetField($user_id, $param['types'], $param['action'], $data);
613
 
660
 
661
+        # 处理自定义字段分组排序
662
+        if (in_array($param['action'], ['save', 'update', 'relative']) && $format == 2) $data = getFieldGroupOrderData($data);
663
+
614
         return resultArray(['data' => array_values($data)]);
664
         return resultArray(['data' => array_values($data)]);
615
     }
665
     }
616
 
666
 
623
     {
673
     {
624
         $param = $this->param;
674
         $param = $this->param;
625
         $fieldModel = model('Field');
675
         $fieldModel = model('Field');
626
-        if (is_array($param['val'])) {
627
-            //多选类型暂不验证
628
-            return resultArray(['data' => '验证通过']);
629
-        }
630
-        $res = $fieldModel->getValidate(trim($param['field']), trim($param['val']), intval($param['id']), trim($param['types']));
676
+        $res = $fieldModel->getValidate(trim($param['field']), $param['val'], intval($param['id']), trim($param['types']));
631
         if (!$res) {
677
         if (!$res) {
632
             return resultArray(['error' => $fieldModel->getError()]);
678
             return resultArray(['error' => $fieldModel->getError()]);
633
         }
679
         }
725
     {
771
     {
726
         return Db::name('crm_number_sequence')->where('number_type', $type)->where('status', 0)->value('number_sequence_id');
772
         return Db::name('crm_number_sequence')->where('number_type', $type)->where('status', 0)->value('number_sequence_id');
727
     }
773
     }
774
+
775
+    /**
776
+     * 处理公海详情数据
777
+     *
778
+     * @param $data array 公海数据
779
+     * @param $poolId int 公海ID
780
+     * @param $actionId int  数据ID
781
+     * @author fanqi
782
+     * @since 2021-06-21
783
+     * @return array
784
+     */
785
+    private function setPoolDetailData($data, $poolId, $actionId)
786
+    {
787
+        $poolData = [];
788
+
789
+        $poolList = db('crm_customer_pool_field_setting')->field(['field_name', 'is_hidden'])->where('pool_id', $poolId)->select();
790
+
791
+        // 组装字段数据
792
+        foreach ($poolList AS $key => $value) {
793
+            $poolData[$value['field_name']] = $value['is_hidden'];
794
+        }
795
+
796
+        // 处理公海数据
797
+        foreach ($data AS $key => $value) {
798
+            if (!empty($poolData[$value['field']]) || $value['field'] == 'owner_user_id') {
799
+                unset($data[(int)$key]);
800
+
801
+                continue;
802
+            }
803
+        }
804
+
805
+        // 前负责人
806
+        $beforeUser = db('crm_customer')->alias('customer')
807
+            ->join('__ADMIN_USER__ user', 'user.id = customer.before_owner_user_id', 'left')
808
+            ->field(['user.id', 'user.username', 'user.realname', 'user.thumb_img'])
809
+            ->where('customer_id', $actionId)
810
+            ->find();
811
+        if (!empty($beforeUser['thumb_img'])) $beforeUser['thumb_img'] = getFullPath($beforeUser['thumb_img']);
812
+
813
+        $data[] = [
814
+            'field'         => 'before_owner_user_id',
815
+            'name'          => '前负责人',
816
+            'form_type'     => 'user',
817
+            'writeStatus'   => 0,
818
+            'fieldName'     => 'before_owner_user_id',
819
+            'value'         => [$beforeUser],
820
+            'setting'       => [],
821
+            'default_value' => [],
822
+            'options'       => '',
823
+            'optionsData'   => ''
824
+        ];
825
+
826
+        return array_values($data);
827
+    }
728
 }
828
 }

+ 4
- 1
application/admin/controller/Groups.php Bestand weergeven

107
     {        
107
     {        
108
         $groupModel = model('Group');
108
         $groupModel = model('Group');
109
         $param = $this->param;
109
         $param = $this->param;
110
+        $userInfo=$this->userInfo;
111
+        $param['user_id']=$userInfo['id'];
110
         $dataInfo = $groupModel->getDataById($param['id']);
112
         $dataInfo = $groupModel->getDataById($param['id']);
111
         if (!$dataInfo) {
113
         if (!$dataInfo) {
112
             return resultArray(['error' => '参数错误']);
114
             return resultArray(['error' => '参数错误']);
130
     {            
132
     {            
131
         $groupModel = model('Group');
133
         $groupModel = model('Group');
132
         $param = $this->param;
134
         $param = $this->param;
135
+        $userInfo=$this->userInfo;
133
         $dataInfo = $groupModel->getDataById($param['id']);
136
         $dataInfo = $groupModel->getDataById($param['id']);
134
         if (!$dataInfo) {
137
         if (!$dataInfo) {
135
             return resultArray(['error' => '参数错误']);
138
             return resultArray(['error' => '参数错误']);
137
         if ($dataInfo['types']) {
140
         if ($dataInfo['types']) {
138
             return resultArray(['error' => '系统角色,不能删除']);
141
             return resultArray(['error' => '系统角色,不能删除']);
139
         }        
142
         }        
140
-        $data = $groupModel->delGroupById($param['id']);      
143
+        $data = $groupModel->delGroupById($param['id'],$userInfo['id']);
141
         if (!$data) {
144
         if (!$data) {
142
             return resultArray(['error' => $groupModel->getError()]);
145
             return resultArray(['error' => $groupModel->getError()]);
143
         }
146
         }

+ 4
- 1
application/admin/controller/Index.php Bestand weergeven

62
             if ($value['field'] == 'check_status') $field_arr[$key]['form_type'] = 'check_status';
62
             if ($value['field'] == 'check_status') $field_arr[$key]['form_type'] = 'check_status';
63
             if ($param['types'] == 'crm_visit' && $value['field'] == 'owner_user_id') $field_arr[$key]['name'] = '回访人';
63
             if ($param['types'] == 'crm_visit' && $value['field'] == 'owner_user_id') $field_arr[$key]['name'] = '回访人';
64
         }
64
         }
65
-
65
+        if(in_array($param['types'],['crm_customer','crm_customer_pool','crm_contacts','crm_business','crm_contract','crm_receivables'])){
66
+            $field=[['field'=>'team_id','name'=>'相关团队','form_type'=>'user','setting'=>[]]];
67
+            $field_arr=array_merge($field_arr,$field);
68
+        }
66
         return resultArray(['data' => $field_arr]);
69
         return resultArray(['data' => $field_arr]);
67
     }
70
     }
68
 
71
 

+ 15
- 5
application/admin/controller/Install.php Bestand weergeven

47
      */    
47
      */    
48
     public function index()
48
     public function index()
49
     {
49
     {
50
-        $protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
50
+        $protocol = strpos(strtolower($_SERVER['HTTP_REFERER']), 'https') === false ? 'http' : 'https';
51
 
51
 
52
         if (strpos(request()->url(), "index.php") === false) {
52
         if (strpos(request()->url(), "index.php") === false) {
53
             $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
53
             $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
70
     public function step1()
70
     public function step1()
71
     {
71
     {
72
         if (strpos(request()->url(), "index.php") === false) {
72
         if (strpos(request()->url(), "index.php") === false) {
73
-            $protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
73
+            $protocol = strpos(strtolower($_SERVER['HTTP_REFERER']), 'https') === false ? 'http' : 'https';
74
             $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
74
             $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
75
             header("Location:" . $url);
75
             header("Location:" . $url);
76
         }
76
         }
97
             die(); 
97
             die(); 
98
         }
98
         }
99
         if (strpos(request()->url(), "index.php") === false) {
99
         if (strpos(request()->url(), "index.php") === false) {
100
-            $protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
100
+            $protocol = strpos(strtolower($_SERVER['HTTP_REFERER']), 'https') === false ? 'http' : 'https';
101
             $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
101
             $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
102
             header("Location:" . $url);
102
             header("Location:" . $url);
103
         }
103
         }
375
             'php'     => ['PHP版本', PHP_VERSION, '7.3 ( <em style="color: #888; font-size: 12px;">>= 7.0</em> )', 'ok','性能更佳'],
375
             'php'     => ['PHP版本', PHP_VERSION, '7.3 ( <em style="color: #888; font-size: 12px;">>= 7.0</em> )', 'ok','性能更佳'],
376
             'gd'      => ['gd', '开启', '开启', 'ok'],
376
             'gd'      => ['gd', '开启', '开启', 'ok'],
377
             'openssl' => ['openssl', '开启', '开启', 'ok'],
377
             'openssl' => ['openssl', '开启', '开启', 'ok'],
378
-            'pdo' => ['pdo', '开启', '开启', 'ok'],
378
+            'pdo'     => ['pdo', '开启', '开启', 'ok'],
379
         ];
379
         ];
380
+        // linux系统下需要posix扩展
381
+        if (in_array(PHP_OS, ['Linux', 'centos', 'Centos', 'ubuntu', 'Ubuntu'])) {
382
+            $items['posix'] = ['posix', '开启', '开启', 'ok'];
383
+        }
380
         session('install_error','');
384
         session('install_error','');
381
         if (substr($items['php'][1],0,3) < '7.0') {
385
         if (substr($items['php'][1],0,3) < '7.0') {
382
             $items['php'][3] = 'error';
386
             $items['php'][3] = 'error';
388
             $items['gd'][3] = 'error';
392
             $items['gd'][3] = 'error';
389
             session('install_error', true);
393
             session('install_error', true);
390
         }
394
         }
395
+
391
         if (!extension_loaded('openssl')) {
396
         if (!extension_loaded('openssl')) {
392
             $items['openssl'][1] = '未开启';
397
             $items['openssl'][1] = '未开启';
393
             $items['openssl'][3] = 'error';
398
             $items['openssl'][3] = 'error';
398
             $items['pdo'][3] = 'error';
403
             $items['pdo'][3] = 'error';
399
             session('install_error', true);
404
             session('install_error', true);
400
         }
405
         }
401
-        // dump($items);die;
406
+        // linux系统下检查是否加载了posix扩展
407
+        if (in_array(PHP_OS, ['Linux', 'centos', 'Centos', 'ubuntu', 'Ubuntu']) && !extension_loaded('posix')) {
408
+            $items['posix'][1] = '未开启';
409
+            $items['posix'][3] = 'error';
410
+            session('install_error', true);
411
+        }
402
         return $items;
412
         return $items;
403
     }
413
     }
404
     
414
     

+ 131
- 1
application/admin/controller/Rules.php Bestand weergeven

9
 
9
 
10
 use think\Hook;
10
 use think\Hook;
11
 use think\Request;
11
 use think\Request;
12
+use think\Db;
12
 
13
 
13
 class Rules extends ApiCommon
14
 class Rules extends ApiCommon
14
 {
15
 {
22
     {
23
     {
23
         $action = [
24
         $action = [
24
             'permission'=>[''],
25
             'permission'=>[''],
25
-            'allow'=>['index']            
26
+            'allow'=>['index','groupauth','upgroupauth','getgroupauth','groupauthid']            
26
         ];
27
         ];
27
         Hook::listen('check_auth',$action);
28
         Hook::listen('check_auth',$action);
28
         $request = Request::instance();
29
         $request = Request::instance();
75
         } 
76
         } 
76
         return resultArray(['data' => '编辑成功']);
77
         return resultArray(['data' => '编辑成功']);
77
     }
78
     }
79
+
80
+    /**
81
+     * 配置角色查看范围列表
82
+     * @author zjf
83
+     */
84
+    public function groupauth()
85
+    {
86
+        $param = $this->param;
87
+
88
+        $data = ['0' => ['name' => '系统管理角色','pid' => 1],'1' => ['name' => '办公管理角色','pid' => 6],'2' => ['name' => '客户管理角色','pid' => 2],'3' => ['name' => '项目管理角色','pid' => '9']];
89
+        $list = db('admin_group')->field('id, pid, title')->select();
90
+        
91
+        $authList = db('admin_group_auth')->where('group_id', $param['group_id'])->column('auth_group_id');
92
+        foreach ($data as $key => $value) {
93
+            foreach ($list as $k => $v) {
94
+                $v['is_true'] = in_array($v['id'], $authList) ? 1 : 0;
95
+
96
+                if($v['pid'] == $value['pid']){
97
+                    $data[$key]['item'][] = $v;
98
+                }
99
+            }
100
+        }
101
+
102
+        return resultArray(['data' => $data]);
103
+    }
104
+
105
+    /**
106
+     * 配置角色查看范围列表
107
+     * @author zjf
108
+     */
109
+    public function groupauthid()
110
+    {
111
+        $param = $this->param;
112
+
113
+        $authList = db('admin_group_auth')->where('group_id', $param['group_id'])->column('auth_group_id');
114
+
115
+        return resultArray(['data' => array_map('intval', $authList)]);
116
+    }
117
+
118
+    /**
119
+     * 编辑配置角色查看范围 
120
+     */
121
+    public function upgroupauth()
122
+    {
123
+        $param = $this->param;
124
+        $group_id = $param['group_id'];
125
+        $auth_group_id = $param['auth_group_id'];
126
+
127
+        $data = [];
128
+        foreach ($auth_group_id as $key => $value) {
129
+            $data[] = [
130
+                'group_id' => $param['group_id'],
131
+                'auth_group_id' => $value
132
+            ];
133
+        }
134
+
135
+        // 启动事务
136
+        Db::startTrans();
137
+        try{
138
+            db('admin_group_auth')->where('group_id', $param['group_id'])->delete();
139
+            db('admin_group_auth')->insertAll($data);
140
+            // 提交事务
141
+            Db::commit();    
142
+            return resultArray(['data' => '编辑成功']);
143
+        } catch (\Exception $e) {
144
+            // 回滚事务
145
+            Db::rollback();
146
+            return resultArray(['data' => '编辑失败']);
147
+        }
148
+    }
149
+
150
+    /**
151
+     * 配置角色查看范围列表
152
+     * @author zjf
153
+     */
154
+    public function getgroupauth()
155
+    {
156
+        $userInfo = $this->userInfo;
157
+        $userId = $userInfo['id'];
158
+
159
+        $groupIds = db('admin_access')->where('user_id', $userId)->column('group_id');
160
+        $rules = db('admin_group')->where('id', 'in', $groupIds)->column('rules');
161
+        
162
+        $arr = [];
163
+        foreach ($rules as $key => $value) {
164
+            if($arr){
165
+                $arr = array_merge(explode(",", trim($value, ",")), $arr);
166
+            }else{
167
+                $arr = explode(",", trim($value, ","));
168
+            }
169
+        }
170
+        $data = ['0' => ['name' => '系统管理角色','pid' => 1],'1' => ['name' => '办公管理角色','pid' => 6],'2' => ['name' => '客户管理角色','pid' => 2],'3' => ['name' => '项目管理角色','pid' => '9']];
171
+
172
+        # 角色权限查看  配置范围对应id
173
+        $rule_authority_id =  db('admin_rule')->where(['title' => '角色权限设置', 'name' => 'update'])->value('id');
174
+        if(!in_array($rule_authority_id, $arr) && $userId != 1){
175
+            $auth_group_ids = db('admin_group_auth')->where('group_id', 'in', $groupIds)->column('auth_group_id');
176
+            $list = db('admin_group')->where('id', 'in', $auth_group_ids)->select();
177
+            $arrData = [];
178
+            foreach ($data as $key => $value) {
179
+                $item = [];
180
+                foreach ($list as $k => $v) {
181
+                    if($v['pid'] == $value['pid']){
182
+                        $item[] = $v;
183
+                    }
184
+                }
185
+                $items = [];
186
+                if(!empty($item)){
187
+                    $items = [
188
+                        'name' => $value['name'],
189
+                        'pid' => $value['pid'],
190
+                        'list' => $item,
191
+                    ];
192
+                    $arrData[] = $items;
193
+                }
194
+            }
195
+            return resultArray(['data' => $arrData]);
196
+        }else{
197
+            $list = db('admin_group')->select();
198
+            foreach ($data as $key => $value) {
199
+                foreach ($list as $k => $v) {
200
+                    if($v['pid'] == $value['pid']){
201
+                        $data[$key]['list'][] = $v;
202
+                    }
203
+                }
204
+            }
205
+            return resultArray(['data' => $data]);
206
+        }
207
+    }
78
 }
208
 }
79
  
209
  

+ 19
- 3
application/admin/controller/Setting.php Bestand weergeven

19
      * @permission 无限制
19
      * @permission 无限制
20
      * @allow 登录用户可访问
20
      * @allow 登录用户可访问
21
      * @other 其他根据系统设置
21
      * @other 其他根据系统设置
22
-    **/    
22
+    **/
23
     public function _initialize()
23
     public function _initialize()
24
     {
24
     {
25
         $action = [
25
         $action = [
28
         ];
28
         ];
29
         Hook::listen('check_auth',$action);
29
         Hook::listen('check_auth',$action);
30
         $request = Request::instance();
30
         $request = Request::instance();
31
-        $a = strtolower($request->action());        
31
+        $a = strtolower($request->action());
32
         if (!in_array($a, $action['permission'])) {
32
         if (!in_array($a, $action['permission'])) {
33
             parent::_initialize();
33
             parent::_initialize();
34
         }
34
         }
39
         if (!in_array(2,$adminTypes) && !in_array(1,$adminTypes) && !in_array($a, $unAction)) {
39
         if (!in_array(2,$adminTypes) && !in_array(1,$adminTypes) && !in_array($a, $unAction)) {
40
             header('Content-Type:application/json; charset=utf-8');
40
             header('Content-Type:application/json; charset=utf-8');
41
             exit(json_encode(['code'=>102,'error'=>'无权操作']));
41
             exit(json_encode(['code'=>102,'error'=>'无权操作']));
42
-        }           
42
+        }
43
     }
43
     }
44
 
44
 
45
     /**
45
     /**
176
 
176
 
177
         return resultArray(['data' => $data]);
177
         return resultArray(['data' => $data]);
178
     }
178
     }
179
+    
180
+    /**
181
+     * 设置顶部导航信息
182
+     *
183
+     * @author      alvin guogaobo
184
+     * @version     1.0 版本号
185
+     * @since       2021/6/22 0022 11:28
186
+     */
187
+    public function appMenuConfig()
188
+    {
189
+        $param=$this->param;
190
+        $userId=$this->userInfo['id'];
191
+        $settingModel = new \app\crm\model\Setting();
192
+        $data=$settingModel->setMenuConfig($param,$userId);
193
+        return resultArray(['data'=>'操作成功']);
194
+    }
179
 }
195
 }

+ 2
- 1
application/admin/controller/Structures.php Bestand weergeven

195
         }        
195
         }        
196
         $structureModel = model('Structure');
196
         $structureModel = model('Structure');
197
         $param = $this->param;
197
         $param = $this->param;
198
-        $data = $structureModel->delStrById($param['id']);       
198
+        $userInfo=$this->userInfo;
199
+        $data = $structureModel->delStrById($param['id'],$userInfo['id']);
199
         if (!$data) {
200
         if (!$data) {
200
             return resultArray(['error' => $structureModel->getError()]);
201
             return resultArray(['error' => $structureModel->getError()]);
201
         } 
202
         } 

+ 28
- 25
application/admin/controller/System.php Bestand weergeven

16
     public function _initialize()
16
     public function _initialize()
17
     {
17
     {
18
         $action = [
18
         $action = [
19
-            'permission'=>['index'],
20
-            'allow'=>['']
19
+            'permission' => ['index'],
20
+            'allow' => ['']
21
         ];
21
         ];
22
-        Hook::listen('check_auth',$action);
22
+        Hook::listen('check_auth', $action);
23
         $request = Request::instance();
23
         $request = Request::instance();
24
-        $a = strtolower($request->action());        
24
+        $a = strtolower($request->action());
25
         if (!in_array($a, $action['permission'])) {
25
         if (!in_array($a, $action['permission'])) {
26
             parent::_initialize();
26
             parent::_initialize();
27
-        }            
28
-    }        
29
-
27
+        }
28
+    }
29
+    
30
     //信息列表
30
     //信息列表
31
     public function index()
31
     public function index()
32
-    {   
32
+    {
33
         $systemModel = model('System');
33
         $systemModel = model('System');
34
         $data = $systemModel->getDataList();
34
         $data = $systemModel->getDataList();
35
         return resultArray(['data' => $data]);
35
         return resultArray(['data' => $data]);
36
     }
36
     }
37
-	
37
+    
38
     //编辑保存
38
     //编辑保存
39
-	public function save()
40
-	{
39
+    public function save()
40
+    {
41
         $param = $this->param;
41
         $param = $this->param;
42
-        $userInfo=$this->userInfo;
43
-        $field_name='';
44
-        $dataInfo=[];
42
+        $userInfo = $this->userInfo;
43
+        $field_name = '';
44
+        $dataInfo = [];
45
         if (isset($param['logo'])) {
45
         if (isset($param['logo'])) {
46
-            $system_id=2;
47
-            $field_name='企业logo';
48
-            $logo = !empty($param['logo']) ? './public/uploads/'.$param['logo'] : '';
49
-            $dataInfo =  db('admin_system')->where('id', $system_id)->column('name,value');
46
+            $system_id = 2;
47
+            $field_name = '企业logo';
48
+            $logo = !empty($param['logo']) ? './public/uploads/' . $param['logo'] : '';
49
+            $dataInfo = db('admin_system')->where('id', $system_id)->column('name,value');
50
             db('admin_system')->where('name', 'logo')->update(['value' => $logo]);
50
             db('admin_system')->where('name', 'logo')->update(['value' => $logo]);
51
-        }elseif (isset($param['name'])) {
52
-            $system_id=1;
53
-            $field_name='企业名称';
54
-            $dataInfo =  db('admin_system')->where('id', $system_id)->column('name,value');
51
+            # 修改记录
52
+            SystemActionLog($userInfo['id'], 'admin_system', 'company', 1, 'update', '企业基本信息设置', '', '', '编辑了:' . $field_name);
53
+        }
54
+        if (isset($param['name'])) {
55
+            $system_id = 1;
56
+            $field_name = '企业名称';
57
+            $dataInfo = db('admin_system')->where('id', $system_id)->column('name,value');
55
             db('admin_system')->where('name', 'name')->update(['value' => $param['name']]);
58
             db('admin_system')->where('name', 'name')->update(['value' => $param['name']]);
59
+            # 修改记录
60
+            SystemActionLog($userInfo['id'], 'admin_system', 'company', 1, 'update', '企业基本信息设置', '', '', '编辑了:' . $field_name);
56
         }
61
         }
57
-        # 修改记录
58
-        SystemActionLog($userInfo['id'],'admin_system','company',1,'update','企业基本信息设置','','','编辑了:'.$field_name);
59
         return resultArray(['data' => '操作成功!']);
62
         return resultArray(['data' => '操作成功!']);
60
-	}
63
+    }
61
 }
64
 }
62
  
65
  

+ 115
- 9
application/admin/controller/UpdateSql.php Bestand weergeven

21
      */
21
      */
22
     static public function addPoolDefaultData()
22
     static public function addPoolDefaultData()
23
     {
23
     {
24
-        # 员工ID
24
+        // 员工ID
25
         $userIds = db('admin_user')->column('id');
25
         $userIds = db('admin_user')->column('id');
26
 
26
 
27
-        # 公海主数据
27
+        // 公海主数据
28
         $poolData = [
28
         $poolData = [
29
             'pool_name'         => '系统默认公海',
29
             'pool_name'         => '系统默认公海',
30
             'admin_user_ids'    => ',1,',
30
             'admin_user_ids'    => ',1,',
42
             'create_time'       => time()
42
             'create_time'       => time()
43
         ];
43
         ];
44
 
44
 
45
-        # 公海规则数据
45
+        // 公海规则数据
46
         $poolRuleData = [
46
         $poolRuleData = [
47
             'pool_id'         => 0,
47
             'pool_id'         => 0,
48
             'type'            => 1,
48
             'type'            => 1,
53
             'limit_day'       => 0
53
             'limit_day'       => 0
54
         ];
54
         ];
55
 
55
 
56
-        # 公海字段数据
56
+        // 公海字段数据
57
         $poolFieldData = [];
57
         $poolFieldData = [];
58
         $fields = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden'])->where(['types' => 'crm_customer'])->select();
58
         $fields = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden'])->where(['types' => 'crm_customer'])->select();
59
         foreach ($fields AS $key => $value) {
59
         foreach ($fields AS $key => $value) {
76
 
76
 
77
         Db::startTrans();
77
         Db::startTrans();
78
         try {
78
         try {
79
-            # 添加公海主数据
79
+            // 添加公海主数据
80
             $poolId = Db::name('crm_customer_pool')->insert($poolData, false, true);
80
             $poolId = Db::name('crm_customer_pool')->insert($poolData, false, true);
81
 
81
 
82
-            # 添加公海规则数据
82
+            // 添加公海规则数据
83
             $poolRuleData['pool_id'] = $poolId;
83
             $poolRuleData['pool_id'] = $poolId;
84
             Db::name('crm_customer_pool_rule')->insert($poolRuleData);
84
             Db::name('crm_customer_pool_rule')->insert($poolRuleData);
85
 
85
 
86
-            # 添加公海字段数据
86
+            // 添加公海字段数据
87
             array_walk($poolFieldData, function (&$val) use ($poolId) {
87
             array_walk($poolFieldData, function (&$val) use ($poolId) {
88
                 $val['pool_id'] = $poolId;
88
                 $val['pool_id'] = $poolId;
89
             });
89
             });
107
      */
107
      */
108
     static public function addFollowRuleData()
108
     static public function addFollowRuleData()
109
     {
109
     {
110
-        # 删除旧版的跟进记录权限规则数据
110
+        // 删除旧版的跟进记录权限规则数据
111
         db('admin_rule')->where(['types' => 2, 'title' => '跟进记录管理', 'name' => 'record', 'level' => 2, 'pid' => 1])->delete();
111
         db('admin_rule')->where(['types' => 2, 'title' => '跟进记录管理', 'name' => 'record', 'level' => 2, 'pid' => 1])->delete();
112
 
112
 
113
-        # 新版跟进记录权限规则增加导入导出
113
+        // 新版跟进记录权限规则增加导入导出
114
         $activityPid = db('admin_rule')->where(['types' => 2, 'title' => '跟进记录', 'name' => 'activity', 'level' => 2])->value('id');
114
         $activityPid = db('admin_rule')->where(['types' => 2, 'title' => '跟进记录', 'name' => 'activity', 'level' => 2])->value('id');
115
         if (!db('admin_rule')->where(['types' => 2, 'pid' => $activityPid, 'name' => 'excelImport'])->value('id')) {
115
         if (!db('admin_rule')->where(['types' => 2, 'pid' => $activityPid, 'name' => 'excelImport'])->value('id')) {
116
             db('admin_rule')->insert(['types' => 2, 'title' => '导入', 'name' => 'excelImport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]);
116
             db('admin_rule')->insert(['types' => 2, 'title' => '导入', 'name' => 'excelImport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]);
119
             db('admin_rule')->insert(['types' => 2, 'title' => '导出', 'name' => 'excelExport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]);
119
             db('admin_rule')->insert(['types' => 2, 'title' => '导出', 'name' => 'excelExport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]);
120
         }
120
         }
121
     }
121
     }
122
+
123
+    /**
124
+     * 处理11.0.3升级时,没有处理旧公海数据的问题
125
+     *
126
+     * @author fanqi
127
+     * @since 2021-06-23
128
+     */
129
+    static public function SynchronizationCustomerToPool()
130
+    {
131
+        $poolData    = [];
132
+        $installData = [];
133
+        $updateData  = [];
134
+
135
+        // 公海数据
136
+        $poolList = db('crm_customer_pool')->alias('pool')
137
+            ->join('__CRM_CUSTOMER_POOL_RELATION__ relation', 'pool.pool_id = relation.pool_id', 'INNER')
138
+            ->field(['relation.pool_id', 'relation.customer_id'])->select();
139
+        // 整理公海数据
140
+        foreach ($poolList AS $key => $value) {
141
+            $poolData[$value['pool_id']][] = $value['customer_id'];
142
+        }
143
+
144
+        // 没有负责人和没有进入公海时间的客户
145
+        $customerIds = db('crm_customer')->where(['owner_user_id' => 0, 'into_pool_time' => 0])->column('customer_id');
146
+
147
+        // 整理要添加(公海客户管理表)和要编辑的数据(修改客户的进入公海时间)
148
+        foreach ($customerIds AS $key => $value) {
149
+            foreach ($poolData AS $k => $v) {
150
+                if (!in_array($value, $v)) {
151
+                    $installData[] = [
152
+                        'pool_id' => $k,
153
+                        'customer_id' => $value
154
+                    ];
155
+                    $updateData[] = $value;
156
+                }
157
+            }
158
+        }
159
+
160
+        // 添加至公海客户关联表
161
+        if (!empty($installData)) {
162
+            db('crm_customer_pool_relation')->insertAll($installData);
163
+        }
164
+
165
+        // 更新客户的进入公海时间
166
+        if (!empty($updateData)) {
167
+            db('crm_customer')->whereIn('customer_id', array_unique($updateData))->exp('before_owner_user_id', 'create_user_id')->update(['into_pool_time' => time()]);
168
+        }
169
+    }
170
+
171
+    /**
172
+     * 发票导出权限
173
+     *
174
+     * @author fanqi
175
+     * @since 2021-06-24
176
+     */
177
+    static public function createInvoiceExportRule()
178
+    {
179
+        // 发票导出权限
180
+        $invoiceId = db('admin_rule')->where(['types' => 2, 'title' => '发票管理', 'name' => 'invoice', 'level' => 2, 'pid' => 1])->value('id');
181
+
182
+        if (!empty($invoiceId)) {
183
+            db('admin_rule')->insert(['types' => 2, 'title' => '导出', 'name' => 'excelExport', 'level' => 3, 'pid' => $invoiceId, 'status' => 1]);
184
+        }
185
+    }
186
+
187
+    /**
188
+     * 修改数字字段类型
189
+     *
190
+     * @author fanqi
191
+     * @since 2021-06-24
192
+     */
193
+    static public function updateFieldNumberType()
194
+    {
195
+        $leadsList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_leads', 'form_type' => 'number'])->select();
196
+        foreach ($leadsList AS $key => $value) {
197
+            Db::execute("ALTER TABLE `5kcrm_crm_leads` MODIFY COLUMN `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
198
+        }
199
+        $customerList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_customer', 'form_type' => 'number'])->select();
200
+        foreach ($customerList AS $key => $value) {
201
+            Db::execute("ALTER TABLE `5kcrm_crm_customer` MODIFY COLUMN  `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
202
+        }
203
+        $contactsList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_contacts', 'form_type' => 'number'])->select();
204
+        foreach ($contactsList AS $key => $value) {
205
+            Db::execute("ALTER TABLE `5kcrm_crm_contacts` MODIFY COLUMN  `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
206
+        }
207
+        $businessList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_business', 'form_type' => 'number'])->select();
208
+        foreach ($businessList AS $key => $value) {
209
+            Db::execute("ALTER TABLE `5kcrm_crm_business` MODIFY COLUMN  `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
210
+        }
211
+        $contractList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_contract', 'form_type' => 'number'])->select();
212
+        foreach ($contractList AS $key => $value) {
213
+            Db::execute("ALTER TABLE `5kcrm_crm_contract` MODIFY COLUMN  `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
214
+        }
215
+        $receivablesList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_receivables', 'form_type' => 'number'])->select();
216
+        foreach ($receivablesList AS $key => $value) {
217
+            Db::execute("ALTER TABLE `5kcrm_crm_receivables` MODIFY COLUMN  `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
218
+        }
219
+        $visitList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_visit', 'form_type' => 'number'])->select();
220
+        foreach ($visitList AS $key => $value) {
221
+            Db::execute("ALTER TABLE `5kcrm_crm_visit` MODIFY COLUMN  `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
222
+        }
223
+        $productList = db("admin_field")->field(['field', 'name', 'default_value'])->where(['types' => 'crm_product', 'form_type' => 'number'])->select();
224
+        foreach ($productList AS $key => $value) {
225
+            Db::execute("ALTER TABLE `5kcrm_crm_product` MODIFY COLUMN  `".$value['field']."` VARCHAR(255) NULL ".$value['default_value']." COMMENT '".$value['name']."'");
226
+        }
227
+    }
122
 }
228
 }

+ 71
- 3
application/admin/controller/Users.php Bestand weergeven

98
         }
98
         }
99
         $serverUserInfo = $this->queryLoginUser();
99
         $serverUserInfo = $this->queryLoginUser();
100
         if (!empty($serverUserInfo)) $data['serverUserInfo'] = $serverUserInfo;
100
         if (!empty($serverUserInfo)) $data['serverUserInfo'] = $serverUserInfo;
101
+
102
+        # 角色权限查看  配置范围对应id
103
+        $rule_authority_id =  db('admin_rule')->where(['title' => '角色权限查看', 'name' => 'ruleList'])->value('id');
104
+        $data['rule_authority_id'] = $rule_authority_id;
105
+
106
+        # 数据库更新 todo 在线升级正常使用后删除
107
+        $updateStatus = $this->executeUpdateSql();
108
+        if (empty($updateStatus['status'])) return resultArray(['error' => $updateStatus['message']]);
109
+
101
         return resultArray(['data' => $data]);
110
         return resultArray(['data' => $data]);
102
     }
111
     }
112
+
113
+    /**
114
+     * 更新SQL
115
+     *
116
+     * @author fanqi
117
+     * @since 2021-05-08
118
+     */
119
+    public function executeUpdateSql()
120
+    {
121
+        // 表前缀
122
+        $prefix = config('database.prefix');
123
+
124
+        // 检查更新记录表是否存在
125
+        if (!db()->query("SHOW TABLES LIKE '".$prefix."admin_upgrade_record'")) {
126
+            db()->query("
127
+                CREATE TABLE `".$prefix."admin_upgrade_record` (
128
+                  `version` int(10) unsigned DEFAULT NULL COMMENT '版本号',
129
+                  UNIQUE KEY `version` (`version`) USING BTREE
130
+                ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT = 'SQL更新记录,用于防止重复执行更新。'
131
+            ");
132
+        }
133
+
134
+        // 检查是否执行过11.0.3版本的更新
135
+        if (!db('admin_upgrade_record')->where('version', 1103)->value('version')) {
136
+            // 添加跟进记录导入导出权限数据
137
+            UpdateSql::addFollowRuleData();
138
+
139
+            // 添加公海默认数据
140
+            $poolStatus = UpdateSql::addPoolDefaultData();
141
+            if (!$poolStatus) return ['status' => false, 'message' => '添加公海默认配置失败,请在后台手动添加!'];
142
+
143
+            // 添加此次升级标记
144
+            db('admin_upgrade_record')->insert(['version' => 1103]);
145
+
146
+            return ['status' => true, 'message' => '更新完成!'];
147
+        }
148
+
149
+        // 检查是否执行过11.0.4版本的更新
150
+        if (!db('admin_upgrade_record')->where('version', 1104)->value('version')) {
151
+            // 处理11.0.3升级时,没有处理旧公海数据的问题
152
+            UpdateSql::SynchronizationCustomerToPool();
153
+
154
+            // 发票导出权限
155
+            UpdateSql::createInvoiceExportRule();
156
+
157
+            // 修改数字字段类型
158
+            UpdateSql::updateFieldNumberType();
159
+
160
+            // 添加此次升级标记
161
+            db('admin_upgrade_record')->insert(['version' => 1104]);
162
+        }
163
+
164
+        return ['status' => true, 'message' => '没有可用更新!'];
165
+    }
103
     
166
     
104
     /**
167
     /**
105
      * 员工创建
168
      * 员工创建
111
         $userModel = model('User');
174
         $userModel = model('User');
112
         $param = $this->param;
175
         $param = $this->param;
113
         $userInfo = $this->userInfo;
176
         $userInfo = $this->userInfo;
177
+        $param['userId']=$userInfo['id'];
114
         $data = $userModel->createData($param);
178
         $data = $userModel->createData($param);
115
         if (!$data) {
179
         if (!$data) {
116
             return resultArray(['error' => $userModel->getError()]);
180
             return resultArray(['error' => $userModel->getError()]);
138
                 header('Content-Type:application/json; charset=utf-8');
202
                 header('Content-Type:application/json; charset=utf-8');
139
                 exit(json_encode(['code' => 102, 'error' => '无权操作']));
203
                 exit(json_encode(['code' => 102, 'error' => '无权操作']));
140
             }
204
             }
205
+            $param['userId']=$userInfo['id'];
141
         }
206
         }
142
         unset($param['username']);
207
         unset($param['username']);
143
         $data = $userModel->updateDataById($param, $param['id']);
208
         $data = $userModel->updateDataById($param, $param['id']);
158
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
223
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
159
         }
224
         }
160
         $param = $this->param;
225
         $param = $this->param;
226
+        $userInfo=$this->userInfo;
227
+        $param['user_id']=$userInfo['id'];
161
         if ($param['password'] && is_array($param['id'])) {
228
         if ($param['password'] && is_array($param['id'])) {
162
             $userModel = model('User');
229
             $userModel = model('User');
163
             $ret = $userModel->updatePwdById($param);
230
             $ret = $userModel->updatePwdById($param);
322
         $param = $this->param;
389
         $param = $this->param;
323
         $userInfo = $this->userInfo;
390
         $userInfo = $this->userInfo;
324
         $userModel = model('User');
391
         $userModel = model('User');
325
-        
392
+        $userId=$userInfo['id'];
326
         if (empty($param['new_pwd']) || empty($param['old_pwd'])) return resultArray(['error' => '密码不能为空!']);
393
         if (empty($param['new_pwd']) || empty($param['old_pwd'])) return resultArray(['error' => '密码不能为空!']);
327
         
394
         
328
         if ($param['id'] && (int)$param['id'] !== $userInfo['id']) {
395
         if ($param['id'] && (int)$param['id'] !== $userInfo['id']) {
359
             $userModel = model('User');
426
             $userModel = model('User');
360
             $old_pwd = $param['old_pwd'];
427
             $old_pwd = $param['old_pwd'];
361
             $new_pwd = $param['new_pwd'];
428
             $new_pwd = $param['new_pwd'];
362
-            $data = $userModel->updatePaw($userInfo, $old_pwd, $new_pwd);
429
+            $data = $userModel->updatePaw($userInfo, $old_pwd, $new_pwd,$userId);
363
             if (!$data) {
430
             if (!$data) {
364
                 return resultArray(['error' => $userModel->getError()]);
431
                 return resultArray(['error' => $userModel->getError()]);
365
             }
432
             }
721
         if (empty($param['group_id'])) return resultArray(['error' => '请选择角色!']);
788
         if (empty($param['group_id'])) return resultArray(['error' => '请选择角色!']);
722
         
789
         
723
         $userModel = new User();
790
         $userModel = new User();
724
-        
791
+        $userInfo=$this->userInfo;
792
+        $param['userId']=$userInfo['id'];
725
         if (!$userModel->copyRole($param)) return resultArray(['error' => '操作失败!']);
793
         if (!$userModel->copyRole($param)) return resultArray(['error' => '操作失败!']);
726
         
794
         
727
         return resultArray(['data' => '操作成功!']);
795
         return resultArray(['data' => '操作成功!']);

+ 6
- 5
application/admin/controller/Work.php Bestand weergeven

125
     {
125
     {
126
         if (empty($this->param['id']))    return resultArray(['error' => '请选择要编辑的权限角色!']);
126
         if (empty($this->param['id']))    return resultArray(['error' => '请选择要编辑的权限角色!']);
127
         if (empty($this->param['title'])) return resultArray(['error' => '请填写权限名称!']);
127
         if (empty($this->param['title'])) return resultArray(['error' => '请填写权限名称!']);
128
+        $userInfo=$this->userInfo;
129
+        $this->param['user_id']=$userInfo['id'];
128
         $data=$workLogic->updateRole($this->param);
130
         $data=$workLogic->updateRole($this->param);
129
-        if (empty($data)) return resultArray(['error' => '操作失败!']);
130
-
131
-        return resultArray(['data' => '操作成功!']);
131
+        if ($data!==false)return resultArray(['data' => '操作成功!']);
132
+        return resultArray(['error' => '操作失败!']);
132
     }
133
     }
133
 
134
 
134
     /**
135
     /**
142
     public function deleteRole(WorkLogic $workLogic)
143
     public function deleteRole(WorkLogic $workLogic)
143
     {
144
     {
144
         if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的权限角色!']);
145
         if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的权限角色!']);
145
-
146
-        $result = $workLogic->deleteRole($this->param['id']);
146
+        $userInfo=$this->userInfo;
147
+        $result = $workLogic->deleteRole($this->param['id'],$userInfo['id']);
147
 
148
 
148
         if (empty($result['status'])) return resultArray(['error' => $result['error']]);
149
         if (empty($result['status'])) return resultArray(['error' => $result['error']]);
149
 
150
 

+ 55
- 1
application/admin/logic/FieldGrantLogic.php Bestand weergeven

46
         'visit' => [
46
         'visit' => [
47
             'number', 'visit_time', 'owner_user_id', 'shape', 'customer_id', 'contacts_id', 'contract_id', 'satisfaction',
47
             'number', 'visit_time', 'owner_user_id', 'shape', 'customer_id', 'contacts_id', 'contract_id', 'satisfaction',
48
             'feedback', 'create_user_id', 'create_time', 'update_time'
48
             'feedback', 'create_user_id', 'create_time', 'update_time'
49
-        ]
49
+        ],
50
+        'invoice' => [
51
+            'invoice_apple_number', 'customer_id', 'contract_id', 'contract_money', 'invoice_date', 'invoice_money', 'invoice_type', 'remark'
52
+        ],
50
     ];
53
     ];
51
 
54
 
52
     /**
55
     /**
90
      */
93
      */
91
     public function createCrmFieldGrant($roleId)
94
     public function createCrmFieldGrant($roleId)
92
     {
95
     {
96
+        # 防止重复,先删除一下
97
+        $this->deleteCrmFieldGrant($roleId);
93
         # 添加线索字段授权数据
98
         # 添加线索字段授权数据
94
         $this->createLeadsFieldGrant($roleId);
99
         $this->createLeadsFieldGrant($roleId);
95
         # 添加客户字段授权数据
100
         # 添加客户字段授权数据
106
         $this->createProductFieldGrant($roleId);
111
         $this->createProductFieldGrant($roleId);
107
         # 添加回访字段授权信息
112
         # 添加回访字段授权信息
108
         $this->createVisitFieldGrant($roleId);
113
         $this->createVisitFieldGrant($roleId);
114
+        # 添加发票字段授权信息
115
+        $this->createInvoiceFieldGrant($roleId);
109
     }
116
     }
110
 
117
 
111
     /**
118
     /**
678
             'update_time' => time()
685
             'update_time' => time()
679
         ]);
686
         ]);
680
     }
687
     }
688
+
689
+    /**
690
+     * 处理回访字段授权信息
691
+     *
692
+     * @param $roleId
693
+     * @author fanqi
694
+     * @since 2021-06-25
695
+     */
696
+    private function createInvoiceFieldGrant($roleId)
697
+    {
698
+        $content = [
699
+            ['field' => 'invoice_apple_number', 'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '发票申请编号'],
700
+            ['field' => 'customer_id',          'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '客户名称'],
701
+            ['field' => 'contract_id',          'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '合同编号'],
702
+            ['field' => 'contract_money',       'read' => 1, 'read_operation' => 0, 'write' => 1, 'write_operation' => 0, 'is_diy' => 0, 'name' => '合同金额'],
703
+            ['field' => 'invoice_money',        'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '开票金额'],
704
+            ['field' => 'invoice_date',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '开票日期'],
705
+            ['field' => 'invoice_type',         'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '开票类型'],
706
+            ['field' => 'remark',               'read' => 1, 'read_operation' => 1, 'write' => 1, 'write_operation' => 1, 'is_diy' => 0, 'name' => '备注'],
707
+        ];
708
+
709
+        $invoiceList = Db::name('admin_field')->field(['name', 'field'])->where('types', 'crm_invoice')->select();
710
+
711
+        # 处理自定义字段
712
+        foreach ($invoiceList AS $key => $value) {
713
+            if (in_array($value['field'], $this->except['invoice'])) continue;
714
+
715
+            $content[] = [
716
+                'name'            => $value['name'],
717
+                'field'           => $value['field'],
718
+                'read'            => 1,
719
+                'read_operation'  => 1,
720
+                'write'           => 1,
721
+                'write_operation' => 1,
722
+                'is_diy'          => 1
723
+            ];
724
+        }
725
+
726
+        Db::name('admin_field_grant')->insert([
727
+            'role_id'     => $roleId,
728
+            'module'      => 'crm',
729
+            'column'      => 'invoice',
730
+            'content'     => serialize($content),
731
+            'create_time' => time(),
732
+            'update_time' => time()
733
+        ]);
734
+    }
681
 }
735
 }

+ 24
- 38
application/admin/logic/InitializeLogic.php Bestand weergeven

440
             # ------ 重置自动编号数据 END ------ #
440
             # ------ 重置自动编号数据 END ------ #
441
 
441
 
442
 
442
 
443
+            # ------ 重置扩展数据 START ------ #
444
+            Db::query("TRUNCATE TABLE ".$prefix."crm_leads_data");
445
+            Db::query("TRUNCATE TABLE ".$prefix."crm_customer_data");
446
+            Db::query("TRUNCATE TABLE ".$prefix."crm_contacts_data");
447
+            Db::query("TRUNCATE TABLE ".$prefix."crm_business_data");
448
+            Db::query("TRUNCATE TABLE ".$prefix."crm_contract_data");
449
+            Db::query("TRUNCATE TABLE ".$prefix."crm_receivables_data");
450
+            Db::query("TRUNCATE TABLE ".$prefix."crm_receivables_plan_data");
451
+            Db::query("TRUNCATE TABLE ".$prefix."crm_invoice_data");
452
+            Db::query("TRUNCATE TABLE ".$prefix."crm_visit_data");
453
+            Db::query("TRUNCATE TABLE ".$prefix."crm_product_data");
454
+            # ------ 重置扩展数据 END ------ #
455
+
456
+
457
+            # ------ 清除待办事项关联数据 START ------ #
458
+            Db::query("TRUNCATE TABLE ".$prefix."crm_dealt_relation");
459
+            # ------ 清除待办事项关联数据 END ------ #
460
+
461
+
443
             # ------ 设置跟进记录常用语 START ------ #
462
             # ------ 设置跟进记录常用语 START ------ #
444
             $phrase = ['电话无人接听', '客户无意向', '客户意向度适中,后续继续跟进', '客户意向度较强,成交几率较大'];
463
             $phrase = ['电话无人接听', '客户无意向', '客户意向度适中,后续继续跟进', '客户意向度较强,成交几率较大'];
445
             $phraseId = db('crm_config')->where('name', 'activity_phrase')->value('id');
464
             $phraseId = db('crm_config')->where('name', 'activity_phrase')->value('id');
515
         # 启动事务
534
         # 启动事务
516
         Db::startTrans();
535
         Db::startTrans();
517
         try {
536
         try {
518
-            # ------ 清除任务数据 START ------ #
519
-
520
-//            # 获取任务ID
521
-//            $taskIds = Db::name('task')->where(['work_id' => ['eq', 0]])->column('task_id');
522
-//
523
-//            # 获取任务下关联的附件ID
524
-//            $taskFieldIds = Db::name('work_task_file')->whereIn('task_id', $taskIds)->column('file_id');
525
-//
526
-//            # 查询活动附件数据
527
-//            $taskFileInfo = $this->getFileList($taskFieldIds);
528
-//
529
-//            # 合并附件数据
530
-//            $files = array_merge($files, $taskFileInfo);
531
-//
532
-//            # 删除任务附件关联表
533
-//            Db::name('work_task_file')->whereIn('task_id', $taskIds)->delete();
534
-//            # 重置自增ID
535
-//            Db::query("ALTER TABLE ".$prefix."work_task_file AUTO_INCREMENT = 1");
536
-//
537
-//            # 删除附件
538
-//            Db::name('admin_file')->whereIn('file_id', $taskFieldIds)->delete();
539
-//
540
-//            # 清除任务关联的客户模块数据数据并重置自增ID
541
-//            Db::query("TRUNCATE TABLE ".$prefix."task_relation");
542
-//
543
-//            # 删除任务log
544
-//            Db::name('work_task_log')->whereIn('task_id', $taskIds)->delete();
545
-//            # 重置任务log自增ID
546
-//            Db::query("ALTER TABLE ".$prefix."work_task_log AUTO_INCREMENT = 1");
547
-//
548
-//            # 删除任务
549
-//            Db::name('task')->where(['work_id' => ['eq', 0]])->delete();
550
-//            # 重置任务自增ID
551
-//            Db::query("ALTER TABLE ".$prefix."task AUTO_INCREMENT = 1");
552
-
553
-            # ------ 清除任务数据 END ------ #
554
-
555
-
556
             # ------ 清除审批数据 START ------ #
537
             # ------ 清除审批数据 START ------ #
557
 
538
 
558
             # 获取审批下关联的附件ID
539
             # 获取审批下关联的附件ID
595
             # ------ 清除审批数据 END ------ #
576
             # ------ 清除审批数据 END ------ #
596
 
577
 
597
 
578
 
579
+            # ------ 重置扩展数据 START ------ #
580
+            Db::query("TRUNCATE TABLE ".$prefix."oa_examine_data");
581
+            # ------ 重置扩展数据 END ------ #
582
+
583
+
598
             # ------ 清除活动中有关审批的数据 START ------ #
584
             # ------ 清除活动中有关审批的数据 START ------ #
599
 
585
 
600
             # 获取有关审批的活动ID
586
             # 获取有关审批的活动ID

+ 2
- 2
application/admin/logic/LogLogic.php Bestand weergeven

245
                 'action'      => in_array('crm',explode('_',$value['module']))==1?
245
                 'action'      => in_array('crm',explode('_',$value['module']))==1?
246
                     '客户管理':(in_array('oa',explode('_',$value['module']))==1?'办公管理':'项目管理'),
246
                     '客户管理':(in_array('oa',explode('_',$value['module']))==1?'办公管理':'项目管理'),
247
                 'content'     => $value['content'],
247
                 'content'     => $value['content'],
248
-                'user_name'     => $value['realname'],
248
+                'user_name'     => $value['realname']?:'系统',
249
                 'action_name'     =>  $this->action[$value['action_name']],
249
                 'action_name'     =>  $this->action[$value['action_name']],
250
             ];
250
             ];
251
         }
251
         }
270
                 'ip'          => $value['client_ip'],
270
                 'ip'          => $value['client_ip'],
271
                 'action'      => $this->systemModules[$value['module_name']],
271
                 'action'      => $this->systemModules[$value['module_name']],
272
                 'content'     => $value['content'],
272
                 'content'     => $value['content'],
273
-                'user_name'     => $value['realname'],
273
+                'user_name'     => $value['realname']?:'系统',
274
                 'action_name'     => $this->action[$value['action_name']],
274
                 'action_name'     => $this->action[$value['action_name']],
275
                 'module'     => '后台管理',
275
                 'module'     => '后台管理',
276
                 'action_down'     => $this->recordModules[$value['controller_name']]?:'',
276
                 'action_down'     => $this->recordModules[$value['controller_name']]?:'',

+ 2
- 2
application/admin/logic/MessageLogic.php Bestand weergeven

245
         $where['is_delete'] = ['eq', 1];
245
         $where['is_delete'] = ['eq', 1];
246
         
246
         
247
         $where['type'] = $this->label('');
247
         $where['type'] = $this->label('');
248
-        $allCount = db('admin_message')->where($where)->count();
248
+        $allCount = db('admin_message')->where($where)->where(['advance_time'=>['<', time()]])->count();
249
         $where['type'] = $this->label(1);
249
         $where['type'] = $this->label(1);
250
         $taskCount = db('admin_message')->where($where)->count();
250
         $taskCount = db('admin_message')->where($where)->count();
251
         $where['type'] = $this->label(2);
251
         $where['type'] = $this->label(2);
255
         $where['type'] = 9;
255
         $where['type'] = 9;
256
         $announceCount = db('admin_message')->where($where)->count();
256
         $announceCount = db('admin_message')->where($where)->count();
257
         $where['type'] = $this->label(5);
257
         $where['type'] = $this->label(5);
258
-        $eventCount = db('admin_message')->where($where)->where(['advance_time'=>['<', time()],'advance_time'=>['<>',0]])->count();
258
+        $eventCount = db('admin_message')->where($where)->where(['advance_time'=>['<', time()]])->count();
259
         $where['type'] = $this->label(6);
259
         $where['type'] = $this->label(6);
260
         $crmCount = db('admin_message')->where($where)->count();
260
         $crmCount = db('admin_message')->where($where)->count();
261
         
261
         

+ 38
- 15
application/admin/logic/PoolConfigLogic.php Bestand weergeven

273
             # 删除用户保存的公海字段数据
273
             # 删除用户保存的公海字段数据
274
             Db::name('crm_customer_pool_field_style')->where('pool_id', $poolId)->delete();
274
             Db::name('crm_customer_pool_field_style')->where('pool_id', $poolId)->delete();
275
 
275
 
276
+            # 删除公海操作记录数据
277
+            Db::name('crm_customer_pool_record')->where('pool_id', $poolId)->delete();
278
+
276
             # 删除公海数据
279
             # 删除公海数据
277
             Db::name('crm_customer_pool')->where('pool_id', $poolId)->delete();
280
             Db::name('crm_customer_pool')->where('pool_id', $poolId)->delete();
278
 
281
 
361
     public function getPoolFieldList($param)
364
     public function getPoolFieldList($param)
362
     {
365
     {
363
         if (!empty($param['pool_id'])) {
366
         if (!empty($param['pool_id'])) {
364
-            return db('crm_customer_pool_field_setting')->field(['field_name AS field', 'name', 'form_type', 'is_hidden'])->where('pool_id', $param['pool_id'])->select();
367
+            return db('crm_customer_pool_field_setting')->field(['field_name AS field', 'name', 'form_type', 'is_hidden', 'is_null', 'is_unique'])->where('pool_id', $param['pool_id'])->select();
365
         } else {
368
         } else {
366
-            $data = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden'])->where(['types' => 'crm_customer'])->select();
369
+            $data = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden', 'is_null', 'is_unique'])->where(['types' => 'crm_customer'])->select();
367
 
370
 
368
             $address = [
371
             $address = [
369
                 'field'     => 'address',
372
                 'field'     => 'address',
370
                 'name'      => '省、市、区/县',
373
                 'name'      => '省、市、区/县',
371
                 'form_type' => 'customer_address',
374
                 'form_type' => 'customer_address',
372
-                'is_hidden' => 0
375
+                'is_hidden' => 0,
376
+                'is_null'   => 0,
377
+                'is_unique' => 0,
373
             ];
378
             ];
374
             $detailAddress = [
379
             $detailAddress = [
375
                 'field'     => 'detail_address',
380
                 'field'     => 'detail_address',
376
                 'name'      => '详细地址',
381
                 'name'      => '详细地址',
377
                 'form_type' => 'text',
382
                 'form_type' => 'text',
378
-                'is_hidden' => 0
383
+                'is_hidden' => 0,
384
+                'is_null'   => 0,
385
+                'is_unique' => 0,
379
             ];
386
             ];
380
             $lastRecord = [
387
             $lastRecord = [
381
                 'field'     => 'last_record',
388
                 'field'     => 'last_record',
382
                 'name'      => '最后跟进记录',
389
                 'name'      => '最后跟进记录',
383
                 'form_type' => 'text',
390
                 'form_type' => 'text',
384
-                'is_hidden' => 0
391
+                'is_hidden' => 0,
392
+                'is_null'   => 0,
393
+                'is_unique' => 0,
385
             ];
394
             ];
386
             $lastTime = [
395
             $lastTime = [
387
                 'field'     => 'last_time',
396
                 'field'     => 'last_time',
388
                 'name'      => '最后跟进时间',
397
                 'name'      => '最后跟进时间',
389
                 'form_type' => 'datetime',
398
                 'form_type' => 'datetime',
390
-                'is_hidden' => 0
399
+                'is_hidden' => 0,
400
+                'is_null'   => 0,
401
+                'is_unique' => 0,
391
             ];
402
             ];
392
             $beforeOwnerUser = [
403
             $beforeOwnerUser = [
393
                 'field'     => 'before_owner_user_id',
404
                 'field'     => 'before_owner_user_id',
394
                 'name'      => '前负责人',
405
                 'name'      => '前负责人',
395
                 'form_type' => 'user',
406
                 'form_type' => 'user',
396
-                'is_hidden' => 0
407
+                'is_hidden' => 0,
408
+                'is_null'   => 0,
409
+                'is_unique' => 0,
397
             ];
410
             ];
398
             $intoPoolTime = [
411
             $intoPoolTime = [
399
                 'field'     => 'into_pool_time',
412
                 'field'     => 'into_pool_time',
400
                 'name'      => '进入公海时间',
413
                 'name'      => '进入公海时间',
401
                 'form_type' => 'datetime',
414
                 'form_type' => 'datetime',
402
-                'is_hidden' => 0
415
+                'is_hidden' => 0,
416
+                'is_null'   => 0,
417
+                'is_unique' => 0,
403
             ];
418
             ];
404
             $createTime = [
419
             $createTime = [
405
                 'field'     => 'create_time',
420
                 'field'     => 'create_time',
406
                 'name'      => '创建时间',
421
                 'name'      => '创建时间',
407
                 'form_type' => 'datetime',
422
                 'form_type' => 'datetime',
408
-                'is_hidden' => 0
423
+                'is_hidden' => 0,
424
+                'is_null'   => 0,
425
+                'is_unique' => 0,
409
             ];
426
             ];
410
             $updateTime = [
427
             $updateTime = [
411
                 'field'     => 'update_time',
428
                 'field'     => 'update_time',
412
                 'name'      => '更新时间',
429
                 'name'      => '更新时间',
413
                 'form_type' => 'datetime',
430
                 'form_type' => 'datetime',
414
-                'is_hidden' => 0
431
+                'is_hidden' => 0,
432
+                'is_null'   => 0,
433
+                'is_unique' => 0,
415
             ];
434
             ];
416
             $createUser = [
435
             $createUser = [
417
                 'field'     => 'create_user_id',
436
                 'field'     => 'create_user_id',
418
                 'name'      => '创建人',
437
                 'name'      => '创建人',
419
                 'form_type' => 'user',
438
                 'form_type' => 'user',
420
-                'is_hidden' => 0
439
+                'is_hidden' => 0,
440
+                'is_null'   => 0,
441
+                'is_unique' => 0,
421
             ];
442
             ];
422
             array_push($data, $address, $detailAddress, $lastRecord, $lastTime, $createTime, $updateTime, $createUser, $beforeOwnerUser, $intoPoolTime);
443
             array_push($data, $address, $detailAddress, $lastRecord, $lastTime, $createTime, $updateTime, $createUser, $beforeOwnerUser, $intoPoolTime);
423
 
444
 
468
 
489
 
469
         foreach ($fields AS $key => $value) {
490
         foreach ($fields AS $key => $value) {
470
             $result[] = [
491
             $result[] = [
471
-                'pool_id' => $poolId,
472
-                'name' => $value['name'],
492
+                'pool_id'    => $poolId,
493
+                'name'       => $value['name'],
473
                 'field_name' => $value['field'],
494
                 'field_name' => $value['field'],
474
-                'form_type' => $value['form_type'],
475
-                'is_hidden' => $value['is_hidden']
495
+                'form_type'  => $value['form_type'],
496
+                'is_hidden'  => $value['is_hidden'],
497
+                'is_null'    => $value['is_null'],
498
+                'is_unique'  => $value['is_unique']
476
             ];
499
             ];
477
         }
500
         }
478
 
501
 

+ 5
- 7
application/admin/logic/WorkLogic.php Bestand weergeven

92
     public function updateRole($param)
92
     public function updateRole($param)
93
     {
93
     {
94
         $res=Db::name('admin_group')->where('id',$param['id'])->find();
94
         $res=Db::name('admin_group')->where('id',$param['id'])->find();
95
+        $userInd=$param['user_id'];
96
+        unset($param['user_id']);
95
         if(!$res){
97
         if(!$res){
96
             return false;
98
             return false;
97
         }else{
99
         }else{
98
             $data=Db::name('admin_group')->update($param);
100
             $data=Db::name('admin_group')->update($param);
99
             # 添加系统操作日志
101
             # 添加系统操作日志
100
-            $user=new ApiCommon();
101
-            $userInfo=$user->userInfo;
102
-            SystemActionLog($userInfo['id'], 'admin_group','project', $param['id'], 'update',$res['title'] , '', '','编辑了项目管理权限:'.$res['title']);
102
+            SystemActionLog($userInd, 'admin_group','project', $param['id'], 'update',$res['title'] , '', '','编辑了项目管理权限:'.$res['title']);
103
             return $data;
103
             return $data;
104
         }
104
         }
105
        
105
        
113
      * @throws \think\Exception
113
      * @throws \think\Exception
114
      * @throws \think\exception\PDOException
114
      * @throws \think\exception\PDOException
115
      */
115
      */
116
-    public function deleteRole($id)
116
+    public function deleteRole($id,$userId)
117
     {
117
     {
118
         $system = Db::name('admin_group')->where('id', $id)->find();
118
         $system = Db::name('admin_group')->where('id', $id)->find();
119
 
119
 
128
             db('work_user')->where('group_id', $id)->update(['group_id' => $readOnlyId]); # 处理私有项目的权限
128
             db('work_user')->where('group_id', $id)->update(['group_id' => $readOnlyId]); # 处理私有项目的权限
129
         }
129
         }
130
         # 添加系统操作日志
130
         # 添加系统操作日志
131
-        $user=new ApiCommon();
132
-        $userInfo=$user->userInfo;
133
-        SystemActionLog($userInfo['id'], 'admin_group','project', $id, 'update',$system['title'] , '', '','删除了项目管理权限:'.$system['title']);
131
+        SystemActionLog($userId, 'admin_group','project', $id, 'update',$system['title'] , '', '','删除了项目管理权限:'.$system['title']);
134
         return ['status' => true];
132
         return ['status' => true];
135
     }
133
     }
136
 }
134
 }

+ 1
- 1
application/admin/model/ActionRecord.php Bestand weergeven

43
 		}
43
 		}
44
 		$userModel = model('User');
44
 		$userModel = model('User');
45
 		foreach ($dataList as $k=>$v) {
45
 		foreach ($dataList as $k=>$v) {
46
-			$dataList[$k]['user_id_info'] = isset($v['user_id']) ? $userModel->getUserById($v['user_id']) : [];
46
+			$dataList[$k]['user_id_info'] = $v['user_id']!=0 ? $userModel->getUserById($v['user_id']) : '系统';
47
 			$dataList[$k]['content'] = explode('.|.', $v['content']);
47
 			$dataList[$k]['content'] = explode('.|.', $v['content']);
48
 		}
48
 		}
49
 		return $dataList;
49
 		return $dataList;

+ 310
- 306
application/admin/model/Common.php Bestand weergeven

10
 use think\Model;
10
 use think\Model;
11
 use think\Request;
11
 use think\Request;
12
 
12
 
13
-class Common extends Model 
13
+class Common extends Model
14
 {
14
 {
15
-	/**
16
-	 * [Request 请求参数]
17
-	 * @Michael_xu
18
-	 * @return    [array]                       
19
-	 */	
20
-	protected function requestData()
21
-	{
22
-		$m = strtolower(request()->module());
23
-		$c = strtolower(request()->controller());
24
-		$a = strtolower(request()->action());
25
-		$ret = [
26
-			'm' => $m,
27
-			'c' => $c,
28
-			'a' => $a
29
-		];
30
-		return $ret;	
31
-	}
32
-
33
-	/**
34
-	 * [fmtRequest 格式化请求参数]
35
-	 * @Michael_xu
36
-	 * @param     [array]      $request [参数]
37
-	 * @return    [array]                       
38
-	 */
39
-    public function fmtRequest( $request = [] )
15
+    /**
16
+     * [Request 请求参数]
17
+     * @Michael_xu
18
+     * @return    [array]
19
+     */
20
+    protected function requestData()
21
+    {
22
+        $m = strtolower(request()->module());
23
+        $c = strtolower(request()->controller());
24
+        $a = strtolower(request()->action());
25
+        $ret = [
26
+            'm' => $m,
27
+            'c' => $c,
28
+            'a' => $a
29
+        ];
30
+        return $ret;
31
+    }
32
+    
33
+    /**
34
+     * [fmtRequest 格式化请求参数]
35
+     * @Michael_xu
36
+     * @param     [array]      $request [参数]
37
+     * @return    [array]
38
+     */
39
+    public function fmtRequest($request = [])
40
     {
40
     {
41
         $pageType = $request['pageType'] ? 'all' : ''; //all全部(不分页)
41
         $pageType = $request['pageType'] ? 'all' : ''; //all全部(不分页)
42
         $page = 1;
42
         $page = 1;
43
-        if (isset($request['page']) && is_numeric($request['page']) ) {
43
+        if (isset($request['page']) && is_numeric($request['page'])) {
44
             $page = $request['page'];
44
             $page = $request['page'];
45
             unset($request['page']);
45
             unset($request['page']);
46
         }
46
         }
47
         $limit = 15;
47
         $limit = 15;
48
-        if (isset($request['limit']) && is_numeric($request['limit']) ) {
48
+        if (isset($request['limit']) && is_numeric($request['limit'])) {
49
             $limit = $request['limit'];
49
             $limit = $request['limit'];
50
             unset($request['limit']);
50
             unset($request['limit']);
51
-		}
52
-		$offset = $length = null;
51
+        }
52
+        $offset = $length = null;
53
         if ($pageType == 'all') {
53
         if ($pageType == 'all') {
54
-        	$page = 1;
55
-        	$limit = 0;
56
-        	unset($request['pageType']);
57
-		} else {
58
-			// 大数据处理-滚动加载-子分页
59
-			if ($request['sub_page'] && $request['sub_limit']) {
60
-				$sub_page = $request['sub_page'];
61
-				$sub_limit = $request['sub_limit'];
62
-				unset($request['sub_page']);
63
-				unset($request['sub_limit']);
64
-				$offset = ($page - 1) * $limit + ($sub_page - 1) * $sub_limit;
65
-				if ($sub_limit * $sub_page > $limit) {
66
-					$length = ($page - 1) * $limit + $limit - $offset;
67
-				} else {
68
-					$length = $sub_limit;
69
-				}
70
-				if ($length < 0) {
71
-					$offset = $length = 0;
72
-				}
73
-			}
74
-		}
75
-		
76
-		if (!isset($offset) || !isset($length)) {
77
-			$offset = ($page - 1) * $limit;
78
-			$length = $limit;
79
-		}
54
+            $page = 1;
55
+            $limit = 0;
56
+            unset($request['pageType']);
57
+        } else {
58
+            // 大数据处理-滚动加载-子分页
59
+            if ($request['sub_page'] && $request['sub_limit']) {
60
+                $sub_page = $request['sub_page'];
61
+                $sub_limit = $request['sub_limit'];
62
+                unset($request['sub_page']);
63
+                unset($request['sub_limit']);
64
+                $offset = ($page - 1) * $limit + ($sub_page - 1) * $sub_limit;
65
+                if ($sub_limit * $sub_page > $limit) {
66
+                    $length = ($page - 1) * $limit + $limit - $offset;
67
+                } else {
68
+                    $length = $sub_limit;
69
+                }
70
+                if ($length < 0) {
71
+                    $offset = $length = 0;
72
+                }
73
+            }
74
+        }
75
+        
76
+        if (!isset($offset) || !isset($length)) {
77
+            $offset = ($page - 1) * $limit;
78
+            $length = $limit;
79
+        }
80
         $ret = [
80
         $ret = [
81
             'page' => $page,
81
             'page' => $page,
82
             'limit' => $limit,
82
             'limit' => $limit,
83
-			'map' => $request,
84
-			'offset' => $offset,
85
-			'length' => $length,
86
-		];
83
+            'map' => $request,
84
+            'offset' => $offset,
85
+            'length' => $length,
86
+        ];
87
         return $ret;
87
         return $ret;
88
     }
88
     }
89
-	
90
-	/**
91
-	 * [getDataById 根据主键获取详情]
92
-	 * @param     string                   $id [主键]
93
-	 * @return    [array]                       
94
-	 */
95
-	public function getDataById($id = '')
96
-	{
97
-		$data = $this->get($id);
98
-		if (!$data) {
99
-			$this->error = '暂无此数据';
100
-			return false;
101
-		}
102
-		return $data;
103
-	}
104
-
105
-	/**
106
-	 * [createData 新建]
107
-	 * @param     array                    $param [description]
108
-	 * @return    [array]                         [description]
109
-	 */
110
-	public function createData($param)
111
-	{	
112
-		// 验证
113
-		$validate = validate($this->name);
114
-		if (!$validate->check($param)) {
115
-			$this->error = $validate->getError();
116
-			return false;
117
-		}
118
-		try {
119
-			$this->data($param)->allowField(true)->save();
120
-			return true;
121
-		} catch(\Exception $e) {
122
-			$this->error = '添加失败';
123
-			return false;
124
-		}
125
-	}
126
-
127
-	/**
128
-	 * [updateDataById 编辑]
129
-	 * @param     [type]                   $param [description]
130
-	 * @param     [type]                   $id    [description]
131
-	 * @return    [type]                          [description]
132
-	 */
133
-	public function updateDataById($param, $id)
134
-	{
135
-		$checkData = $this->get($id);
136
-		if (!$checkData) {
137
-			$this->error = '暂无此数据';
138
-			return false;
139
-		}
140
-
141
-		// 验证
142
-		$validate = validate($this->name);
143
-		if (!$validate->scene('edit')->check($param)) {
144
-			$this->error = $validate->getError();
145
-			return false;
146
-		}
147
-
148
-		try {
149
-			$this->allowField(true)->save($param, [$this->getPk() => $id]);
150
-			return true;
151
-		} catch(\Exception $e) {
152
-			$this->error = '编辑失败';
153
-			return false;
154
-		}
155
-	}
156
-
157
-	/**
158
-	 * [delDataById 根据id删除数据]
159
-	 * @param     string                   $id     [主键]
160
-	 * @param     boolean                  $delSon [是否删除子孙数据]
161
-	 * @return    [type]                           [description]
162
-	 */
163
-	public function delDataById($id = '', $delSon = false)
164
-	{
165
-		if (!$id) {
166
-			$this->error = '删除失败';
167
-			return false;
168
-		}
169
-		$this->startTrans();
170
-		try {
171
-			$this->where($this->getPk(), $id)->delete();
172
-			if ($delSon && is_numeric($id)) {
173
-				// 删除子孙
174
-				$childIds = $this->getAllChild($id);
175
-				if($childIds){
176
-					$this->where($this->getPk(), 'in', $childIds)->delete();
177
-				}
178
-			}
179
-			$this->commit();
180
-			return true;
181
-		} catch(\Exception $e) {
182
-			$this->error = '删除失败';
183
-			$this->rollback();
184
-			return false;
185
-		}		
186
-	}
187
-
188
-	/**
189
-	 * [delDatas 批量删除数据]
190
-	 * @param     array                   $ids    [主键数组]
191
-	 * @param     boolean                 $delSon [是否删除子孙数据]
192
-	 * @return    [type]                          [description]
193
-	 */
194
-	public function delDatas($ids = [], $delSon = false)
195
-	{
196
-		if (empty($ids)) {
197
-			$this->error = '删除失败';
198
-			return false;
199
-		}
200
-		
201
-		// 查找所有子元素
202
-		if ($delSon) {
203
-			foreach ($ids as $k => $v) {
204
-				if (!is_numeric($v)) continue;
205
-				$childIds = $this->getAllChild($v);
206
-				$ids = array_merge($ids, $childIds);
207
-			}
208
-			$ids = array_unique($ids);
209
-		}
210
-
211
-		try {
212
-			$this->where($this->getPk(), 'in', $ids)->delete();
213
-			return true;
214
-		} catch (\Exception $e) {
215
-			$this->error = '操作失败';
216
-			return false;
217
-		}		
218
-
219
-	}
220
-
221
-	/**
222
-	 * [enableDatas 批量启用、禁用]
223
-	 * @param     string                   $ids    [主键数组]
224
-	 * @param     integer                  $status [状态1启用0禁用]
225
-	 * @param     [boolean]                $delSon [是否删除子孙数组]
226
-	 * @return    [type]                           [description]
227
-	 */
228
-	public function enableDatas($ids = [], $status = 1, $delSon = false)
229
-	{
230
-		if (empty($ids)) {
231
-			$this->error = '参数错误';
232
-			return false;
233
-		}
234
-
235
-		// 查找所有子元素
236
-		if ($delSon && $status === '0') {
237
-			foreach ($ids as $k => $v) {
238
-				$childIds = $this->getAllChild($v);
239
-				$ids = array_merge($ids, $childIds);
240
-			}
241
-			$ids = array_unique($ids);
242
-		}
243
-		try {
244
-			$this->where($this->getPk(),'in',$ids)->setField('status', $status);
245
-			return true;
246
-		} catch (\Exception $e) {
247
-			$this->error = '操作失败';
248
-			return false;
249
-		}
250
-	}
251
-
252
-	/**
253
-	 * 获取所有子孙
254
-	 */
255
-	public function getAllChild($id, &$data = [])
256
-	{
257
-		$map['pid'] = $id;
258
-		$childIds = $this->where($map)->column($this->getPk());
259
-		if (!empty($childIds)) {
260
-			foreach ($childIds as $v) {
261
-				$data[] = $v;
262
-				$this->getAllChild($v, $data);
263
-			}
264
-		}
265
-		return $data;
266
-	}
267
-
268
-	/**
269
-	 * 逻辑删除,将数据标记为删除状态
270
-	 * @author Michael_xu
271
-	 */	
272
-	public function signDelById($id)
273
-	{
274
-		if (!$id) {
275
-			$this->error = '删除失败';
276
-			return false;
277
-		}
278
-		$this->startTrans();
279
-		try {
280
-			$data['is_deleted'] = 1;
281
-			$data['delete_time'] = time();
282
-			$this->allowField(true)->save($data, [$this->getPk() => $id]);
283
-			$this->commit();
284
-			return true;
285
-		} catch(\Exception $e) {
286
-			$this->error = '删除失败';
287
-			$this->rollback();
288
-			return false;
289
-		}			
290
-	}
291
-
292
-
293
-	/**
294
-	 * 导出数据处理
295
-	 */
296
-	public function exportHandle($list, $field_list, $type = '')
297
-	{
298
-	
299
-		foreach ($list as &$val) {
300
-			foreach ($field_list as $field) {
301
-				switch ($field['form_type']) {
302
-					case 'user':
303
-						if (isset($val[$field['field'] . 'name'])) {
304
-							$val[$field['field']] = $val[$field['field'] . 'name'];
305
-						}
306
-//						else {
307
-//							$val[$field['field']] = implode(',', array_column($val[$field['field'] . '_info'], 'realname'));
308
-//						}
309
-						break;
310
-					case 'structure':
89
+    
90
+    /**
91
+     * [getDataById 根据主键获取详情]
92
+     * @param string $id [主键]
93
+     * @return    [array]
94
+     */
95
+    public function getDataById($id = '')
96
+    {
97
+        $data = $this->get($id);
98
+        if (!$data) {
99
+            $this->error = '暂无此数据';
100
+            return false;
101
+        }
102
+        return $data;
103
+    }
104
+    
105
+    /**
106
+     * [createData 新建]
107
+     * @param array $param [description]
108
+     * @return    [array]                         [description]
109
+     */
110
+    public function createData($param)
111
+    {
112
+        // 验证
113
+        $validate = validate($this->name);
114
+        if (!$validate->check($param)) {
115
+            $this->error = $validate->getError();
116
+            return false;
117
+        }
118
+        try {
119
+            $this->data($param)->allowField(true)->save();
120
+            return true;
121
+        } catch (\Exception $e) {
122
+            $this->error = '添加失败';
123
+            return false;
124
+        }
125
+    }
126
+    
127
+    /**
128
+     * [updateDataById 编辑]
129
+     * @param     [type]                   $param [description]
130
+     * @param     [type]                   $id    [description]
131
+     * @return    [type]                          [description]
132
+     */
133
+    public function updateDataById($param, $id)
134
+    {
135
+        $checkData = $this->get($id);
136
+        if (!$checkData) {
137
+            $this->error = '暂无此数据';
138
+            return false;
139
+        }
140
+        
141
+        // 验证
142
+        $validate = validate($this->name);
143
+        if (!$validate->scene('edit')->check($param)) {
144
+            $this->error = $validate->getError();
145
+            return false;
146
+        }
147
+        
148
+        try {
149
+            $this->allowField(true)->save($param, [$this->getPk() => $id]);
150
+            return true;
151
+        } catch (\Exception $e) {
152
+            $this->error = '编辑失败';
153
+            return false;
154
+        }
155
+    }
156
+    
157
+    /**
158
+     * [delDataById 根据id删除数据]
159
+     * @param string $id [主键]
160
+     * @param boolean $delSon [是否删除子孙数据]
161
+     * @return    [type]                           [description]
162
+     */
163
+    public function delDataById($id = '', $delSon = false)
164
+    {
165
+        if (!$id) {
166
+            $this->error = '删除失败';
167
+            return false;
168
+        }
169
+        $this->startTrans();
170
+        try {
171
+            $this->where($this->getPk(), $id)->delete();
172
+            if ($delSon && is_numeric($id)) {
173
+                // 删除子孙
174
+                $childIds = $this->getAllChild($id);
175
+                if ($childIds) {
176
+                    $this->where($this->getPk(), 'in', $childIds)->delete();
177
+                }
178
+            }
179
+            $this->commit();
180
+            return true;
181
+        } catch (\Exception $e) {
182
+            $this->error = '删除失败';
183
+            $this->rollback();
184
+            return false;
185
+        }
186
+    }
187
+    
188
+    /**
189
+     * [delDatas 批量删除数据]
190
+     * @param array $ids [主键数组]
191
+     * @param boolean $delSon [是否删除子孙数据]
192
+     * @return    [type]                          [description]
193
+     */
194
+    public function delDatas($ids = [], $delSon = false)
195
+    {
196
+        if (empty($ids)) {
197
+            $this->error = '删除失败';
198
+            return false;
199
+        }
200
+        
201
+        // 查找所有子元素
202
+        if ($delSon) {
203
+            foreach ($ids as $k => $v) {
204
+                if (!is_numeric($v)) continue;
205
+                $childIds = $this->getAllChild($v);
206
+                $ids = array_merge($ids, $childIds);
207
+            }
208
+            $ids = array_unique($ids);
209
+        }
210
+        
211
+        try {
212
+            $this->where($this->getPk(), 'in', $ids)->delete();
213
+            return true;
214
+        } catch (\Exception $e) {
215
+            $this->error = '操作失败';
216
+            return false;
217
+        }
218
+        
219
+    }
220
+    
221
+    /**
222
+     * [enableDatas 批量启用、禁用]
223
+     * @param string $ids [主键数组]
224
+     * @param integer $status [状态1启用0禁用]
225
+     * @param     [boolean]                $delSon [是否删除子孙数组]
226
+     * @return    [type]                           [description]
227
+     */
228
+    public function enableDatas($ids = [], $status = 1, $delSon = false)
229
+    {
230
+        if (empty($ids)) {
231
+            $this->error = '参数错误';
232
+            return false;
233
+        }
234
+        
235
+        // 查找所有子元素
236
+        if ($delSon && $status === '0') {
237
+            foreach ($ids as $k => $v) {
238
+                $childIds = $this->getAllChild($v);
239
+                $ids = array_merge($ids, $childIds);
240
+            }
241
+            $ids = array_unique($ids);
242
+        }
243
+        try {
244
+            $this->where($this->getPk(), 'in', $ids)->setField('status', $status);
245
+            return true;
246
+        } catch (\Exception $e) {
247
+            $this->error = '操作失败';
248
+            return false;
249
+        }
250
+    }
251
+    
252
+    /**
253
+     * 获取所有子孙
254
+     */
255
+    public function getAllChild($id, &$data = [])
256
+    {
257
+        $map['pid'] = $id;
258
+        $childIds = $this->where($map)->column($this->getPk());
259
+        if (!empty($childIds)) {
260
+            foreach ($childIds as $v) {
261
+                $data[] = $v;
262
+                $this->getAllChild($v, $data);
263
+            }
264
+        }
265
+        return $data;
266
+    }
267
+    
268
+    /**
269
+     * 逻辑删除,将数据标记为删除状态
270
+     * @author Michael_xu
271
+     */
272
+    public function signDelById($id)
273
+    {
274
+        if (!$id) {
275
+            $this->error = '删除失败';
276
+            return false;
277
+        }
278
+        $this->startTrans();
279
+        try {
280
+            $data['is_deleted'] = 1;
281
+            $data['delete_time'] = time();
282
+            $this->allowField(true)->save($data, [$this->getPk() => $id]);
283
+            $this->commit();
284
+            return true;
285
+        } catch (\Exception $e) {
286
+            $this->error = '删除失败';
287
+            $this->rollback();
288
+            return false;
289
+        }
290
+    }
291
+    
292
+    
293
+    /**
294
+     * 导出数据处理
295
+     */
296
+    public function exportHandle($list, $field_list, $type = '')
297
+    {
298
+        
299
+        foreach ($list as &$val) {
300
+            foreach ($field_list as $field) {
301
+                switch ($field['form_type']) {
302
+                    case 'user':
303
+                        if (isset($val[$field['field'] . 'name'])) {
304
+                            $val[$field['field']] = $val[$field['field'] . 'name'];
305
+                        }
306
+                        if ($field['field'] == 'order_user_id') {
307
+                            $val[$field['field']] = $val[$field['field'] . '_name'];
308
+                        }
309
+                        break;
310
+                    case 'structure':
311
 //						$temp = array_map(function ($val) { return $val->toarray(); }, $val[$field['field'] . '_name']);
311
 //						$temp = array_map(function ($val) { return $val->toarray(); }, $val[$field['field'] . '_name']);
312
 //						$val[$field['field']] = implode(',', array_column($temp, 'name'));
312
 //						$val[$field['field']] = implode(',', array_column($temp, 'name'));
313
 //						$val[$field['field']] = implode(',', array_column($temp, 'name'));
313
 //						$val[$field['field']] = implode(',', array_column($temp, 'name'));
314
-						break;
315
-					case 'datetime':
316
-						$val[$field['field']] = strtotime($val[$field['field']]) ? $val[$field['field']] : '';
317
-						break;
318
-					case 'customer':break;
319
-					case 'business':break;
320
-					case 'contacts':break;
321
-						$val[$field['field']] = $val[$field['field'] . '_info']['name'];
322
-						break;
323
-					default :
324
-						switch ($field['field']) {
325
-							// 商机销售阶段、商机状态组
326
-							case 'status_id':
327
-							    if($val['is_end']!=0){
328
-                                    $val[$field['field']]= $val['is_end'];
314
+                        break;
315
+                    case 'datetime':
316
+                        $val[$field['field']] = strtotime($val[$field['field']]) ? $val[$field['field']] : '';
317
+                        break;
318
+                    case 'customer':break;
319
+                    case 'business':break;
320
+                    case 'contacts':
321
+                        $val[$field['field']] = $val[$field['field'] . '_info']['name'];
322
+                        break;
323
+                    default :
324
+                        switch ($field['field']) {
325
+                            // 商机销售阶段、商机状态组
326
+                            case 'status_id':
327
+                                if ($val['is_end'] != 0) {
328
+                                    $val[$field['field']] = $val['is_end'];
329
                                 }
329
                                 }
330
-							    break;
331
-							case 'type_id':break;
330
+                                break;
331
+                            case 'type_id':
332
+                                break;
332
 //								$val[$field['field']] = $val[$field['field'] . '_info'];
333
 //								$val[$field['field']] = $val[$field['field'] . '_info'];
333
                             case 'check_status' :
334
                             case 'check_status' :
334
                                 $val[$field['field']] = $val[$field['field'] . '_info'];
335
                                 $val[$field['field']] = $val[$field['field'] . '_info'];
335
-								break;
336
-						}
337
-				}
338
-			}
339
-		}
340
-		return $list;
341
-	}
336
+                                break;
337
+                            case 'plan_id' :
338
+                                $val[$field['field']] = $val[$field['field'] . '_info'];
339
+                                break;
340
+                        }
341
+                }
342
+            }
343
+        }
344
+        return $list;
345
+    }
342
 }
346
 }

+ 226
- 268
application/admin/model/Excel.php Bestand weergeven

14
 use think\Cache;
14
 use think\Cache;
15
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
15
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
16
 use think\cache\driver\Redis;
16
 use think\cache\driver\Redis;
17
+
17
 class Excel extends Common
18
 class Excel extends Common
18
 {
19
 {
19
     /**
20
     /**
26
         'crm_customer',
27
         'crm_customer',
27
         'crm_contacts',
28
         'crm_contacts',
28
         'crm_product',
29
         'crm_product',
30
+        'crm_contract',
31
+        'crm_business',
29
         'admin_user',
32
         'admin_user',
30
         'task'
33
         'task'
31
     ];
34
     ];
72
     public function excelImportDownload($field_list, $types, $save_path = '')
75
     public function excelImportDownload($field_list, $types, $save_path = '')
73
     {
76
     {
74
         $fieldModel = new \app\admin\model\Field();
77
         $fieldModel = new \app\admin\model\Field();
75
-    
78
+        
76
         //实例化主文件
79
         //实例化主文件
77
         $objPHPExcel = new Spreadsheet();
80
         $objPHPExcel = new Spreadsheet();
78
         $objProps = $objPHPExcel->getProperties(); // 设置excel文档的属性
81
         $objProps = $objPHPExcel->getProperties(); // 设置excel文档的属性
86
         $objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet
89
         $objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet
87
         $objActSheet = $objPHPExcel->getActiveSheet();
90
         $objActSheet = $objPHPExcel->getActiveSheet();
88
         $objActSheet->setTitle('导入模板' . date('Y-m-d', time())); //设置sheet的标题
91
         $objActSheet->setTitle('导入模板' . date('Y-m-d', time())); //设置sheet的标题
89
-    
92
+        
90
         //存储Excel数据源到其他工作薄
93
         //存储Excel数据源到其他工作薄
91
         $objPHPExcel->createSheet();
94
         $objPHPExcel->createSheet();
92
         $subObject = $objPHPExcel->getSheet(1);
95
         $subObject = $objPHPExcel->getSheet(1);
111
         } else {
114
         } else {
112
             $k = 0;
115
             $k = 0;
113
         }
116
         }
117
+        $objActSheet->getColumnDimension('A1')->setWidth(70);
114
         foreach ($field_list as $field) {
118
         foreach ($field_list as $field) {
115
             if ($field['form_type'] == 'map_address' && $types == 'crm_customer') {
119
             if ($field['form_type'] == 'map_address' && $types == 'crm_customer') {
116
                 for ($a = 0; $a <= 3; $a++) {
120
                 for ($a = 0; $a <= 3; $a++) {
121
                 }
125
                 }
122
             } else {
126
             } else {
123
                 $objActSheet->getColumnDimension($this->stringFromColumnIndex($k))->setWidth(20); //设置单元格宽度
127
                 $objActSheet->getColumnDimension($this->stringFromColumnIndex($k))->setWidth(20); //设置单元格宽度
124
-                if ($field['form_type'] == 'select' || $field['form_type'] == 'checkbox' || $field['form_type'] == 'radio' || $field['form_type'] == 'category' || $field['form_type']=='user') {
128
+                if ($field['form_type'] == 'select' || $field['form_type'] == 'checkbox' || $field['form_type'] == 'radio' || $field['form_type'] == 'category' || $field['form_type'] == 'user') {
125
                     //产品类别
129
                     //产品类别
126
                     if ($field['form_type'] == 'category' && $field['types'] == 'crm_product') {
130
                     if ($field['form_type'] == 'category' && $field['types'] == 'crm_product') {
127
                         $setting = db('crm_product_category')->order('pid asc')->column('name');
131
                         $setting = db('crm_product_category')->order('pid asc')->column('name');
128
-                    } elseif($field['form_type']=='user' && $field['field'] == 'owner_user_id') {
132
+                    } elseif ($field['form_type'] == 'user' && ($field['field'] == 'owner_user_id' || $field['field'] == 'create_user_id' || $field['field'] == 'before_owner_user_id')) {
129
                         $setting = db('admin_user')->order('id asc')->column('realname');
133
                         $setting = db('admin_user')->order('id asc')->column('realname');
130
-                    }else{
134
+                    } else {
131
                         $setting = $field['setting'] ?: [];
135
                         $setting = $field['setting'] ?: [];
132
                     }
136
                     }
133
                     $select_value = implode(',', $setting);
137
                     $select_value = implode(',', $setting);
146
                             $endcell = $c;
150
                             $endcell = $c;
147
                         }
151
                         }
148
                         for ($j = 3; $j <= 70; $j++) {
152
                         for ($j = 3; $j <= 70; $j++) {
153
+                            $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getFont()->setName("宋体")->setSize(11)->getColor()->setARGB('#00000000');
149
                             $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
154
                             $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
150
                             //数据有效性   start
155
                             //数据有效性   start
151
                             $objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation();
156
                             $objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation();
164
                     } else {
169
                     } else {
165
                         if ($select_value) {
170
                         if ($select_value) {
166
                             for ($j = 3; $j <= 70; $j++) {
171
                             for ($j = 3; $j <= 70; $j++) {
172
+                                $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getFont()->setName("宋体")->setSize(11)->getColor()->setARGB('#00000000');
167
                                 $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
173
                                 $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
168
                                 //数据有效性   start
174
                                 //数据有效性   start
169
                                 $objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation();
175
                                 $objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation();
182
                         }
188
                         }
183
                     }
189
                     }
184
                 }
190
                 }
191
+                
185
                 $objActSheet->getStyle($this->stringFromColumnIndex($k))->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
192
                 $objActSheet->getStyle($this->stringFromColumnIndex($k))->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
186
                 //检查该字段若必填,加上"*"
193
                 //检查该字段若必填,加上"*"
187
                 $field['name'] = sign_required($field['is_null'], $field['name']);
194
                 $field['name'] = sign_required($field['is_null'], $field['name']);
188
                 $objActSheet->setCellValue($this->stringFromColumnIndex($k) . '2', $field['name']);
195
                 $objActSheet->setCellValue($this->stringFromColumnIndex($k) . '2', $field['name']);
196
+                if (strstr($field['name'], '*')) {
197
+                    $objActSheet->getStyle($this->stringFromColumnIndex($k) . '2')->getFont()->getColor()->setARGB('#FF0000');
198
+                }
189
                 $k++;
199
                 $k++;
190
             }
200
             }
191
         }
201
         }
193
         $mark_row = $this->stringFromColumnIndex($k);
203
         $mark_row = $this->stringFromColumnIndex($k);
194
         
204
         
195
         $objActSheet->mergeCells('A1:' . $max_row . '1');
205
         $objActSheet->mergeCells('A1:' . $max_row . '1');
196
-        $objActSheet->getStyle('A1:' . $mark_row . '1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); //水平居中
197
-        $objActSheet->getStyle('A1:' . $mark_row . '1')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); //垂直居中
198
-        $objActSheet->getRowDimension(1)->setRowHeight(28); //设置行高
199
-        $objActSheet->getStyle('A1')->getFont()->getColor()->setARGB('FFFF0000');
200
-        $objActSheet->getStyle('A1')->getAlignment()->setWrapText(true);
201
-        
202
         $objActSheet->getStyle('A1')->getFont()->getColor()->setARGB('FFFF0000');
206
         $objActSheet->getStyle('A1')->getFont()->getColor()->setARGB('FFFF0000');
203
-        $objActSheet->getStyle('A1')->getAlignment()->setWrapText(true);
207
+        $objActSheet->getStyle('A2:' . $max_row . '2')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); //
204
         //设置单元格格式范围的字体、字体大小、加粗
208
         //设置单元格格式范围的字体、字体大小、加粗
205
-        $objActSheet->getStyle('A1:' . $max_row . '1')->getFont()->setName("微软雅黑")->setSize(13)->getColor()->setARGB('#00000000');
209
+        $objActSheet->getStyle('A1:' . $max_row . '1')->getFont()->setName("宋体")->setSize(11)->getColor()->setARGB('#00000000');
206
         //给单元格填充背景色
210
         //给单元格填充背景色
207
-        $objActSheet->getStyle('A1:' . $max_row . '1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('#ff9900');
208
-        
211
+//        $objActSheet->getStyle('A1:' . $max_row . '1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('#ff9900');
212
+        $objActSheet->getStyle('A1:' . $max_row . '1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT); //水平居中
213
+        $objActSheet->getStyle('A1:' . $max_row . '1')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT); //垂直居中
214
+        $objActSheet->getRowDimension(1)->setRowHeight(100); //设置行高
215
+        $objActSheet->getRowDimension(2)->setRowHeight(30); //设置行高
216
+        $objActSheet->getStyle('A1')->getAlignment()->setWrapText(true);
209
         switch ($types) {
217
         switch ($types) {
210
             case 'crm_leads' :
218
             case 'crm_leads' :
211
                 $types_name = '线索信息';
219
                 $types_name = '线索信息';
243
                 $types_name = '任务信息';
251
                 $types_name = '任务信息';
244
                 $type_name = 'task';
252
                 $type_name = 'task';
245
                 break;
253
                 break;
254
+            case 'crm_pool' :
255
+                $types_name = '公海信息';
256
+                $type_name = 'pool';
257
+                break;
258
+                case 'crm_activity' :
259
+                $types_name = '跟进记录';
260
+                $type_name = 'activity';
261
+                break;
246
             default :
262
             default :
247
                 $types_name = '悟空软件';
263
                 $types_name = '悟空软件';
248
                 $type_name = 'WuKong';
264
                 $type_name = 'WuKong';
249
                 break;
265
                 break;
250
         }
266
         }
251
-        $content = $types_name . '(*代表必填项;时间格式:' . date('Y-m-d H:i:s') . ')';
267
+        
268
+        //内容设置
269
+        $content='';
270
+        if ($types == 'admin_user') {
271
+            $content ="注意事项:\n1、表头标“*”的红色字体为必填项\n2、手机号:目前只支持中国大陆的11位手机号码;且手机号不允许重复\n3、登录密码:密码由6-20位字母、数字组成\n4、部门:上下级部门间用“/”隔开,且从最上级部门开始,例如“上海分公司/市场部/市场一部”。如出现相同的部门,则默认导入组织架构中顺序靠前的部门";
272
+        } elseif($types == 'crm_activity'){
273
+            $content = "注意事项:\n1、表头标“*”的红色字体为必填项\n2、跟进时间:推荐格式为2020-2-1\n3、若相关数据有多条时用“/”区分例如:杭州科技有限公司/卡卡罗特软件科技有限公司\n4、所属客户中的客户需要存在系统中,且填写的所属客户名称与系统中的客户名称必须保持一致否则会导入失败\n5、创建人为系统员工,请填写系统员工“姓名”,若匹配不到系统员工,则会导致导入失败\n6、如果系统中存在多个名称重复的情况,会默认导入到最新的数据中";
274
+        }elseif($types == 'crm_pool'){
275
+            $content = "注意事项:\n1、表头标“*”的红色字体为必填项\n2、日期时间:推荐格式为2020-02-02 13:13:13\n3、日期:推荐格式为2020-02-02\n4、手机号:支持6-15位数字(包含国外手机号格式)\n5、邮箱:只支持邮箱格式\n6、多行文本:字数限制为800字\n7、负责人不必填,若填写负责人,则数据将进入客户模块,否则进入公海模块";
276
+        }else{
277
+            $content = "注意事项:\n1、表头标“*”的红色字体为必填项\n2、日期时间:推荐格式为2020-02-02 13:13:13\n3、日期:推荐格式为2020-02-02\n4、手机号:支持6-15位数字(包含国外手机号格式)\n5、邮箱:只支持邮箱格式\n6、多行文本:字数限制为800字";
278
+        }
252
         $objActSheet->setCellValue('A1', $content);
279
         $objActSheet->setCellValue('A1', $content);
280
+        //设置A1单元格内容为
281
+        $objActSheet->getStyle('A1')->getAlignment()->setWrapText(true);//合并单元格换行
253
         $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xls');
282
         $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xls');
254
         ob_end_clean();
283
         ob_end_clean();
255
         if ($save_path) {
284
         if ($save_path) {
432
                 foreach ($field_list as $rule) {
461
                 foreach ($field_list as $rule) {
433
                     if ($rule['form_type'] == 'customer_address') {
462
                     if ($rule['form_type'] == 'customer_address') {
434
                         $address_arr = explode(chr(10), $val['address']);
463
                         $address_arr = explode(chr(10), $val['address']);
435
-                        
436
                         $rows[] = $address_arr[0] ?: '';
464
                         $rows[] = $address_arr[0] ?: '';
437
                         $rows[] = $address_arr[1] ?: '';
465
                         $rows[] = $address_arr[1] ?: '';
438
                         $rows[] = $address_arr[2] ?: '';
466
                         $rows[] = $address_arr[2] ?: '';
439
                     } else {
467
                     } else {
468
+                        if (is_numeric($val[$rule['field']]) && strlen($val[$rule['field']]) > 15) {
469
+                            $val[$rule['field']] = "\t" . $val[$rule['field']] . "\t";
470
+                        }
440
                         $rows[] = $fieldModel->getValueByFormtype($val[$rule['field']], $rule['form_type']);
471
                         $rows[] = $fieldModel->getValueByFormtype($val[$rule['field']], $rule['form_type']);
441
                     }
472
                     }
442
                 }
473
                 }
488
             $queue->dequeue();
519
             $queue->dequeue();
489
             return false;
520
             return false;
490
         }
521
         }
491
-        $user_id = $param['owner_user_id'];
492
-        
522
+        if (!empty($param['pool_id'])) {
523
+            $user_id = $param['create_user_id'];
524
+        } else {
525
+            $user_id = $param['owner_user_id'];
526
+        }
493
         // 采用伪队列  允许三人同时导入数据
527
         // 采用伪队列  允许三人同时导入数据
494
         $queue = new Queue(self::IMPORT_QUEUE, 50000000);
528
         $queue = new Queue(self::IMPORT_QUEUE, 50000000);
495
         $import_queue_index = input('import_queue_index');
529
         $import_queue_index = input('import_queue_index');
556
             $save_path = UPLOAD_PATH . $save_name;
590
             $save_path = UPLOAD_PATH . $save_name;
557
             
591
             
558
             // 队列-判断是否需要排队
592
             // 队列-判断是否需要排队
559
-//            if (!$queue->canExec()) {
560
-//                $this->error = [
561
-//                    'temp_file' => $save_name,
562
-//                    'page' => -2,
563
-//                    'import_queue_index' => $import_queue_index,
564
-//                    'info' => $queue->error
565
-//                ];
566
-//                return true;
567
-//            }
568
-
593
+            if (!$queue->canExec()) {
594
+                $this->error = [
595
+                    'temp_file' => $save_name,
596
+                    'page' => -2,
597
+                    'import_queue_index' => $import_queue_index,
598
+                    'info' => $queue->error
599
+                ];
600
+                return true;
601
+            }
602
+            
569
             // 加载类库
603
             // 加载类库
570
             vendor("phpexcel.PHPExcel");
604
             vendor("phpexcel.PHPExcel");
571
             vendor("phpexcel.PHPExcel.Writer.Excel5");
605
             vendor("phpexcel.PHPExcel.Writer.Excel5");
649
                     break;
683
                     break;
650
             }
684
             }
651
             // 字段
685
             // 字段
652
-    
686
+            # 下次升级
653
             $fieldModel = new \app\admin\model\Field();
687
             $fieldModel = new \app\admin\model\Field();
654
             $fieldParam['types'] = $types;
688
             $fieldParam['types'] = $types;
655
             $fieldParam['action'] = 'excel';
689
             $fieldParam['action'] = 'excel';
656
-            $field_list = $fieldModel->field($fieldParam);
657
-            if(!empty($param['pool_id'])){
658
-                $pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select();
659
-                $merge_list = $fieldModel->field($fieldParam);
660
-                $field_list=array_intersect($merge_list,$pool_list);
690
+            if (!empty($param['pool_id'])) {
691
+                $list = [];
692
+                $field_list = db('crm_customer_pool_field_setting')->where(['pool_id' => $param['pool_id'], 'is_hidden' => 0,
693
+                    'field_name' => ['not in', ['deal_status', 'create_user_id']]])->field('field_name as field,form_type,name')->select();
694
+                foreach ($field_list as $k => &$v) {
695
+                    if ($v['field'] == 'address') {
696
+                        $v['field'] = 'customer_address';
697
+                        $v['form_type'] = 'map_address';
698
+                        $list[] = $v;
699
+                        unset($field_list[$k]);
700
+                    } elseif ($v['field'] == 'detail_address') {
701
+                        unset($field_list[$k]);
702
+                    }
703
+                }
704
+                $field_list = array_merge($field_list, $list);
705
+            } else {
706
+                $field_list = $fieldModel->field($fieldParam);
707
+            }
708
+            if ($types != 'admin_user' && empty($param['pool_id'])) {
709
+                $field = [1 => [
710
+                    'field' => 'owner_user_id',
711
+                    'types' => 'crm_leads',
712
+                    'name' => '负责人',
713
+                    'form_type' => 'user',
714
+                    'default_value' => '',
715
+                    'is_null' => 1,
716
+                    'input_tips' => '',
717
+                    'setting' => array(),
718
+                    'is_hidden' => 0,
719
+                    'writeStatus' => 1,
720
+                    'value' => '']
721
+                ];
722
+                $first_array = array_splice($field_list, 2, 0, $field);
661
             }
723
             }
662
             $field_list = array_map(function ($val) {
724
             $field_list = array_map(function ($val) {
663
                 if (method_exists($val, 'toArray')) {
725
                 if (method_exists($val, 'toArray')) {
667
                 }
729
                 }
668
             }, $field_list);
730
             }, $field_list);
669
             $field_key_name_list = array_column($field_list, 'name', 'field');
731
             $field_key_name_list = array_column($field_list, 'name', 'field');
670
-            # 下次升级
671
-//            $fieldModel = new \app\admin\model\Field();
672
-//            $fieldParam['types'] = $types;
673
-//            $fieldParam['action'] = 'excel';
674
-//            if(!empty($param['pool_id'])){
675
-//                $pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select();
676
-//                $merge_list = $fieldModel->field($fieldParam);
677
-//                $field_list=array_intersect($merge_list,$pool_list);
678
-//            }else{
679
-//                $field_list = $fieldModel->field($fieldParam);
680
-//                $field=[1=>[
681
-//                    'field'=>'owner_user_id',
682
-//                    'types'=>'crm_leads',
683
-//                    'name'=>'负责人',
684
-//                    'form_type'=>'user',
685
-//                    'default_value'=>'',
686
-//                    'is_unique' => 1,
687
-//                    'is_null' => 1,
688
-//                    'input_tips' =>'',
689
-//                    'setting' => Array(),
690
-//                    'is_hidden'=>0,
691
-//                    'writeStatus' => 1,
692
-//                    'value' => '']
693
-//                ];
694
-//                $first_array = array_splice($field_list, 0, 2);
695
-//            }
696
-//            $field_list = array_map(function ($val) {
697
-//                if (method_exists($val, 'toArray')) {
698
-//                    return $val->toArray();
699
-//                } else {
700
-//                    return $val;
701
-//                }
702
-//            }, $field_list);
703
-//            $field_key_name_list = array_column($field_list, 'name', 'field');
704
             // 加载导入数据文件
732
             // 加载导入数据文件
705
             $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
733
             $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
706
             $objRender->setReadDataOnly(true);
734
             $objRender->setReadDataOnly(true);
717
             // 检测导入文件是否使用最新模板
745
             // 检测导入文件是否使用最新模板
718
             $header = $sheet->rangeToArray("A2:{$max_col}2")[0];
746
             $header = $sheet->rangeToArray("A2:{$max_col}2")[0];
719
             $temp = 0;
747
             $temp = 0;
720
-           
721
             for ($i = 0; $i < count($field_list); $i++) {
748
             for ($i = 0; $i < count($field_list); $i++) {
722
                 if (
749
                 if (
723
                     $header[$i] == $field_list[$i]['name']
750
                     $header[$i] == $field_list[$i]['name']
724
                     || $header[$i] == '*' . $field_list[$i]['name']
751
                     || $header[$i] == '*' . $field_list[$i]['name']
725
                 ) {
752
                 ) {
753
+                    $res[] = $header[$i];
726
                     $temp++;
754
                     $temp++;
727
                     // 字段为地址时,占四列
755
                     // 字段为地址时,占四列
728
                 } elseif ($field_list[$i]['form_type'] == 'map_address') {
756
                 } elseif ($field_list[$i]['form_type'] == 'map_address') {
732
                         && $header[$i + 2] == $this->map_address[2]
760
                         && $header[$i + 2] == $this->map_address[2]
733
                         && $header[$i + 3] == $this->map_address[3]
761
                         && $header[$i + 3] == $this->map_address[3]
734
                     ) {
762
                     ) {
763
+                        $ress[] = $header[$i];
735
                         $temp++;
764
                         $temp++;
736
                     }
765
                     }
737
                 }
766
                 }
738
             }
767
             }
739
-            
740
-            
741
             // 每次导入条数
768
             // 每次导入条数
742
             $page_size = 100;
769
             $page_size = 100;
743
             
770
             
768
             // 数据重复时的处理方式 0跳过  1覆盖
795
             // 数据重复时的处理方式 0跳过  1覆盖
769
             $config = $param['config'] ?: 0;
796
             $config = $param['config'] ?: 0;
770
             // 默认数据
797
             // 默认数据
771
-            if(!empty($param['pool_id'])){
798
+            if (!empty($param['pool_id'])) {
772
                 //公海导入
799
                 //公海导入
773
                 $default_data = [
800
                 $default_data = [
774
                     'create_user_id' => $param['create_user_id'],
801
                     'create_user_id' => $param['create_user_id'],
775
                     'create_time' => time(),
802
                     'create_time' => time(),
776
                     'update_time' => time(),
803
                     'update_time' => time(),
777
                     'owner_user_id' => 0,
804
                     'owner_user_id' => 0,
778
-                    'before_owner_user_id'=>$param['create_user_id'],
779
-                    'into_pool_time'=>time(),
805
+                    'into_pool_time' => time(),
780
                     'pool_id' => $param['pool_id'],
806
                     'pool_id' => $param['pool_id'],
781
                 ];
807
                 ];
782
-            }else{
808
+            } else {
783
                 $default_data = [
809
                 $default_data = [
784
                     'create_user_id' => $param['create_user_id'],
810
                     'create_user_id' => $param['create_user_id'],
785
-                    'owner_user_id' => $param['owner_user_id'],
786
                     'create_time' => time(),
811
                     'create_time' => time(),
787
                     'update_time' => time(),
812
                     'update_time' => time(),
788
                 ];
813
                 ];
789
             }
814
             }
790
             if ($temp !== count($field_list)) {
815
             if ($temp !== count($field_list)) {
791
-//                $this->error = '请使用最新导入模板';
792
                 @unlink($save_path);
816
                 @unlink($save_path);
793
                 $queue->dequeue();
817
                 $queue->dequeue();
794
                 foreach ($dataList as $val) {
818
                 foreach ($dataList as $val) {
795
-                    $error_data_func($val, '请使用最新导入模板1');
819
+                    $error_data_func($val, '请使用最新导入模板');
796
                 }
820
                 }
797
                 $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
821
                 $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
798
                 $objWriter->save($error_path);
822
                 $objWriter->save($error_path);
871
                         }
895
                         }
872
                         $fk++;
896
                         $fk++;
873
                     }
897
                     }
874
-                    if (!empty($not_null_field)) {
898
+                    if (!empty($not_null_field) && empty($param['pool_id'])) {
875
                         $error_data_func($val, implode(', ', $not_null_field) . '不能为空');
899
                         $error_data_func($val, implode(', ', $not_null_field) . '不能为空');
876
                         continue;
900
                         continue;
877
                     }
901
                     }
887
                             $old_data_id_list = $dataModel->whereOr($unique_where)->column($db_id);
911
                             $old_data_id_list = $dataModel->whereOr($unique_where)->column($db_id);
888
                         }
912
                         }
889
                     }
913
                     }
914
+                    $userId = '';
890
                     #下次升级
915
                     #下次升级
891
-//                    if(empty($param['pool_id'])){
892
-//                        $user_id=db('admin_user')->where('realname',$val[2])->value('id');
893
-//                        $data['owner_user_id']=$user_id?:0;
894
-//                    }
916
+                    if ($param['pool_id']) {
917
+                        $userId = db('admin_user')->where('realname', $val[2])->value('id');
918
+                        $data['before_owner_user_id'] = 0;
919
+                    } else {
920
+                        $userId = db('admin_user')->where('realname', $val[2])->value('id');
921
+                        $data['owner_user_id'] = $userId ?: 0;
922
+                    }
895
                     $owner = db('crm_customer_pool')->where(['pool_id' => $param['pool_id']])->value('admin_user_ids');
923
                     $owner = db('crm_customer_pool')->where(['pool_id' => $param['pool_id']])->value('admin_user_ids');
896
-                    $auth=db('admin_access')->where('user_id',$param['create_user_id'])->column('group_id');
924
+                    $auth = db('admin_access')->where('user_id', $param['create_user_id'])->column('group_id');
897
                     // 数据重复时
925
                     // 数据重复时
898
-                    if (!empty($old_data_id_list) && empty($param['pool_id'])) {
926
+                    if ($old_data_id_list) {
899
                         if ($config) {
927
                         if ($config) {
900
                             $data = array_merge($data, $default_data);
928
                             $data = array_merge($data, $default_data);
901
                             $data['create_user_id'] = $param['create_user_id'];
929
                             $data['create_user_id'] = $param['create_user_id'];
904
                             try {
932
                             try {
905
                                 $up_success_count = 0;
933
                                 $up_success_count = 0;
906
                                 foreach ($old_data_id_list as $id) {
934
                                 foreach ($old_data_id_list as $id) {
907
-                                    if ($types == 'crm_customer') {
908
-                                        if (!in_array($param['create_user_id'],trim(stringToArray($owner),',')) && !in_array(1, $auth) && $param['create_user_id']!=1) {
909
-                                            $temp_error ='当前导入人员对该公海数据,无导入权限';
935
+                                    if ($types == 'crm_customer' && !empty($param['pool_id'])) {
936
+                                        if (!in_array($param['create_user_id'], trim(stringToArray($owner), ',')) && !in_array(1, $auth) && $param['create_user_id'] != 1) {
937
+                                            $temp_error = '当前导入人员对该公海数据,无导入权限';
910
                                             $error_data_func($val, $temp_error);
938
                                             $error_data_func($val, $temp_error);
911
                                             break;
939
                                             break;
940
+                                        } else {
941
+                                            if (!$dataModel->updateDataById($data, $id)) {
942
+                                                $temp_error = $dataModel->getError();
943
+                                                if ($temp_error == '无权操作') {
944
+                                                    $temp_error = '当前导入人员对该数据无写入权限';
945
+                                                }
946
+                                                $error_data_func($val, $temp_error);
947
+                                                $dataModel->rollback();
948
+                                                break;
949
+                                            }
912
                                         }
950
                                         }
913
-                                    }
914
-                                    if (!$dataModel->updateDataById($data, $id)) {
915
-                                        $temp_error = $dataModel->getError();
916
-                                        if ($temp_error == '无权操作') {
917
-                                            $temp_error = '当前导入人员对该数据无写入权限';
951
+                                    } else {
952
+                                        if (!$dataModel->updateDataById($data, $id)) {
953
+                                            $temp_error = $dataModel->getError();
954
+                                            if ($temp_error == '无权操作') {
955
+                                                $temp_error = '当前导入人员对该数据无写入权限';
956
+                                            }
957
+                                            $error_data_func($val, $temp_error);
958
+                                            $dataModel->rollback();
959
+                                            break;
918
                                         }
960
                                         }
919
-                                        $error_data_func($val, $temp_error);
920
-                                        $dataModel->rollback();
921
-                                        break;
922
                                     }
961
                                     }
923
                                     $up_success_count++;
962
                                     $up_success_count++;
924
                                 }
963
                                 }
944
                             $unique_field = array_unique($unique_field);
983
                             $unique_field = array_unique($unique_field);
945
                             $error_data_func($val, implode(', ', $unique_field) . ' 根据查重规则,该条数据重复');
984
                             $error_data_func($val, implode(', ', $unique_field) . ' 根据查重规则,该条数据重复');
946
                         }
985
                         }
947
-                    }elseif(!empty($old_data_id_list) && !empty($param['pool_id'])){
948
-                        $error_data_func($val,  ' 重复数据不在当前公海,无权覆盖');
949
                     } else {
986
                     } else {
950
-                        if ($types == 'crm_customer') {
951
-                        if (!in_array($param['create_user_id'],trim(stringToArray($owner),',')) && !in_array(1, $auth) && $param['create_user_id']!=1) {
952
-                            $temp_error = '当前导入人员对该公海数据,无导入权限';
953
-                            $error_data_func($val, $temp_error);
954
-                        }
955
-                        }else{
987
+                        if ($types == 'crm_customer' && !empty($param['pool_id'])) {
988
+                            if (!in_array($param['create_user_id'], trim(stringToArray($owner), ',')) && !in_array(1, $auth) && $param['create_user_id'] != 1) {
989
+                                $temp_error = '当前导入人员对该公海数据,无导入权限';
990
+                                $error_data_func($val, $temp_error);
991
+                            } else {
992
+                                $data = array_merge($data, $default_data);
993
+                                $data['excel'] = 1;
994
+                                if (!$resData = $dataModel->createData($data)) {
995
+                                    $error_data_func($val, $dataModel->getError());
996
+                                }
997
+                            }
998
+                        } else {
956
                             $data = array_merge($data, $default_data);
999
                             $data = array_merge($data, $default_data);
1000
+                            if ($types != 'admin_user') {
1001
+                                $data['excel'] = 1;
1002
+                            }
957
                             if (!$resData = $dataModel->createData($data)) {
1003
                             if (!$resData = $dataModel->createData($data)) {
958
                                 $error_data_func($val, $dataModel->getError());
1004
                                 $error_data_func($val, $dataModel->getError());
959
                             }
1005
                             }
1001
                     'error' => $error
1047
                     'error' => $error
1002
                 ]);
1048
                 ]);
1003
                 // 执行完成
1049
                 // 执行完成
1004
-                $redis= new Redis();
1050
+                $redis = new Redis();
1005
                 if ($done >= $total) {
1051
                 if ($done >= $total) {
1006
                     // 出队
1052
                     // 出队
1007
                     $queue->dequeue();
1053
                     $queue->dequeue();
1024
                         'user_id' => $user_id,
1070
                         'user_id' => $user_id,
1025
                         'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
1071
                         'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
1026
                     ]);
1072
                     ]);
1027
-                  
1073
+                    
1028
                     Cache::rm('item');
1074
                     Cache::rm('item');
1029
                     Cache::rm('excel_item');
1075
                     Cache::rm('excel_item');
1030
                     Cache::set('item', 1, config('import_cache_time'));
1076
                     Cache::set('item', 1, config('import_cache_time'));
2154
         $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
2200
         $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
2155
         $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
2201
         $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
2156
         $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
2202
         $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
2157
-        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2158
-        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2203
+        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2204
+        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2159
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFont()->getColor()->setARGB('FF000000');
2205
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFont()->getColor()->setARGB('FF000000');
2160
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
2206
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
2161
         
2207
         
2168
             $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getFont()->setBold(true);//设置是否加粗
2214
             $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getFont()->setBold(true);//设置是否加粗
2169
             $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//垂直居中
2215
             $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//垂直居中
2170
             $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2216
             $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2171
-            $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2217
+            $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2172
             if ($v[3] > 0)//大于0表示需要设置宽度
2218
             if ($v[3] > 0)//大于0表示需要设置宽度
2173
             {
2219
             {
2174
                 $objPHPExcel->getActiveSheet()->getColumnDimension($cellKey[$k])->setWidth($v[3]);//设置列宽度
2220
                 $objPHPExcel->getActiveSheet()->getColumnDimension($cellKey[$k])->setWidth($v[3]);//设置列宽度
2176
         }
2222
         }
2177
         $objActSheet->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getFont()->getColor()->setARGB('FF000000');
2223
         $objActSheet->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getFont()->getColor()->setARGB('FF000000');
2178
         $objActSheet->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
2224
         $objActSheet->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
2179
-        $callCount = count($callback) + 2;
2180
-        $style_array = array(
2181
-            'borders' => array(
2182
-                'allborders' => array(
2183
-                    'style' => \PHPExcel_Style_Border::BORDER_THIN
2184
-                )
2185
-            ));
2186
-        $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . $callCount)->applyFromArray($style_array);
2225
+//边框
2226
+        //        $callCount = count($callback) + 2;
2227
+//        $style_array = array(
2228
+//            'borders' => array(
2229
+//                'allborders' => array(
2230
+//                    'style' => \PHPExcel_Style_Border::BORDER_THIN
2231
+//                )
2232
+//            ));
2233
+//        $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . $callCount)->applyFromArray($style_array);
2187
         foreach ($callback as $k => $item) {
2234
         foreach ($callback as $k => $item) {
2188
             foreach ($field_list as $key => $rule) {
2235
             foreach ($field_list as $key => $rule) {
2189
-                $objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2236
+                $objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2190
                 $objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
2237
                 $objPHPExcel->getActiveSheet()->getStyle($cellKey[$key] . ($k + 1 + $topNumber) . ':' . $cellKey[count($field_list) - 1] . ($k + 1 + $topNumber))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
2191
                 $objPHPExcel->getActiveSheet()->setCellValue($cellKey[$key] . ($k + 1 + $topNumber), $item[$rule['field']]);
2238
                 $objPHPExcel->getActiveSheet()->setCellValue($cellKey[$key] . ($k + 1 + $topNumber), $item[$rule['field']]);
2192
             }
2239
             }
2249
             $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
2296
             $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
2250
             $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//垂直居中
2297
             $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//垂直居中
2251
             
2298
             
2252
-            $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2299
+            $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
2253
             $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2300
             $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2254
             
2301
             
2255
             if ($v[3] > 0)//大于0表示需要设置宽度
2302
             if ($v[3] > 0)//大于0表示需要设置宽度
2394
         $excelData = Cache::pull('excel');
2441
         $excelData = Cache::pull('excel');
2395
         $base = $excelData['base'];
2442
         $base = $excelData['base'];
2396
         if ($param == 0) {
2443
         if ($param == 0) {
2397
-            if($base=='batchTaskImportData'){
2444
+            if ($base == 'batchTaskImportData') {
2398
                 $this->batchTaskImportData('', $excelData);
2445
                 $this->batchTaskImportData('', $excelData);
2399
-            }else{
2446
+            } elseif ($base == 'ActivityImport') {
2447
+                $this->ActivityImport('', $excelData);
2448
+            } else {
2400
                 $this->batchImportData('', $excelData);
2449
                 $this->batchImportData('', $excelData);
2401
             }
2450
             }
2402
             $data = 0;
2451
             $data = 0;
2403
         } elseif ($param == 1) {
2452
         } elseif ($param == 1) {
2404
             $data = '';
2453
             $data = '';
2405
         }
2454
         }
2406
-    
2455
+        
2407
         return $data;
2456
         return $data;
2408
     }
2457
     }
2409
     
2458
     
2454
         } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
2503
         } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
2455
             $data['firstPage'] = false;
2504
             $data['firstPage'] = false;
2456
             $data['lastPage'] = false;
2505
             $data['lastPage'] = false;
2457
-        } else if ($param['page'] == 1) {
2506
+        } else if ($param['page'] == 1  && (int)($param['page'] * $param['limit']) < $dataCount) {
2458
             $data['firstPage'] = true;
2507
             $data['firstPage'] = true;
2459
             $data['lastPage'] = false;
2508
             $data['lastPage'] = false;
2460
         }
2509
         }
2471
      * @version     1.0 版本号
2520
      * @version     1.0 版本号
2472
      * @since       2021/4/9 0009 16:31
2521
      * @since       2021/4/9 0009 16:31
2473
      */
2522
      */
2474
-    public function ActivityImport($file,$field_list,$param,$controller = null)
2523
+    public function ActivityImport($file, $field_list, $param, $controller = null)
2475
     {
2524
     {
2476
         // 导入模块
2525
         // 导入模块
2477
         $types = $param['types'];
2526
         $types = $param['types'];
2480
             $queue->dequeue();
2529
             $queue->dequeue();
2481
             return false;
2530
             return false;
2482
         }
2531
         }
2483
-       
2532
+        $user_id = $param['user_id'];
2484
         // 采用伪队列  允许三人同时导入数据
2533
         // 采用伪队列  允许三人同时导入数据
2485
         $queue = new Queue(self::IMPORT_QUEUE, 30000);
2534
         $queue = new Queue(self::IMPORT_QUEUE, 30000);
2486
         $import_queue_index = input('import_queue_index');
2535
         $import_queue_index = input('import_queue_index');
2487
-     
2536
+        
2488
         // 队列任务ID
2537
         // 队列任务ID
2489
         if (!$import_queue_index) {
2538
         if (!$import_queue_index) {
2490
             if (!$import_queue_index = $queue->makeTaskId()) {
2539
             if (!$import_queue_index = $queue->makeTaskId()) {
2501
         }
2550
         }
2502
         // 取消导入
2551
         // 取消导入
2503
         if ($param['page'] == -1) {
2552
         if ($param['page'] == -1) {
2504
-           
2553
+            
2505
             @unlink(UPLOAD_PATH . $param['temp_file']);
2554
             @unlink(UPLOAD_PATH . $param['temp_file']);
2506
             $this->error = [
2555
             $this->error = [
2507
                 'msg' => '导入已取消',
2556
                 'msg' => '导入已取消',
2508
                 'page' => -1
2557
                 'page' => -1
2509
             ];
2558
             ];
2510
-           
2559
+            
2511
             if ($param['error']) {
2560
             if ($param['error']) {
2512
                 $this->error['error_file_path'] = 'temp/' . $param['error_file'];
2561
                 $this->error['error_file_path'] = 'temp/' . $param['error_file'];
2513
             } else {
2562
             } else {
2514
-               
2563
+                
2515
                 @unlink(TEMP_DIR . $param['error_file']);
2564
                 @unlink(TEMP_DIR . $param['error_file']);
2516
             }
2565
             }
2517
             $temp = $queue->cache('last_import_cache');
2566
             $temp = $queue->cache('last_import_cache');
2518
-           
2567
+            
2519
             (new ImportRecord())->createData([
2568
             (new ImportRecord())->createData([
2520
                 'type' => $types,
2569
                 'type' => $types,
2521
                 'total' => $temp['total'],
2570
                 'total' => $temp['total'],
2522
                 'done' => $temp['done'],
2571
                 'done' => $temp['done'],
2523
                 'cover' => $temp['cover'],
2572
                 'cover' => $temp['cover'],
2524
                 'error' => $temp['error'],
2573
                 'error' => $temp['error'],
2574
+                'user_id' => $user_id,
2525
                 'error_data_file_path' => $temp['error'] ? 'temp/' . $error_data_file_name : ''
2575
                 'error_data_file_path' => $temp['error'] ? 'temp/' . $error_data_file_name : ''
2526
             ]);
2576
             ]);
2527
             $queue->dequeue();
2577
             $queue->dequeue();
2559
             vendor("phpexcel.PHPExcel.Writer.Excel5");
2609
             vendor("phpexcel.PHPExcel.Writer.Excel5");
2560
             vendor("phpexcel.PHPExcel.Writer.Excel2007");
2610
             vendor("phpexcel.PHPExcel.Writer.Excel2007");
2561
             vendor("phpexcel.PHPExcel.IOFactory");
2611
             vendor("phpexcel.PHPExcel.IOFactory");
2562
-           
2612
+            
2563
             // 错误数据临时文件路径  错误数据开始行数
2613
             // 错误数据临时文件路径  错误数据开始行数
2564
             if ($param['error_file']) {
2614
             if ($param['error_file']) {
2565
                 $error_path = TEMP_DIR . $param['error_file'];
2615
                 $error_path = TEMP_DIR . $param['error_file'];
2578
             // 加载错误数据文件
2628
             // 加载错误数据文件
2579
             
2629
             
2580
             $err_PHPExcel = \PHPExcel_IOFactory::load($error_path);
2630
             $err_PHPExcel = \PHPExcel_IOFactory::load($error_path);
2581
-           
2631
+            
2582
             $error_sheet = $err_PHPExcel->setActiveSheetIndex(0);
2632
             $error_sheet = $err_PHPExcel->setActiveSheetIndex(0);
2583
             /**
2633
             /**
2584
              * 添加错误数据到临时文件
2634
              * 添加错误数据到临时文件
2605
             $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
2655
             $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
2606
             $objRender->setReadDataOnly(true);
2656
             $objRender->setReadDataOnly(true);
2607
             $ExcelObj = $objRender->load($save_path);
2657
             $ExcelObj = $objRender->load($save_path);
2608
-          
2658
+            
2609
             // 指定工作表
2659
             // 指定工作表
2610
             $sheet = $ExcelObj->getSheet(0);
2660
             $sheet = $ExcelObj->getSheet(0);
2611
             // 总行数
2661
             // 总行数
2642
             }
2692
             }
2643
             // 读取数据
2693
             // 读取数据
2644
             $dataList = $sheet->rangeToArray("A{$start_row}:{$max_col}{$end_row}");
2694
             $dataList = $sheet->rangeToArray("A{$start_row}:{$max_col}{$end_row}");
2645
-            // 默认数据
2646
-            $default_data = [
2647
-            ];
2648
-            switch ($types){
2695
+            switch ($types) {
2649
                 case 'crm_business':
2696
                 case 'crm_business':
2650
                     $dataModel = new \app\crm\model\Business();
2697
                     $dataModel = new \app\crm\model\Business();
2651
                     $db = db('crm_business');
2698
                     $db = db('crm_business');
2652
                     $db_id = 'business_id';
2699
                     $db_id = 'business_id';
2653
-                    $activity_type=5;
2700
+                    $activity_type = 5;
2701
+                    $activity_name='所属商机';
2654
                     break;
2702
                     break;
2655
                 case 'crm_contract':
2703
                 case 'crm_contract':
2656
                     $db = db('crm_contract');
2704
                     $db = db('crm_contract');
2657
                     $db_id = 'contract_id';
2705
                     $db_id = 'contract_id';
2658
-                    $activity_type=6;
2706
+                    $activity_type = 6;
2707
+                    $activity_name='所属合同';
2659
                     break;
2708
                     break;
2660
                 case 'crm_leads' :
2709
                 case 'crm_leads' :
2661
                     $dataModel = new \app\crm\model\Leads();
2710
                     $dataModel = new \app\crm\model\Leads();
2662
                     $db = db('crm_leads');
2711
                     $db = db('crm_leads');
2663
                     $db_id = 'leads_id';
2712
                     $db_id = 'leads_id';
2664
-                    $activity_type=1;
2713
+                    $activity_type = 1;
2714
+                    $activity_name='所属线索';
2665
                     break;
2715
                     break;
2666
                 case 'crm_customer' :
2716
                 case 'crm_customer' :
2667
                     $dataModel = new \app\crm\model\Customer();
2717
                     $dataModel = new \app\crm\model\Customer();
2668
                     $db = db('crm_customer');
2718
                     $db = db('crm_customer');
2669
                     $db_id = 'customer_id';
2719
                     $db_id = 'customer_id';
2670
                     $fieldParam['form_type'] = ['not in', ['file', 'form', 'user', 'structure']];
2720
                     $fieldParam['form_type'] = ['not in', ['file', 'form', 'user', 'structure']];
2671
-                    $activity_type=2;
2721
+                    $activity_type = 2;
2722
+                    $activity_name='所属客户';
2672
                     break;
2723
                     break;
2673
                 case 'crm_contacts' :
2724
                 case 'crm_contacts' :
2674
                     $dataModel = new \app\crm\model\Contacts();
2725
                     $dataModel = new \app\crm\model\Contacts();
2675
                     $db = db('crm_contacts');
2726
                     $db = db('crm_contacts');
2676
                     $db_id = 'contacts_id';
2727
                     $db_id = 'contacts_id';
2677
-                    $activity_type=3;
2728
+                    $activity_type = 3;
2729
+                    $activity_name='所属联系人';
2678
                     break;
2730
                     break;
2679
             }
2731
             }
2680
-         
2732
+            
2681
             // 开始导入数据
2733
             // 开始导入数据
2682
             foreach ($dataList as $val) {
2734
             foreach ($dataList as $val) {
2683
                 $fk = 0;
2735
                 $fk = 0;
2704
                     continue;
2756
                     continue;
2705
                 }
2757
                 }
2706
                 $activityLogic = new \app\crm\logic\ActivityLogic();
2758
                 $activityLogic = new \app\crm\logic\ActivityLogic();
2707
-                $userData=db('admin_user')->where(['realname'=>$val[1],'status'=>['neq',0]])->value('id');
2708
-                $customerData=$db->where('name',$val[2])->value($db_id);
2709
-                $classData = db('crm_activity')->where(['content' => $val[0], 'activity_type' => $param['activity_type'],'activity_type_id'=>$customerData])->order('activity_id', 'asc')->select();
2759
+                $userData = db('admin_user')->where(['realname' => $val[1], 'status' => ['neq', 0]])->value('id');
2760
+                $customerData = $db->where('name', $val[2])->value($db_id);
2761
+                $classData = db('crm_activity')->where(['content' => $val[0], 'activity_type' => $param['activity_type'], 'activity_type_id' => $customerData])->order('activity_id', 'asc')->select();
2762
+                
2710
                 if (empty($customerData)) {
2763
                 if (empty($customerData)) {
2711
-                    $error_data_func($val, '所属客户'.$val[2].'不存在');
2764
+                    $error_data_func($val, $activity_name . $val[2] . '不存在');
2712
                     continue;
2765
                     continue;
2713
                 }
2766
                 }
2714
                 if (empty($userData)) {
2767
                 if (empty($userData)) {
2715
-                    $error_data_func($val, '管理员'.$val[1].'不存在');
2768
+                    $error_data_func($val, '管理员' . $val[1] . '不存在');
2716
                     continue;
2769
                     continue;
2717
                 }
2770
                 }
2718
-                if($types=='crm_customer' && (!empty($val[5]) || !empty($val[6]))){
2719
-                    $contactsData=db('crm_contacts')->where('name',$val[5])->value($db_id);
2720
-                    $businessData=$db->where('crm_business',$val[6])->value($db_id);
2721
-                    if (empty($contactsData)&&eempty($businessData)) {
2722
-                        $error_data_func($val, '联系人'.$val[5].'不存在或商机'.$val[6].'不存在');
2723
-                        continue;
2771
+                if ($types == 'crm_customer' && (!empty($val[5]) || !empty($val[6]))) {
2772
+                    if(strstr($val[5], '/')||strstr($val[6], '/')){
2773
+                        $val[5]= explode ( '/' , $val[5]);
2774
+                        $val[6]= explode ( '/' , $val[6]);
2724
                     }
2775
                     }
2776
+                    $contactsData = db('crm_contacts')->where('name', ['in',arrayToString($val[5])])->column('contacts_id');
2777
+                    $businessData = db('crm_business')->where('name', ['in',arrayToString($val[6])] )->column('business_id');
2778
+                    $data['business_ids']=arrayToString($businessData);
2779
+                    $data['contacts_ids']=arrayToString($contactsData);
2725
                 }
2780
                 }
2726
-                if ($classData[0]['activity_id'] != '') {
2727
-                    
2728
-                    $data['activity_id'] = $classData[0]['activity_id'];
2729
-                    $data = array_merge($data, $default_data);
2730
-                    $data['create_user_id'] = $userData;
2731
-                    $data['activity_type_id'] = $customerData;
2732
-                    $data['activity_type'] = $activity_type;
2733
-                    if (!$resData = $activityLogic->update($data)) {
2734
-                        $error_data_func($val, $dataModel->getError());
2735
-                    }
2736
-                }else{
2737
-                    $data = array_merge($data, $default_data);
2738
-                    $data['user_id']=$userData;
2781
+//                if ($classData && $classData[0]['activity_id'] != '') {
2782
+//                    $data['activity_id'] = $classData[0]['activity_id'];
2783
+//                    $data['activity_type_id'] = $customerData;
2784
+//                    $data['activity_type'] = $activity_type;
2785
+//                    $data['create_user_id'] = $user_id;
2786
+//                    if (!$resData = $activityLogic->update($data)) {
2787
+//                        $error_data_func($val, $dataModel->getError());
2788
+//                    }
2789
+//                } else {                }
2790
+                    $data['user_id'] = $userData;
2739
                     $data['activity_type_id'] = $customerData;
2791
                     $data['activity_type_id'] = $customerData;
2740
                     $data['activity_type'] = $activity_type;
2792
                     $data['activity_type'] = $activity_type;
2793
+                    $data['excel'] = 1;
2794
+                    $data['create_user_id'] = $user_id;
2741
                     unset($data['create_user_id']);
2795
                     unset($data['create_user_id']);
2742
                     if (!$resData = $activityLogic->save($data)) {
2796
                     if (!$resData = $activityLogic->save($data)) {
2743
                         $error_data_func($val, $dataModel->getError());
2797
                         $error_data_func($val, $dataModel->getError());
2744
                     }
2798
                     }
2745
-                }
2799
+
2746
             }
2800
             }
2747
             // 完成数(已导入数)
2801
             // 完成数(已导入数)
2748
             $done = ($page - 1) * $page_size + count($dataList);
2802
             $done = ($page - 1) * $page_size + count($dataList);
2755
             // 错误数据文件保存
2809
             // 错误数据文件保存
2756
             $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
2810
             $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
2757
             $objWriter->save($error_path);
2811
             $objWriter->save($error_path);
2758
-           
2812
+            
2759
             $this->error = [
2813
             $this->error = [
2760
                 // 数据导入文件临时路径
2814
                 // 数据导入文件临时路径
2761
                 'temp_file' => $save_name,
2815
                 'temp_file' => $save_name,
2774
                 // 导入任务ID
2828
                 // 导入任务ID
2775
                 'import_queue_index' => $import_queue_index
2829
                 'import_queue_index' => $import_queue_index
2776
             ];
2830
             ];
2777
-           
2831
+            
2778
             $queue->cache('last_import_cache', [
2832
             $queue->cache('last_import_cache', [
2779
                 'total' => $total,
2833
                 'total' => $total,
2780
                 'done' => $done,
2834
                 'done' => $done,
2800
                     'done' => $done,
2854
                     'done' => $done,
2801
                     'cover' => $cover,
2855
                     'cover' => $cover,
2802
                     'error' => $error,
2856
                     'error' => $error,
2857
+                    'user_id' => $user_id,
2803
                     'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
2858
                     'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
2804
                 ]);
2859
                 ]);
2805
                 Cache::set('item', 1, config('import_cache_time'));
2860
                 Cache::set('item', 1, config('import_cache_time'));
2826
             return false;
2881
             return false;
2827
         }
2882
         }
2828
     }
2883
     }
2829
-    
2830
-    /**
2831
-     * 自定义excel导入样式
2832
-     * @param $field_list
2833
-     * @param $param
2834
-     * @param $types
2835
-     *
2836
-     * @author      alvin guogaobo
2837
-     * @version     1.0 版本号
2838
-     * @since       2021/4/10 0010 09:27
2839
-     */
2840
-    public function importDown($field_list,$types,$save_path='')
2841
-    {
2842
-        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); //创建一个新的工作表
2843
-        //实例化主文件
2844
-        $objPHPExcel = new Spreadsheet();
2845
-        $worksheet = $spreadsheet->getActiveSheet();
2846
-        if ($save_path) {
2847
-            $worksheet->setCellValue('A2', '错误原因(导入时需删除本列)');
2848
-            $worksheet->getColumnDimension('A')->setWidth(40); //设置单元格宽度
2849
-            $k = 1;
2850
-        } else {
2851
-            $k = 0;
2852
-        }
2853
-        $worksheet->getColumnDimension('A1')->setWidth(70); //设置A列宽度为30
2854
-        foreach ($field_list as $v) {
2855
-            for ($j = 3; $j <= 70; $j++) {
2856
-                $worksheet->getStyle($this->stringFromColumnIndex($k).$j)->getNumberFormat()
2857
-                    ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
2858
-               }
2859
-            $worksheet->getColumnDimension($this->stringFromColumnIndex($k))->setWidth(40); //自动设置B列宽度
2860
-            //检查该字段若必填,加上"*"
2861
-            $v['name'] = sign_required($v['is_null'], $v['name']);
2862
-            $worksheet->setCellValue($this->stringFromColumnIndex($k) . '2', $v['name']);
2863
-            $k++;
2864
-        }
2865
-        //加上"*"颜色变红
2866
-        $worksheet -> getStyle('A2:C2') -> getFont()
2867
-            -> getColor() -> setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);
2868
-        $max_row = $this->stringFromColumnIndex($k-1);//列
2869
-        $mark_row = $this->stringFromColumnIndex($k);
2870
-        //样式设置 - 字体
2871
-        $worksheet->getStyle('A1:' . $max_row . '1')->getFont()
2872
-            ->setBold(true)->setName('宋体')
2873
-            ->setSize(11); //设置单元格A7:G10的字体样式
2874
-        $worksheet->getStyle('A2:' . $max_row . '2')->getFont()
2875
-           ->setBold(true)->setName('宋体')
2876
-            ->setSize(11); //设置单元格A7:G10的字体样式; //设置单元格A1的字体颜色
2877
-        //样式设置 - 行高
2878
-        $worksheet->getRowDimension('1')->setRowHeight(200); //设置第10行高度为100
2879
-        //样式设置 - 水平、垂直居中
2880
-        $styleArray = [
2881
-            'alignment' => [
2882
-                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT,
2883
-                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT
2884
-            ],
2885
-        ];
2886
-        $worksheet->getStyle('A1:'.$max_row.'1')->applyFromArray($styleArray);
2887
-        //样式设置 - 边框
2888
-        $styleArray = [
2889
-            'borders' => [
2890
-                'outline' => [
2891
-                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
2892
-                ],
2893
-                'inside' => [
2894
-                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
2895
-                ]
2896
-            ],
2897
-        ];
2898
-        $worksheet->getStyle('A1:'.$max_row.'1')->applyFromArray($styleArray);
2899
-        //样式设置 - 合并和拆分
2900
-        $worksheet->mergeCells('A1:'.$max_row.'1'); //合并单元格
2901
-        //内容设置
2902
-        $worksheet->setCellValue('A1', "
2903
-        注意事项:\n
2904
-        1、表头标“*”的红色字体为必填项\n
2905
-        2、跟进时间:推荐格式为2020-2-1\n
2906
-        3、若相关数据有多条时用“/”区分例如:杭州科技有限公司/卡卡罗特软件科技有限公司\n
2907
-        4、所属客户中的客户需要存在系统中,且填写的所属客户名称与系统中的客户名称必须保持一致否则会导入失败\n
2908
-        5、创建人为系统员工,请填写系统员工“姓名”,若匹配不到系统员工,则会导致导入失败\n
2909
-        6、如果系统中存在多个名称重复的情况,会默认导入到最新的数据中"
2910
-        ); //设置A1单元格内容为
2911
-        $worksheet->getStyle('A1')->getAlignment()->setWrapText(true);//合并单元格换行
2912
-
2913
-        //下载工作表
2914
-        ob_end_clean();
2915
-        if ($save_path) {
2916
-                $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
2917
-                $writer -> save($save_path);
2918
-        } else {
2919
-            header('Content-Type: application/vnd.ms-excel');
2920
-            header('Content-Disposition: attachment;filename="1.xls"');
2921
-            header('Cache-Control: max-age=0');
2922
-            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
2923
-            $writer->save('php://output');
2924
-        }
2925
-    }
2926
 }
2884
 }

+ 621
- 208
application/admin/model/Field.php
Diff onderdrukt omdat het te groot bestand
Bestand weergeven


+ 5
- 7
application/admin/model/Group.php Bestand weergeven

100
 	//编辑角色
100
 	//编辑角色
101
 	public function updateDataById($param,$group_id)
101
 	public function updateDataById($param,$group_id)
102
 	{
102
 	{
103
+	    $userId = $param['user_id'];
103
 		$dataInfo = $this->get($group_id);
104
 		$dataInfo = $this->get($group_id);
104
 		if(!$dataInfo){
105
 		if(!$dataInfo){
105
 			$this->error = '该角色不存在或已删除';
106
 			$this->error = '该角色不存在或已删除';
106
 			return false;
107
 			return false;
107
 		}
108
 		}
108
 		unset($param['types']);
109
 		unset($param['types']);
110
+		unset($param['user_id']);
109
 
111
 
110
 		# 处理编辑时,前端可能不传父id的问题(admin_rule表level为1的主键)
112
 		# 处理编辑时,前端可能不传父id的问题(admin_rule表level为1的主键)
111
         if (!empty($param['rules'])) {
113
         if (!empty($param['rules'])) {
125
         }
127
         }
126
 		$flag = $this->where('id = '.$group_id)->update($param);
128
 		$flag = $this->where('id = '.$group_id)->update($param);
127
 		if ($flag) {
129
 		if ($flag) {
128
-		    $user=new ApiCommon();
129
-		    $user_id=$user->userInfo;
130
-            SystemActionLog($user_id['id'], 'admin_group','role', $group_id,  'update', $dataInfo['title'], '', '','编辑了:'.$dataInfo['title']);
130
+            SystemActionLog($userId, 'admin_group','role', $group_id,  'update', $dataInfo['title'], '', '','编辑了:'.$dataInfo['title']);
131
             return true;
131
             return true;
132
 		} else {
132
 		} else {
133
 			$this->error = '操作失败';
133
 			$this->error = '操作失败';
136
 	}
136
 	}
137
 	
137
 	
138
 	//删除角色
138
 	//删除角色
139
-	public function delGroupById($group_id = '')
139
+	public function delGroupById($group_id = '',$userId)
140
 	{
140
 	{
141
 		$dataInfo = $this->get($group_id);
141
 		$dataInfo = $this->get($group_id);
142
 		if(!$dataInfo){
142
 		if(!$dataInfo){
150
 		$flag = $this->where('id = '.$group_id)->delete();
150
 		$flag = $this->where('id = '.$group_id)->delete();
151
 		if ($flag) {
151
 		if ($flag) {
152
 		    # 系统操作记录
152
 		    # 系统操作记录
153
-            $user=new ApiCommon();
154
-            $user_id=$user->userInfo;
155
-            SystemActionLog($user_id['id'], 'admin_group','role', $group_id,  'update', $dataInfo['title'], '', '','删除了角色:'.$dataInfo['title']);
153
+            SystemActionLog($userId, 'admin_group','role', $group_id,  'update', $dataInfo['title'], '', '','删除了角色:'.$dataInfo['title']);
156
             return true;
154
             return true;
157
 		} else {
155
 		} else {
158
 			$this->error = '删除失败';
156
 			$this->error = '删除失败';

+ 7
- 1
application/admin/model/Message.php Bestand weergeven

165
      * 移除团队成员
165
      * 移除团队成员
166
      */
166
      */
167
     const TEAM_END = 31;
167
     const TEAM_END = 31;
168
-
168
+    /**
169
+     * 移除队成员
170
+     */
171
+    const TEAM_LEADS = 32;
169
     /**
172
     /**
170
      * 消息类型
173
      * 消息类型
171
      *
174
      *
273
         31 => [
276
         31 => [
274
             'template' => '将{from_user} 移除了您 {title} 的团队。',
277
             'template' => '将{from_user} 移除了您 {title} 的团队。',
275
         ],
278
         ],
279
+        32 => [
280
+            'template' => '{from_user} 将您添加为线索 {title} 的成员。',
281
+        ],
276
     ];
282
     ];
277
 
283
 
278
     /**
284
     /**

+ 24
- 23
application/admin/model/Scene.php Bestand weergeven

150
 	{
150
 	{
151
 		$where = [];
151
 		$where = [];
152
 		$where['scene_id'] = $id;
152
 		$where['scene_id'] = $id;
153
-		// $where['user_id'] = [['=',$user_id],['=',0],'or'];
154
 		$data = db('admin_scene')->where($where)->find();
153
 		$data = db('admin_scene')->where($where)->find();
155
 		if (!$types) {
154
 		if (!$types) {
156
 			$types = $data['types'] ? : '';
155
 			$types = $data['types'] ? : '';
407
 		$where['types'] = $types;
406
 		$where['types'] = $types;
408
 		$where['user_id'] = $user_id;
407
 		$where['user_id'] = $user_id;
409
 		$scene_id = db('admin_scene_default')->where($where)->value('scene_id');
408
 		$scene_id = db('admin_scene_default')->where($where)->value('scene_id');
410
-		if (!$scene_id && in_array($types,['crm_leads','crm_customer','crm_business','crm_contacts','crm_contract','crm_receivables','crm_visit'])) {
409
+		if (!$scene_id && in_array($types,['crm_leads','crm_customer','crm_business','crm_contacts','crm_contract','crm_receivables','crm_visit','crm_invoice'])) {
411
 			$resData['bydata'] = 'all';
410
 			$resData['bydata'] = 'all';
412
 		} else {
411
 		} else {
413
 			$resData = db('admin_scene')->where(['scene_id' => $scene_id])->find();
412
 			$resData = db('admin_scene')->where(['scene_id' => $scene_id])->find();
417
 		} else {
416
 		} else {
418
 			//处理data
417
 			//处理data
419
 			$data = $resData ? json_decode($resData,true) : [];			
418
 			$data = $resData ? json_decode($resData,true) : [];			
420
-		}		
419
+		}
421
 		return $data;				
420
 		return $data;				
422
 	}
421
 	}
423
 
422
 
429
      */	
428
      */	
430
     public function getByData($types, $bydata, $user_id)
429
     public function getByData($types, $bydata, $user_id)
431
     {
430
     {
432
-//        print_r($types . '--');
433
-//        print_r($bydata . '--');
434
-//        print_r($user_id);
435
-//        exit;
436
     	$map           = [];
431
     	$map           = [];
437
     	$auth_user_ids = [];
432
     	$auth_user_ids = [];
438
     	$part_user_ids = [];
433
     	$part_user_ids = [];
448
     		    break;
443
     		    break;
449
     		case 'sub' :
444
     		case 'sub' :
450
                 # 下属负责的
445
                 # 下属负责的
451
-    		    $auth_user_ids = getSubUserId(false) ? : ['-1'];
446
+    		    $auth_user_ids = getSubUserId(false, 0, $user_id) ? : ['-1'];
452
     		    break;
447
     		    break;
453
     		case 'all' :
448
     		case 'all' :
454
                 # 全部
449
                 # 全部
456
     		    break;
451
     		    break;
457
     		case 'is_transform' :
452
     		case 'is_transform' :
458
                 # 已转化线索
453
                 # 已转化线索
459
-    		    $map['is_transform'] = ['condition' => 'eq', 'value' => 1, 'form_type' => 'text', 'name' => ''];
454
+    		    $map['is_transform'] = ['condition' => 'is', 'value' => [1], 'form_type' => 'text', 'name' => ''];
460
     		    break;
455
     		    break;
461
     		case 'pool' :
456
     		case 'pool' :
462
     		    # 今日进入公海的客户
457
     		    # 今日进入公海的客户
465
     			break;
460
     			break;
466
             case 'win_business' :
461
             case 'win_business' :
467
                 # 赢单的商机
462
                 # 赢单的商机
468
-                $map['is_end'] = ['condition' => 'eq', 'value' => 1];
463
+                $map['is_end'] = ['condition' => 'is', 'value' => [1], 'form_type' => 'text'];
469
                 break;
464
                 break;
470
             case 'fail_business' :
465
             case 'fail_business' :
471
                 # 输单的商机
466
                 # 输单的商机
472
-                $map['is_end'] = ['condition' => 'eq', 'value' => 2];
467
+                $map['is_end'] = ['condition' => 'is', 'value' => [2], 'form_type' => 'text'];
473
                 break;
468
                 break;
474
             case 'star' :
469
             case 'star' :
475
                 $where = $this->getStarParam($types, $user_id);
470
                 $where = $this->getStarParam($types, $user_id);
476
                 if (!empty($where)) $map = $where;
471
                 if (!empty($where)) $map = $where;
477
                 break;
472
                 break;
473
+            case 'go_business' :
474
+                # 进行中的商机
475
+                $map['is_end'] = ['condition' => 'is', 'value' => ['0'], 'form_type' => 'text'];
476
+                break;
477
+            case 'put_on_shelves' :
478
+                # 上架的产品
479
+                $map['status'] = ['condition' => 'is', 'value' => ['上架'], 'form_type' => 'select', 'name' => '是否上架', 'type' => 'status'];
480
+                break;
481
+            case 'pull_off_shelves' :
482
+                # 下架的产品
483
+                $map['status'] = ['condition' => 'is', 'value' => ['下架'], 'form_type' => 'select', 'name' => '是否上架', 'type' => 'status'];
484
+                break;
478
     		default :
485
     		default :
479
                 # 全部
486
                 # 全部
480
     		    $auth_user_ids = '';
487
     		    $auth_user_ids = '';
483
     	$auth_user_ids = $auth_user_ids ? : [];
490
     	$auth_user_ids = $auth_user_ids ? : [];
484
 
491
 
485
     	if ($auth_user_ids) {
492
     	if ($auth_user_ids) {
486
-    		$map['owner_user_id'] = ['condition' => 'in','value' => $auth_user_ids,'form_type' => 'text','name' => ''];
493
+    		$map['owner_user_id'] = ['condition' => 'in', 'value' => $auth_user_ids, 'form_type' => 'user', 'name' => ''];
487
     	}
494
     	}
488
 
495
 
489
     	if ($part_user_ids) {
496
     	if ($part_user_ids) {
490
-    		$map['ro_user_id'] = $part_user_ids ? : '';
491
-    		$map['rw_user_id'] = $part_user_ids ? : '';
497
+    		$map['ro_user_id'] = $part_user_ids;
498
+    		$map['rw_user_id'] = $part_user_ids;
492
     	}
499
     	}
493
 
500
 
494
     	return $map;
501
     	return $map;
505
      */
512
      */
506
     public function getStarParam($types, $user_id)
513
     public function getStarParam($types, $user_id)
507
     {
514
     {
508
-        $where  = [];
509
-        $result = [];
510
-
511
-        $data = Db::name('crm_star')->field(['target_id'])->where(['user_id' => $user_id, 'type' => 'crm_' . $types])->select();
515
+        $primaryKey = getPrimaryKeyName('crm_' . $types);
512
 
516
 
513
-        foreach ($data AS $key => $value) $result[] = $value['target_id'];
517
+        $targetIds = Db::name('crm_star')->where(['user_id' => $user_id, 'type' => 'crm_' . $types])->column('target_id');
514
 
518
 
515
-        if ($types == 'leads')    $where['leads_id']    = $result ? ['condition' => 'in', 'value' => implode(',', $result)] : 0;
516
-        if ($types == 'customer') $where['customer_id'] = $result ? ['condition' => 'in', 'value' => implode(',', $result)] : 0;
517
-        if ($types == 'contacts') $where['contacts_id'] = $result ? ['condition' => 'in', 'value' => implode(',', $result)] : 0;
518
-        if ($types == 'business') $where['business_id'] = $result ? ['condition' => 'in', 'value' => implode(',', $result)] : 0;
519
+        $where[$primaryKey] = ['condition' => 'in', 'value' => !empty($targetIds) ? $targetIds : [-1], 'form_type' => 'user'];
519
 
520
 
520
         return $where;
521
         return $where;
521
     }
522
     }

+ 2
- 4
application/admin/model/Structure.php Bestand weergeven

64
 		return $det;
64
 		return $det;
65
 	}
65
 	}
66
 
66
 
67
-	public function delStrById($id)
67
+	public function delStrById($id,$userId)
68
 	{
68
 	{
69
 		if (!$id) {
69
 		if (!$id) {
70
 			$this->error = '删除失败';
70
 			$this->error = '删除失败';
90
 			$this->error = '删除失败';
90
 			$this->error = '删除失败';
91
 			return false;
91
 			return false;
92
 		} else {
92
 		} else {
93
-            $apiCommon = new ApiCommon();
94
-            $userInfo = $apiCommon->userInfo;
95
 		    $content='删除了部门:'.$dataInfo['name'];
93
 		    $content='删除了部门:'.$dataInfo['name'];
96
             # 添加记录
94
             # 添加记录
97
-            SystemActionLog($userInfo['id'], 'admin_structure','structures', $id,'delete', $dataInfo['name'], '', '', $content);
95
+            SystemActionLog($userId, 'admin_structure','structures', $id,'delete', $dataInfo['name'], '', '', $content);
98
             return true;
96
             return true;
99
 		}	
97
 		}	
100
 	}
98
 	}

+ 1028
- 988
application/admin/model/User.php
Diff onderdrukt omdat het te groot bestand
Bestand weergeven


+ 262
- 0
application/admin/traits/FieldVerificationTrait.php Bestand weergeven

1
+<?php
2
+/**
3
+ * 字段验证(线索、客户、联系人、商机、合同、回款、回访、产品、办公审批)
4
+ */
5
+namespace app\admin\traits;
6
+
7
+trait FieldVerificationTrait
8
+{
9
+
10
+    /**
11
+     * 数据验证
12
+     *
13
+     * @param array $param 要验证的数据
14
+     * @param int $userId 用户ID
15
+     * @param string $types 自定义表栏目类型:crm_leads、crm_customer ...
16
+     * @param int $dataId 编辑时,相应的模块数据的ID
17
+     * @param int $typesId 自定义表栏目类型ID
18
+     * @author fanqi
19
+     * @since 2021-05-18
20
+     * @return string
21
+     */
22
+    public function fieldDataValidate($param, $types, $userId, $dataId = 0, $typesId = 0)
23
+    {
24
+        $error = '';
25
+
26
+        $grantData = getFieldGrantData($userId);     # 字段授权
27
+        $userLevel = isSuperAdministrators($userId); # 用户级别
28
+
29
+        # 查询自定义字段表数据
30
+        $fieldList = $this->getFieldList($types, $typesId);
31
+
32
+        # 验证
33
+        foreach ($fieldList AS $key => $value) {
34
+            # 字段授权,没有读写权限,跳过验证。
35
+            if (!$userLevel && !empty($grantData[$types])) {
36
+                $status = getFieldGrantStatus($value['field'], $grantData[$types]);
37
+
38
+                if (empty($status['read']) || (empty($dataId) && empty($status['write']))) continue;
39
+            }
40
+
41
+            # 验证非明细表格字段数据
42
+            if (!empty($value['is_null']) && !in_array($value['form_type'], ['detail_table', 'boolean_value']) && (isset($param[$value['field']]) && empty($param[$value['field']]))) {
43
+                $error = $value['name'] . '字段不能为空!';
44
+                break;
45
+            }
46
+
47
+            # 验证字段长度
48
+            if (!empty($value['max_length']) && $value['form_type'] != 'detail_table' && strlen($param[$value['field']]) > $value['max_length']) {
49
+                $error = $value['name'] . '字段超过设定长度!';
50
+                break;
51
+            }
52
+
53
+            # 验证百分数字段长度
54
+            if ($value['form_type'] == 'percent' && strlen($param[$value['field']]) > 11) {
55
+                $error = $value['name'] . "字段长度不能大于10位!";
56
+                break;
57
+            }
58
+
59
+            # 验证数字字段长度
60
+            if ($value['form_type'] == 'number' && strlen($param[$value['field']]) > 16) {
61
+                $error = $value['name'] . "字段长度不能大于16位!";
62
+                break;
63
+            }
64
+
65
+            # 验证明细表格不能为空
66
+            if (!empty($value['is_null']) && $value['form_type'] == 'detail_table' && isset($param[$value['field']]) && empty($param[$value['field']])) {
67
+                $error = $value['name'] . '数据不能为空!';
68
+            }
69
+            # 验证明细表格可以为空,明细表格里的字段不能为空的情况。
70
+            if ($value['form_type'] == 'detail_table') {
71
+                foreach ($param[$value['field']] AS $val) {
72
+                    foreach ($val AS $v) {
73
+                        if (!empty($v['is_null']) && empty($v['is_hidden']) && isset($v['value']) && empty($v['value'])) {
74
+                            $error = $value['name'] . '中的' . $v['name'] . '字段不能为空!';
75
+                            break;
76
+                        }
77
+                    }
78
+                }
79
+            }
80
+
81
+            if (empty($value['is_unique'])) continue;
82
+
83
+            // 人员、部门、文件、手写签名、描述文字、多选、明细表格跳过验证
84
+            if (in_array($value['form_type'], ['user', 'structure', 'file', 'handwriting_sign', 'desc_text', 'checkbox', 'detail_table'])) continue;
85
+
86
+            $uniqueStatus = false;
87
+
88
+            # 验证唯一性
89
+            if ($value['form_type'] == 'date_interval' && !empty($param[$value['field']])) {
90
+                // 日期区间
91
+                $uniqueStatus = $this->checkDataUniqueForDateInterval($types, $value['field'], $param[$value['field']], $dataId);
92
+            } elseif ($value['form_type'] == 'position' && !empty($param[$value['field']])) {
93
+                // 地址
94
+                $uniqueStatus = $this->checkDataUniqueForPosition($types, $value['field'], $param[$value['field']], $dataId);
95
+            } elseif ($value['form_type'] == 'location' && !empty($param[$value['field']])) {
96
+                // 定位
97
+                $uniqueStatus = $this->checkDataUniqueForLocation($types, $value['field'], $param[$value['field']], $dataId);
98
+            } else {
99
+                if (!empty($param[$value['field']])) $uniqueStatus = $this->checkDataUniqueForCommon($types, $value['field'], $param[$value['field']], $dataId);
100
+            }
101
+
102
+            if (!empty($uniqueStatus)) {
103
+                $error = $types == 'crm_customer' ? '(客户/公海)中的' . $value['name'] . "字段值重复!" : $value['name'] . "字段值重复!";
104
+                break;
105
+            }
106
+        }
107
+
108
+        return $error;
109
+    }
110
+
111
+    /**
112
+     * 验证唯一性(通用)
113
+     * 单行文本、多行文本、网址、布尔值、单选、数字
114
+     * 手机、邮箱、日期、日期时间、货币、百分数
115
+     *
116
+     * @param string $types 栏目类型
117
+     * @param string $field 字段名称
118
+     * @param string $value 字段值
119
+     * @param int $dataId 更新时,传来的数据ID
120
+     * @author fanqi
121
+     * @since 2021-05-18
122
+     * @return float|mixed|string
123
+     */
124
+    private function checkDataUniqueForCommon($types, $field, $value, $dataId = 0)
125
+    {
126
+        if (empty($value)) return false;
127
+
128
+        # 主键
129
+        $primaryKey = getPrimaryKeyName($types);
130
+
131
+        # 查询条件
132
+        $where[$field] = $value;
133
+        if (!empty($dataId)) $where[$primaryKey] = ['neq', $dataId];
134
+
135
+        return db($types)->where($where)->value($primaryKey);
136
+    }
137
+
138
+    /**
139
+     * 验证唯一性(日期区间)
140
+     *
141
+     * @param string $types 栏目类型
142
+     * @param string $field 字段名称
143
+     * @param array $value 字段值
144
+     * @param int $dataId 更新时,传来的数据ID
145
+     * @author fanqi
146
+     * @since 2021-05-18
147
+     * @return float|mixed|string
148
+     */
149
+    private function checkDataUniqueForDateInterval($types, $field, $value, $dataId = 0)
150
+    {
151
+        if (empty($value)) return false;
152
+
153
+        # 主键
154
+        $primaryKey = getPrimaryKeyName($types);
155
+
156
+        # 查询条件
157
+        $where[$field] = implode('_', $value);
158
+        if (!empty($dataId)) $where[$primaryKey] = ['neq', $dataId];
159
+
160
+        return db($types)->where($where)->value($primaryKey);
161
+    }
162
+
163
+    /**
164
+     * 验证唯一性(地址)
165
+     *
166
+     * @param string $types 栏目类型
167
+     * @param string $field 字段名称
168
+     * @param array $value 字段值
169
+     * @param int $dataId 更新时,传来的数据ID
170
+     * @author fanqi
171
+     * @since 2021-05-18
172
+     * @return float|mixed|string
173
+     */
174
+    private function checkDataUniqueForPosition($types, $field, $value, $dataId = 0)
175
+    {
176
+        if (empty($value)) return false;
177
+
178
+        # 主键
179
+        $primaryKey = getPrimaryKeyName($types);
180
+
181
+        # 查询条件
182
+        $where[$field] = implode(',', array_column($value, 'name'));
183
+        if (!empty($dataId)) $where[$primaryKey] = ['neq', $dataId];
184
+
185
+        return db($types)->where($where)->value($primaryKey);
186
+    }
187
+
188
+    /**
189
+     * 验证唯一性(定位)
190
+     *
191
+     * @param string $types 栏目类型
192
+     * @param string $field 字段名称
193
+     * @param array $value 字段值
194
+     * @param int $dataId 更新时,传来的数据ID
195
+     * @author fanqi
196
+     * @since 2021-05-18
197
+     * @return float|mixed|string
198
+     */
199
+    private function checkDataUniqueForLocation($types, $field, $value, $dataId = 0)
200
+    {
201
+        if (empty($value['address'])) return false;
202
+
203
+        # 主键
204
+        $primaryKey = getPrimaryKeyName($types);
205
+
206
+        # 查询条件
207
+        $where[$field] = $value['address'];
208
+        if (!empty($dataId)) $where[$primaryKey] = ['neq', $dataId];
209
+
210
+        return db($types)->where($where)->value($primaryKey);
211
+    }
212
+
213
+//    /**
214
+//     * 验证唯一性(部门)
215
+//     *
216
+//     * @param string $types 栏目类型
217
+//     * @param string $field 字段名称
218
+//     * @param string $value 字段值
219
+//     * @param int $dataId 更新时,传来的数据ID
220
+//     * @author fanqi
221
+//     * @since 2021-05-18
222
+//     * @return float|mixed|string
223
+//     */
224
+//    private function checkDataUniqueForStructure($types, $field, $value, $dataId = 0)
225
+//    {
226
+//        if (empty($value)) return false;
227
+//
228
+//        # 主键
229
+//        $primaryKey = getPrimaryKeyName($types);
230
+//
231
+//        # 查询条件
232
+//        $where[$field] = ',' . $value . ',';
233
+//        if (!empty($dataId)) $where[$primaryKey] = ['neq', $dataId];
234
+//
235
+//        return db($types)->where($where)->value($primaryKey);
236
+//    }
237
+
238
+    /**
239
+     * 自定义字段列表
240
+     *
241
+     * @param string $types 自定义表栏目类型:crm_leads、crm_customer ...
242
+     * @param int $typesId 自定义表栏目类型ID
243
+     * @author fanqi
244
+     * @since 2021-05-18
245
+     * @return bool|\PDOStatement|string|\think\Collection
246
+     */
247
+    private function getFieldList($types, $typesId)
248
+    {
249
+        # 查询条件
250
+        $where = [
251
+            'types'     => $types,
252
+            'types_id'  => $typesId,
253
+            'is_hidden' => 0,
254
+            'form_type' => ['neq', 'desc_text']
255
+        ];
256
+
257
+        # 查询字段
258
+        $fields = ['field', 'name', 'form_type', 'is_unique', 'is_null', 'max_length'];
259
+
260
+        return db('admin_field')->field($fields)->where($where)->select();
261
+    }
262
+}

+ 2
- 40
application/admin/view/install/step6.html Bestand weergeven

42
         <h1 style="text-align:center;padding-top: 20px;">安装悟空CRM数据库超时,请手动导入SQL文件!</h1>
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;">
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>
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>
45
+            <p>2、修改config目录下database_template.php文件的数据库连接信息</p>
46
+            <p>3、最后将database_template.php重名为database.php</p>
85
         </div>
47
         </div>
86
     </div>
48
     </div>
87
 </div>
49
 </div>

+ 1
- 0
application/command.php Bestand weergeven

12
 return [
12
 return [
13
     app\common\command\ImportFollowRecord::class,
13
     app\common\command\ImportFollowRecord::class,
14
     app\common\command\PoolCommand::class,
14
     app\common\command\PoolCommand::class,
15
+    app\common\command\Team::class,
15
 ];
16
 ];

+ 867
- 284
application/common.php
Diff onderdrukt omdat het te groot bestand
Bestand weergeven


+ 102
- 100
application/common/command/PoolCommand.php Bestand weergeven

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

+ 153
- 0
application/common/command/Team.php Bestand weergeven

1
+<?php
2
+/**
3
+ * 使用定时器将符合条件的团队成员移出团队
4
+ *
5
+ * @author guogaobo
6
+ * @since 2021-05-20
7
+ */
8
+
9
+namespace app\common\command;
10
+
11
+use think\Config;
12
+use think\console\Command;
13
+use think\console\Input;
14
+use think\console\input\Argument;
15
+use think\console\input\Option;
16
+use think\console\Output;
17
+use think\Db;
18
+use think\response\Json;
19
+use Workerman\Lib\Timer;
20
+use Workerman\Worker;
21
+
22
+class Team extends Command
23
+{
24
+    protected $timer;
25
+    protected $interval = 10;
26
+    
27
+    protected function configure()
28
+    {
29
+        $this->setName('team')
30
+            ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
31
+            ->addOption('d', null, Option::VALUE_NONE, 'daemon(守护进程)方式启动')
32
+            ->setDescription('团队成员移出定时器');
33
+        
34
+        // 读取数据库配置文件
35
+        $filename = ROOT_PATH . 'config' . DS . 'database.php';
36
+        // 重新加载数据库配置文件
37
+        Config::load($filename, 'database');
38
+    }
39
+    
40
+    /**
41
+     * 初始化
42
+     *
43
+     * @param Input $input
44
+     * @param Output $output
45
+     */
46
+    protected function init(Input $input, Output $output)
47
+    {
48
+        global $argv;
49
+        
50
+        $argv[1] = $input->getArgument('status') ?: 'start';
51
+        
52
+        if ($input->hasOption('d')) {
53
+            $argv[2] = '-d';
54
+        } else {
55
+            unset($argv[2]);
56
+        }
57
+    }
58
+    
59
+    /**
60
+     * 停止定时器
61
+     */
62
+    public function stop()
63
+    {
64
+        Timer::del($this->timer);
65
+    }
66
+    
67
+    /**
68
+     * 启动定时器
69
+     */
70
+    public function start()
71
+    {
72
+        $this->timer = Timer::add(1, function () {
73
+            # 只在凌晨12点至6点间执行
74
+            if ((int)date('H') >= 0 && (int)date('H') < 6) {
75
+            # 团队成员过滤规则
76
+            db('crm_team')->where('target_time',0)->delete();
77
+            $ruleList = db('crm_team')
78
+                ->where('target_time', '<', time())->select();
79
+            if (!empty($ruleList)) {
80
+                Db::startTrans();
81
+                try {
82
+                    foreach ($ruleList as $v) {
83
+                        
84
+                        switch ($v['types']) {
85
+                            case 1 :
86
+                                $data_name = 'customer_id';
87
+                                $types = 'crm_customer';
88
+                                $typesName = '客户';
89
+                                break;
90
+                            case 2 :
91
+                                $data_name = 'contacts_id';
92
+                                $types = 'crm_contacts';
93
+                                $typesName = '联系人';
94
+                                break;
95
+                            case 3 :
96
+                                $data_name = 'business_id';
97
+                                $types = 'crm_business';
98
+                                $typesName = '商机';
99
+                                break;
100
+                            case 4 :
101
+                                $data_name = 'contract_id';
102
+                                $types = 'crm_contract';
103
+                                $typesName = '合同';
104
+                                break;
105
+                            case 5 :
106
+                                $data_name = 'receivables_id';
107
+                                $types = 'crm_receivables';
108
+                                $typesName = '回款';
109
+                                break;
110
+                        }
111
+                        $resData = db($types)->where([$data_name => $v['target_id']])->field('name,rw_user_id,ro_user_id')->find();
112
+                        if ($v['types'] == 5) {
113
+                            $resData = db($types)->where([$data_name => $v['target_id']])->field('number as name,rw_user_id,ro_user_id')->find();
114
+                        }
115
+                        $team_user_id = array_column($ruleList, 'team_user_id');
116
+                        $old_rw_user_id = !empty($resData['rw_user_id']) ? explode(',', trim($resData['rw_user_id'], ',')) : []; //去重
117
+                        //只读
118
+                        $old_ro_user_id = !empty($resData['ro_user_id']) ? explode(',', trim($resData['ro_user_id'], ',')) : []; //去重
119
+                        if ($v['auth'] == 1) {
120
+                            $all_rw_user_id = $team_user_id ? array_diff($old_ro_user_id, $team_user_id) : ''; // 差集
121
+                            $data['ro_user_id'] = $all_rw_user_id ? ',' . implode(',', $all_rw_user_id) . ',' : ''; //去空
122
+                        } else {
123
+                            $all_ro_user_id = $team_user_id ? array_diff($old_rw_user_id, $team_user_id) : ''; // 差集
124
+                            $data['rw_user_id'] = $all_ro_user_id ? ',' . implode(',', $all_ro_user_id) . ',' : ''; //去空    ;
125
+                        }
126
+                        $upData = db($types)->where([$data_name => $v['target_id']])->update($data);
127
+                        db('crm_team')->where(['target_id' => $v['target_id'], 'types' => $v['types'], 'team_user_id' => ['in', arrayToString($team_user_id)]])->delete();
128
+                    }
129
+                    Db::commit();
130
+                } catch (\Exception $e) {
131
+                    Db::rollback();
132
+                }
133
+            }
134
+            }
135
+        });
136
+    }
137
+    
138
+    protected function execute(Input $input, Output $output)
139
+    {
140
+        # 动态修改运行时参数
141
+        set_time_limit(0);
142
+        ini_set('memory_limit', '512M');
143
+        
144
+        $this->init($input, $output);
145
+        
146
+        # 创建定时器任务
147
+        $worker = new Worker();
148
+        $worker->name = 'team';
149
+        $worker->count = 1;
150
+        $worker->onWorkerStart = [$this, 'start'];
151
+        $worker->runAll();
152
+    }
153
+}

+ 112
- 32
application/crm/common.php Bestand weergeven

1
 <?php
1
 <?php
2
 //权限控制
2
 //权限控制
3
-\think\Hook::add('check_auth','app\\common\\behavior\\AuthenticateBehavior');
3
+\think\Hook::add('check_auth', 'app\\common\\behavior\\AuthenticateBehavior');
4
 
4
 
5
 use think\Db;
5
 use think\Db;
6
 
6
 
7
 /**
7
 /**
8
  * 处理相关团队
8
  * 处理相关团队
9
- * @author
10
  * @param types 类型
9
  * @param types 类型
11
  * @param types 类型ID
10
  * @param types 类型ID
12
  * @param type  权限 1只读2读写
11
  * @param type  权限 1只读2读写
14
  * @param is_del 1 移除操作, 2编辑操作, 3添加操作
13
  * @param is_del 1 移除操作, 2编辑操作, 3添加操作
15
  * @param owner_user_id 操作人
14
  * @param owner_user_id 操作人
16
  * @param is_module 相关 1相关,不进行数据权限判断
15
  * @param is_module 相关 1相关,不进行数据权限判断
16
+ * @author
17
  */
17
  */
18
-function teamUserId($types, $types_id, $type, $user_id, $is_del, $owner_user_id, $is_module = 0)
18
+function teamUserId($param, $types, $types_id, $type, $user_id, $is_del, $owner_user_id, $is_module = 0)
19
 {
19
 {
20
     $userModel = new \app\admin\model\User();
20
     $userModel = new \app\admin\model\User();
21
     $authIds = [];
21
     $authIds = [];
22
-	switch ($types) {
23
-        case 'crm_leads' : 
22
+    switch ($types) {
23
+        case 'crm_leads' :
24
             $data_name = 'leads_id';
24
             $data_name = 'leads_id';
25
             $authIds = $userModel->getUserByPer('crm', 'leads', 'teamsave');
25
             $authIds = $userModel->getUserByPer('crm', 'leads', 'teamsave');
26
             break;
26
             break;
27
-        case 'crm_customer' : 
28
-            $data_name = 'customer_id'; 
27
+        case 'crm_customer' :
28
+            $data_name = 'customer_id';
29
             $authIds = $userModel->getUserByPer('crm', 'customer', 'teamsave');
29
             $authIds = $userModel->getUserByPer('crm', 'customer', 'teamsave');
30
             break;
30
             break;
31
-        case 'crm_contacts' : 
31
+        case 'crm_contacts' :
32
             $data_name = 'contacts_id';
32
             $data_name = 'contacts_id';
33
-            $authIds = $userModel->getUserByPer('crm', 'contacts', 'teamsave'); 
33
+            $authIds = $userModel->getUserByPer('crm', 'contacts', 'teamsave');
34
             break;
34
             break;
35
-        case 'crm_business' : 
36
-            $data_name = 'business_id'; 
35
+        case 'crm_business' :
36
+            $data_name = 'business_id';
37
             $authIds = $userModel->getUserByPer('crm', 'business', 'teamsave');
37
             $authIds = $userModel->getUserByPer('crm', 'business', 'teamsave');
38
             break;
38
             break;
39
-        case 'crm_contract' : 
40
-            $data_name = 'contract_id'; 
39
+        case 'crm_contract' :
40
+            $data_name = 'contract_id';
41
             $authIds = $userModel->getUserByPer('crm', 'contract', 'teamsave');
41
             $authIds = $userModel->getUserByPer('crm', 'contract', 'teamsave');
42
             break;
42
             break;
43
+        case 'crm_receivables' :
44
+            $data_name = 'receivables_id';
45
+            $authIds = $userModel->getUserByPer('crm', 'receivables', 'teamsave');
46
+            break;
43
     }
47
     }
44
     if (!is_array($types_id) && $types_id) {
48
     if (!is_array($types_id) && $types_id) {
45
         $types_id = [$types_id];
49
         $types_id = [$types_id];
46
     }
50
     }
47
     $errorMessage = [];
51
     $errorMessage = [];
48
-    foreach ($types_id as $k=>$v) {
49
-        $resData = db($types)->where([$data_name => $v])->field('name,owner_user_id,rw_user_id,ro_user_id')->find();
50
-        if (!in_array($resData['owner_user_id'],$authIds) && $resData['owner_user_id'] && $is_module !== 1) {
51
-            $errorMessage[] = $resData['name'].'处理团队操作失败,错误原因:无权限';
52
+    foreach ($types_id as $k => $v) {
53
+        if ($types == 'crm_receivables') {
54
+            $resData = db($types)->where([$data_name => $v])->field('number as name,owner_user_id,rw_user_id,ro_user_id')->find();
55
+        } else {
56
+            $resData = db($types)->where([$data_name => $v])->field('name,owner_user_id,rw_user_id,ro_user_id')->find();
57
+        }
58
+        
59
+        if (!in_array($resData['owner_user_id'], $authIds) && $resData['owner_user_id'] && $is_module !== 1) {
60
+            $errorMessage[] = $resData['name'] . '处理团队操作失败,错误原因:无权限';
52
             continue;
61
             continue;
53
-        }  
54
-        $type = $type ? : 1;
62
+        }
63
+        $type = $type ?: 1;
55
         $data = [];
64
         $data = [];
56
         //读写
65
         //读写
57
-        $old_rw_user_id = stringToArray($resData['rw_user_id']) ? : []; //去重
66
+        $old_rw_user_id = stringToArray($resData['rw_user_id']) ?: []; //去重
58
         //只读
67
         //只读
59
-        $old_ro_user_id = stringToArray($resData['ro_user_id']) ? : []; //去重          
68
+        $old_ro_user_id = stringToArray($resData['ro_user_id']) ?: []; //去重
60
         if ($is_del == 1) {
69
         if ($is_del == 1) {
61
             $all_rw_user_id = $old_rw_user_id ? array_diff($old_rw_user_id, $user_id) : ''; // 差集
70
             $all_rw_user_id = $old_rw_user_id ? array_diff($old_rw_user_id, $user_id) : ''; // 差集
62
             $data['rw_user_id'] = $all_rw_user_id ? arrayToString($all_rw_user_id) : ''; //去空
71
             $data['rw_user_id'] = $all_rw_user_id ? arrayToString($all_rw_user_id) : ''; //去空
63
-
72
+            
64
             $all_ro_user_id = $old_ro_user_id ? array_diff($old_ro_user_id, $user_id) : ''; // 差集
73
             $all_ro_user_id = $old_ro_user_id ? array_diff($old_ro_user_id, $user_id) : ''; // 差集
65
             $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空           
74
             $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空           
66
         } elseif ($is_del == 2) {
75
         } elseif ($is_del == 2) {
76
         } else {
85
         } else {
77
             $del_ro_user_id = []; //需要删除的只读
86
             $del_ro_user_id = []; //需要删除的只读
78
             $del_rw_user_id = []; //需要删除的读写
87
             $del_rw_user_id = []; //需要删除的读写
79
-            foreach ($user_id as $key=>$val) {
88
+            foreach ($user_id as $key => $val) {
80
                 if (in_array($val, $old_ro_user_id) && !in_array($val, $old_rw_user_id) && $type == 2) {
89
                 if (in_array($val, $old_ro_user_id) && !in_array($val, $old_rw_user_id) && $type == 2) {
81
                     $del_ro_user_id[] = $val;
90
                     $del_ro_user_id[] = $val;
82
                 }
91
                 }
83
                 if (in_array($val, $old_rw_user_id) && !in_array($val, $old_ro_user_id) && $type == 1) {
92
                 if (in_array($val, $old_rw_user_id) && !in_array($val, $old_ro_user_id) && $type == 1) {
84
                     $del_rw_user_id[] = $val;
93
                     $del_rw_user_id[] = $val;
85
-                }                
94
+                }
86
             }
95
             }
87
             if ($type == 2) {
96
             if ($type == 2) {
88
                 $all_rw_user_id = $old_rw_user_id ? array_diff(array_merge($old_rw_user_id, $user_id), $del_rw_user_id) : $user_id; // 合并
97
                 $all_rw_user_id = $old_rw_user_id ? array_diff(array_merge($old_rw_user_id, $user_id), $del_rw_user_id) : $user_id; // 合并
90
                 $data['rw_user_id'] = $all_rw_user_id ? arrayToString($all_rw_user_id) : ''; //去空 
99
                 $data['rw_user_id'] = $all_rw_user_id ? arrayToString($all_rw_user_id) : ''; //去空 
91
                 if ($del_ro_user_id) {
100
                 if ($del_ro_user_id) {
92
                     $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空         
101
                     $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空         
93
-                }                
102
+                }
94
             } else {
103
             } else {
95
                 $all_rw_user_id = $old_rw_user_id ? array_diff($old_rw_user_id, $del_rw_user_id) : $user_id; // 合并
104
                 $all_rw_user_id = $old_rw_user_id ? array_diff($old_rw_user_id, $del_rw_user_id) : $user_id; // 合并
96
                 $all_ro_user_id = $old_ro_user_id ? array_diff(array_merge($old_ro_user_id, $user_id), $del_ro_user_id) : $user_id; // 合并                
105
                 $all_ro_user_id = $old_ro_user_id ? array_diff(array_merge($old_ro_user_id, $user_id), $del_ro_user_id) : $user_id; // 合并                
97
                 $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空 
106
                 $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空 
98
                 if ($del_rw_user_id) {
107
                 if ($del_rw_user_id) {
99
                     $data['rw_user_id'] = $all_rw_user_id ? arrayToString($all_rw_user_id) : ''; //去空         
108
                     $data['rw_user_id'] = $all_rw_user_id ? arrayToString($all_rw_user_id) : ''; //去空         
100
-                }                             
109
+                }
101
             }
110
             }
102
         }
111
         }
112
+        $res = !empty($param['user_id']) ?$param['user_id']  :[];
113
+        $types_data = ['crm_leads' => 6, 'crm_customer' => 1, 'crm_contacts' => 2, 'crm_business' => 3, 'crm_contract' => 4, 'crm_receivables' => 5];
114
+        $target_time = $param['target_time'];
115
+        $request = [];
116
+        foreach ($res as $val) {
117
+            $request['team_user_id'] = $val;
118
+            $request['target_time'] = $target_time;
119
+            $request['auth'] = $type;
120
+            $request['target_id'] = $v;
121
+            $dataInfo = db('crm_team')->where(['target_id' => $v, 'types' => $types_data[$types],'team_user_id'=>$val])->find();
122
+            if ($dataInfo) {
123
+                $res = db('crm_team')->where(['target_id' => $v, 'types' => $types_data[$types],'team_user_id'=>$val])->update($request);
124
+            } else {
125
+                $request['types'] = $types_data[$types];
126
+                $res = db('crm_team')->insert($request);
127
+            }
128
+        }
129
+        
103
         $upData = db($types)->where([$data_name => $v])->update($data);
130
         $upData = db($types)->where([$data_name => $v])->update($data);
104
-        if (!$upData) {
105
-            $errorMessage[] = $resData['name'].'处理团队操作失败'; 
131
+        if (!$upData && !$res) {
132
+            $errorMessage[] = $resData['name'] . '处理团队操作失败';
106
         }
133
         }
107
     }
134
     }
108
-    return $errorMessage ? : 1;
135
+    return $errorMessage ?: 1;
109
 }
136
 }
110
 
137
 
111
 //根据时间段获取所包含的年份
138
 //根据时间段获取所包含的年份
114
     $yearArr = [];
141
     $yearArr = [];
115
     $monthArr = monthList($start_time, $end_time);
142
     $monthArr = monthList($start_time, $end_time);
116
     foreach ($monthArr as $v) {
143
     foreach ($monthArr as $v) {
117
-        $yearArr[date('Y',$v)] = date('Y',$v);
144
+        $yearArr[date('Y', $v)] = date('Y', $v);
118
     }
145
     }
119
     return $yearArr;
146
     return $yearArr;
120
 }
147
 }
125
     $monthList = [];
152
     $monthList = [];
126
     $monthArr = monthList($start_time, $end_time);
153
     $monthArr = monthList($start_time, $end_time);
127
     foreach ($monthArr as $v) {
154
     foreach ($monthArr as $v) {
128
-        $monthList[date('Y',$v)][] = date('m',$v);
155
+        $monthList[date('Y', $v)][] = date('m', $v);
129
     }
156
     }
130
     return $monthList;
157
     return $monthList;
131
-}
158
+}
159
+
160
+function encrypt($data, $key)
161
+{
162
+    header('Content-type:text/html;charset=utf-8');
163
+    $key = md5($key);
164
+    $x = 0;
165
+    $len = mb_strlen($data);
166
+    $l = mb_strlen($key);
167
+    for ($i = 0; $i < $len; $i++) {
168
+        if ($x == $l) {
169
+            $x = 0;
170
+        }
171
+        $char .= $key{$x};
172
+        $x++;
173
+    }
174
+    for ($i = 0; $i < $len; $i++) {
175
+        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
176
+    }
177
+    return base64_encode($str);
178
+}
179
+
180
+/**
181
+ * [对加密的数据进行解密]
182
+ * @E-mial wuliqiang_aa@163.com
183
+ * @TIME   2017-04-07
184
+ * @WEB    http://blog.iinu.com.cn
185
+ * @param  [数据] $data [已经进行加密的数据]
186
+ * @param  [密钥] $key  [解密的唯一方法]
187
+ */
188
+function decrypt($data, $key = '72-crm')
189
+{
190
+    header('Content-type:text/html;charset=utf-8');
191
+    $key = md5($key);
192
+    $x = 0;
193
+    $data = base64_decode($data);
194
+    $len = mb_strlen($data);
195
+    $l = mb_strlen($key);
196
+    for ($i = 0; $i < $len; $i++) {
197
+        if ($x == $l) {
198
+            $x = 0;
199
+        }
200
+        $char .= mb_substr($key, $x, 1);
201
+        $x++;
202
+    }
203
+    for ($i = 0; $i < $len; $i++) {
204
+        if (ord(mb_substr($data, $i, 1)) < ord(mb_substr($char, $i, 1))) {
205
+            $str .= chr((ord(mb_substr($data, $i, 1)) + 256) - ord(mb_substr($char, $i, 1)));
206
+        } else {
207
+            $str .= chr(ord(mb_substr($data, $i, 1)) - ord(mb_substr($char, $i, 1)));
208
+        }
209
+    }
210
+    return $str;
211
+}

+ 132
- 140
application/crm/controller/Activity.php Bestand weergeven

5
  * @author qifan
5
  * @author qifan
6
  * @date 2020-12-09
6
  * @date 2020-12-09
7
  */
7
  */
8
+
8
 namespace app\crm\controller;
9
 namespace app\crm\controller;
9
 
10
 
10
 use app\admin\controller\ApiCommon;
11
 use app\admin\controller\ApiCommon;
23
     public function _initialize()
24
     public function _initialize()
24
     {
25
     {
25
         $action = [
26
         $action = [
26
-            'permission'=>[],
27
-            'allow'=>['index', 'save', 'read', 'update', 'delete', 'getphrase', 'setphrase', 'getrecordauth','excelimport','excelexport','exceldownload']
27
+            'permission' => [],
28
+            'allow' => ['index', 'save', 'read', 'update', 'delete', 'getphrase', 'setphrase', 'getrecordauth', 'excelimport', 'excelexport', 'exceldownload']
28
         ];
29
         ];
29
-        Hook::listen('check_auth',$action);
30
+        Hook::listen('check_auth', $action);
30
         $request = Request::instance();
31
         $request = Request::instance();
31
         $a = strtolower($request->action());
32
         $a = strtolower($request->action());
32
         if (!in_array($a, $action['permission'])) {
33
         if (!in_array($a, $action['permission'])) {
33
             parent::_initialize();
34
             parent::_initialize();
34
         }
35
         }
35
     }
36
     }
36
-
37
+    
37
     /**
38
     /**
38
      * 活动列表
39
      * 活动列表
39
      *
40
      *
47
     {
48
     {
48
         $param = $this->param;
49
         $param = $this->param;
49
         $param['user_id'] = $this->userInfo['id'];
50
         $param['user_id'] = $this->userInfo['id'];
50
-
51
+        
51
         $data = $activityLogic->index($param);
52
         $data = $activityLogic->index($param);
52
-
53
+        
53
         return resultArray(['data' => $data]);
54
         return resultArray(['data' => $data]);
54
     }
55
     }
55
-
56
+    
56
     /**
57
     /**
57
      * 创建活动【跟进记录】
58
      * 创建活动【跟进记录】
58
      *
59
      *
66
         if (!checkPerByAction('crm', 'activity', 'save')) {
67
         if (!checkPerByAction('crm', 'activity', 'save')) {
67
             return resultArray(['error' => '你没有创建跟进记录的权限!']);
68
             return resultArray(['error' => '你没有创建跟进记录的权限!']);
68
         }
69
         }
69
-        if (empty($this->param['activity_type']))    return resultArray(['error' => '缺少模块类型!']);
70
+        if (empty($this->param['activity_type'])) return resultArray(['error' => '缺少模块类型!']);
70
         if (empty($this->param['activity_type_id'])) return resultArray(['error' => '缺少活动类型ID!']);
71
         if (empty($this->param['activity_type_id'])) return resultArray(['error' => '缺少活动类型ID!']);
71
-        if (empty($this->param['content']))          return resultArray(['error' => '请填写跟进内容!']);
72
+        if (empty($this->param['content'])) return resultArray(['error' => '请填写跟进内容!']);
72
         if (!empty($this->param['next_time']) && strtotime($this->param['next_time']) < time()) {
73
         if (!empty($this->param['next_time']) && strtotime($this->param['next_time']) < time()) {
73
             return resultArray(['error' => '下次联系时间不能在当前时间之前!']);
74
             return resultArray(['error' => '下次联系时间不能在当前时间之前!']);
74
         }
75
         }
75
-
76
+        
76
         $param = $this->param;
77
         $param = $this->param;
77
         $param['user_id'] = $this->userInfo['id'];
78
         $param['user_id'] = $this->userInfo['id'];
78
-
79
+        
79
         if (!$activityLogic->save($param)) return resultArray(['error' => '操作失败!']);
80
         if (!$activityLogic->save($param)) return resultArray(['error' => '操作失败!']);
80
         return resultArray(['data' => '操作成功!']);
81
         return resultArray(['data' => '操作成功!']);
81
     }
82
     }
82
-
83
+    
83
     /**
84
     /**
84
      * 活动详情
85
      * 活动详情
85
      *
86
      *
95
             return resultArray(['error' => '你没有查看跟进记录的权限!']);
96
             return resultArray(['error' => '你没有查看跟进记录的权限!']);
96
         }
97
         }
97
         if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']);
98
         if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']);
98
-
99
+        
99
         $data = $activityLogic->read($this->param['activity_id']);
100
         $data = $activityLogic->read($this->param['activity_id']);
100
-
101
+        
101
         return resultArray(['data' => $data]);
102
         return resultArray(['data' => $data]);
102
     }
103
     }
103
-
104
+    
104
     /**
105
     /**
105
      * 编辑活动【跟进记录】
106
      * 编辑活动【跟进记录】
106
      *
107
      *
114
         if (!checkPerByAction('crm', 'activity', 'update')) {
115
         if (!checkPerByAction('crm', 'activity', 'update')) {
115
             return resultArray(['error' => '你没有编辑跟进记录的权限!']);
116
             return resultArray(['error' => '你没有编辑跟进记录的权限!']);
116
         }
117
         }
117
-        if (empty($this->param['activity_id']))      return resultArray(['error' => '请选择跟进记录!']);
118
-        if (empty($this->param['activity_type']))    return resultArray(['error' => '缺少活动类型!']);
118
+        if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']);
119
+        if (empty($this->param['activity_type'])) return resultArray(['error' => '缺少活动类型!']);
119
         if (empty($this->param['activity_type_id'])) return resultArray(['error' => '缺少活动类型ID!']);
120
         if (empty($this->param['activity_type_id'])) return resultArray(['error' => '缺少活动类型ID!']);
120
-        if (empty($this->param['content']))          return resultArray(['error' => '请填写跟进内容!']);
121
-
122
-        $param  = $this->param;
121
+        if (empty($this->param['content'])) return resultArray(['error' => '请填写跟进内容!']);
122
+        
123
+        $param = $this->param;
123
         $userId = $this->userInfo['id'];
124
         $userId = $this->userInfo['id'];
124
-
125
+        
125
         if (!$activityLogic->update($param)) return resultArray(['error' => '操作失败!']);
126
         if (!$activityLogic->update($param)) return resultArray(['error' => '操作失败!']);
126
-
127
+        
127
         $data = $activityLogic->getFollowData($param['activity_id'], $userId);
128
         $data = $activityLogic->getFollowData($param['activity_id'], $userId);
128
-
129
+        
129
         return resultArray(['data' => $data]);
130
         return resultArray(['data' => $data]);
130
     }
131
     }
131
-
132
+    
132
     /**
133
     /**
133
      * 删除活动【跟进记录】
134
      * 删除活动【跟进记录】
134
      *
135
      *
137
      */
138
      */
138
     public function delete(ActivityLogic $activityLogic)
139
     public function delete(ActivityLogic $activityLogic)
139
     {
140
     {
141
+        $userInfo = $this->userInfo;
140
         if (!checkPerByAction('crm', 'activity', 'delete')) {
142
         if (!checkPerByAction('crm', 'activity', 'delete')) {
141
             return resultArray(['error' => '你没有删除跟进记录的权限!']);
143
             return resultArray(['error' => '你没有删除跟进记录的权限!']);
142
         }
144
         }
143
         if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']);
145
         if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']);
144
-
145
-        if (!$activityLogic->delete($this->param['activity_id'])) return resultArray(['error' => '操作失败!']);
146
+        
147
+        if (!$activityLogic->delete($this->param['activity_id'], $userInfo['id'])) return resultArray(['error' => '操作失败!']);
146
         return resultArray(['data' => '操作成功!']);
148
         return resultArray(['data' => '操作成功!']);
147
     }
149
     }
148
-
150
+    
149
     /**
151
     /**
150
      * 获取常用语
152
      * 获取常用语
151
      *
153
      *
155
     public function getPhrase(ActivityLogic $activityLogic)
157
     public function getPhrase(ActivityLogic $activityLogic)
156
     {
158
     {
157
         $data = $activityLogic->getPhrase();
159
         $data = $activityLogic->getPhrase();
158
-
160
+        
159
         return resultArray(['data' => $data]);
161
         return resultArray(['data' => $data]);
160
     }
162
     }
161
-
163
+    
162
     /**
164
     /**
163
      * 设置常用语
165
      * 设置常用语
164
      *
166
      *
169
      */
171
      */
170
     public function setPhrase(ActivityLogic $activityLogic)
172
     public function setPhrase(ActivityLogic $activityLogic)
171
     {
173
     {
172
-        if (empty($this->param['phrase']))     return resultArray(['error' => '缺少常用语数据!']);
174
+        if (empty($this->param['phrase'])) return resultArray(['error' => '缺少常用语数据!']);
173
         if (!is_array($this->param['phrase'])) return resultArray(['error' => '参数格式错误!']);
175
         if (!is_array($this->param['phrase'])) return resultArray(['error' => '参数格式错误!']);
174
-
176
+        
175
         if (!$activityLogic->setPhrase($this->param['phrase'])) return resultArray(['error' => '操作失败!']);
177
         if (!$activityLogic->setPhrase($this->param['phrase'])) return resultArray(['error' => '操作失败!']);
176
-
178
+        
177
         return resultArray(['data' => '操作成功!']);
179
         return resultArray(['data' => '操作成功!']);
178
     }
180
     }
179
-
181
+    
180
     /**
182
     /**
181
      * 跟进记录权限
183
      * 跟进记录权限
182
      *
184
      *
185
     public function getRecordAuth()
187
     public function getRecordAuth()
186
     {
188
     {
187
         $data = [
189
         $data = [
188
-            'index'  => checkPerByAction('crm', 'activity', 'index'),
189
-            'read'   => checkPerByAction('crm', 'activity', 'read'),
190
-            'save'   => checkPerByAction('crm', 'activity', 'save'),
190
+            'index' => checkPerByAction('crm', 'activity', 'index'),
191
+            'read' => checkPerByAction('crm', 'activity', 'read'),
192
+            'save' => checkPerByAction('crm', 'activity', 'save'),
191
             'update' => checkPerByAction('crm', 'activity', 'update'),
193
             'update' => checkPerByAction('crm', 'activity', 'update'),
192
             'delete' => checkPerByAction('crm', 'activity', 'delete'),
194
             'delete' => checkPerByAction('crm', 'activity', 'delete'),
193
         ];
195
         ];
194
-
196
+        
195
         return resultArray(['data' => $data]);
197
         return resultArray(['data' => $data]);
196
     }
198
     }
199
+    
197
     /**
200
     /**
198
      * 导入模板下载
201
      * 导入模板下载
199
      * @author      alvin guogaobo
202
      * @author      alvin guogaobo
200
      * @version     1.0 版本号
203
      * @version     1.0 版本号
201
      * @since       2021/4/10 0010 16:01
204
      * @since       2021/4/10 0010 16:01
202
      */
205
      */
203
-    public function excelDownload($save_path = ''){
206
+    public function excelDownload($save_path = '')
207
+    {
204
         $param = $this->param;
208
         $param = $this->param;
205
         $excelModel = new \app\admin\model\Excel();
209
         $excelModel = new \app\admin\model\Excel();
206
-        $field_list=$this->importData($param);
207
-        $types='crm_activity';
208
-        $excelModel->importDown($field_list,$types,$save_path);
210
+        $field_list = $this->importData($param);
211
+        $types = 'crm_activity';
212
+        $excelModel->excelImportDownload($field_list, $types, $save_path);
209
     }
213
     }
210
     
214
     
211
     /**
215
     /**
216
      * @version     1.0 版本号
220
      * @version     1.0 版本号
217
      * @since       2021/4/13 0013 11:15
221
      * @since       2021/4/13 0013 11:15
218
      */
222
      */
219
-    public function importData($param){
220
-        switch ($param['label']){
223
+    public function importData($param)
224
+    {
225
+        $field_list = [];
226
+        switch ($param['crmType']) {
221
             case 1 :
227
             case 1 :
222
                 $field = [
228
                 $field = [
223
                     '2' => [
229
                     '2' => [
224
                         'name' => '所属线索',
230
                         'name' => '所属线索',
225
                         'field' => 'activity_type_id',
231
                         'field' => 'activity_type_id',
226
-                        'types' => 'log',
227
-                        'form_type' => 'datetime',
232
+                        'form_type' => 'leads_id',
228
                         'is_null' => 1,
233
                         'is_null' => 1,
229
                     ]
234
                     ]
230
                 ];
235
                 ];
236
+                $name = '所属线索';
231
                 break;
237
                 break;
232
             case 3:
238
             case 3:
233
                 $field = [
239
                 $field = [
234
                     '2' => [
240
                     '2' => [
235
                         'name' => '所属联系人',
241
                         'name' => '所属联系人',
236
                         'field' => 'activity_type_id',
242
                         'field' => 'activity_type_id',
237
-                        'types' => 'log',
238
-                        'form_type' => 'datetime',
243
+                        'form_type' => 'contacts_id',
239
                         'is_null' => 1,
244
                         'is_null' => 1,
240
                     ],
245
                     ],
241
                 ];
246
                 ];
247
+                $name = '所属联系人';
242
                 break;
248
                 break;
243
             case 5:
249
             case 5:
244
                 $field = [
250
                 $field = [
245
                     '2' => [
251
                     '2' => [
246
                         'name' => '所属商机',
252
                         'name' => '所属商机',
247
                         'field' => 'activity_type_id',
253
                         'field' => 'activity_type_id',
248
-                        'types' => 'log',
249
-                        'form_type' => 'text',
254
+                        'form_type' => 'business_id',
250
                         'is_null' => 1,
255
                         'is_null' => 1,
251
-                    ]
256
+                    ],
252
                 ];
257
                 ];
258
+                $name = '所属商机';
253
                 break;
259
                 break;
254
             case 6:
260
             case 6:
255
                 $field = [
261
                 $field = [
256
                     '2' => [
262
                     '2' => [
257
                         'name' => '所属合同',
263
                         'name' => '所属合同',
258
                         'field' => 'activity_type_id',
264
                         'field' => 'activity_type_id',
259
-                        'types' => 'log',
260
-                        'form_type' => 'text',
265
+                        'form_type' => 'contract_id',
261
                         'is_null' => 1,
266
                         'is_null' => 1,
262
                     ],
267
                     ],
263
                 ];
268
                 ];
269
+                $name = '所属合同';
264
                 break;
270
                 break;
265
             case 2:
271
             case 2:
266
-                $field_list = [
267
-                    '0' => [
268
-                        'name' => '跟进内容',
269
-                        'field' => 'content',
270
-                        'types' => 'log',
271
-                        'form_type' => 'text',
272
-                        'is_null' => 1,
273
-                    ],
274
-                    '1' => [
275
-                        'name' => '创建人',
276
-                        'field' => 'create_user_id',
277
-                        'types' => 'log',
278
-                        'form_type' => 'user',
279
-                        'is_null' => 1,
280
-                    ],
272
+                $field = [
281
                     '2' => [
273
                     '2' => [
282
                         'name' => '所属客户',
274
                         'name' => '所属客户',
283
                         'field' => 'activity_type_id',
275
                         'field' => 'activity_type_id',
284
-                        'types' => 'log',
285
-                        'form_type' => 'text',
276
+                        'form_type' => 'customer_id',
286
                         'is_null' => 1,
277
                         'is_null' => 1,
287
                     ],
278
                     ],
288
-                    '3' => [
289
-                        'name' => '跟进时间-例:2020-2-1',
290
-                        'field' => 'next_time',
291
-                        'types' => 'log',
292
-                        'form_type' => 'datetime',
293
-                    ],
294
-                    '4' => [
295
-                        'name' => '跟进方式',
296
-                        'field' => 'category',
297
-                        'types' => 'log',
298
-                        'form_type' => 'text',
299
-                    ],
300
-                    '5' => [
301
-                        'name' => '相关联系人',
302
-                        'field' => 'contacts_ids',
303
-                        'types' => 'log',
304
-                        'form_type' => 'text',
305
-                    ],
306
-                    '6' => [
307
-                        'name' => '相关商机',
308
-                        'field' => 'business_ids',
309
-                        'types' => 'log',
310
-                        'form_type' => 'text',
311
-                    ]
312
                 ];
279
                 ];
280
+                $name = '所属客户';
313
                 break;
281
                 break;
314
         }
282
         }
315
         $fields = [
283
         $fields = [
316
             '0' => [
284
             '0' => [
317
                 'name' => '跟进内容',
285
                 'name' => '跟进内容',
318
                 'field' => 'content',
286
                 'field' => 'content',
319
-                'types' => 'log',
320
                 'form_type' => 'text',
287
                 'form_type' => 'text',
321
                 'is_null' => 1,
288
                 'is_null' => 1,
322
             ],
289
             ],
323
             '1' => [
290
             '1' => [
324
                 'name' => '创建人',
291
                 'name' => '创建人',
325
                 'field' => 'create_user_id',
292
                 'field' => 'create_user_id',
326
-                'types' => 'log',
327
                 'form_type' => 'user',
293
                 'form_type' => 'user',
328
                 'is_null' => 1,
294
                 'is_null' => 1,
329
             ],
295
             ],
330
             '2' => [
296
             '2' => [
331
-                'name' => '所属111',
332
-                'field' => 'activity_type_id',
333
-                'types' => 'log',
334
-                'form_type' => 'text',
335
-                'is_null' => 1,
336
-            ],
337
-            '3' => [
338
                 'name' => '跟进时间-例:2020-2-1',
297
                 'name' => '跟进时间-例:2020-2-1',
339
                 'field' => 'next_time',
298
                 'field' => 'next_time',
340
-                'types' => 'log',
341
                 'form_type' => 'datetime',
299
                 'form_type' => 'datetime',
342
             ],
300
             ],
343
-            '4' => [
301
+            '3' => [
344
                 'name' => '跟进方式',
302
                 'name' => '跟进方式',
345
                 'field' => 'category',
303
                 'field' => 'category',
346
-                'types' => 'log',
347
-                'form_type' => 'text',
304
+                'form_type' => 'select',
305
+                'setting' =>
306
+                    array
307
+                    (
308
+                        0 => "见面拜访",
309
+                        1 => "电话",
310
+                        2 => "短信",
311
+                        3 => "邮件",
312
+                        4 => "微信"
313
+                    )
348
             ],
314
             ],
349
         ];
315
         ];
350
         // 导入的字段列表
316
         // 导入的字段列表
351
-        if(!empty($param['down'])){
352
-            $field_list = [
353
-                '0' => ['name' => '所属客户', 'field' => 'activity_type_name'],
317
+        if ($param['is_excel']) {
318
+            $field_lists = [
319
+                '0' => ['name' => $name, 'field' => 'activity_type_name'],
354
                 '1' => ['name' => '跟进内容', 'field' => 'content'],
320
                 '1' => ['name' => '跟进内容', 'field' => 'content'],
355
                 '2' => ['name' => '创建人', 'field' => 'create_user_name'],
321
                 '2' => ['name' => '创建人', 'field' => 'create_user_name'],
356
                 '3' => ['name' => '跟进时间', 'field' => 'create_time'],
322
                 '3' => ['name' => '跟进时间', 'field' => 'create_time'],
357
-                '4' => ['name' => '跟进方式','field' => 'category'],
358
-                '5' => ['name' => '下次联系时间', 'field' => 'next_time'],
359
-                '6' => ['name' => '相关联系人', 'field' => 'contacts_ids'],
360
-                '7' => ['name' => '相关商机', 'field' => 'business_ids'],
361
-               
323
+                '4' => ['name' => '跟进方式', 'field' => 'category'],
324
+                '5' => ['name' => '下次联系时间', 'field' => 'next_time']
362
             ];
325
             ];
363
-        }else{
364
-            if(empty($field_list)){
365
-                $field_list=array_merge($fields,$field);
326
+            if ($param['crmType'] == 2) {
327
+                $fields = [
328
+                    '6' => ['name' => '相关联系人', 'field' => 'contacts_ids'],
329
+                    '7' => ['name' => '相关商机', 'field' => 'business_ids'],];
330
+                $field_list = array_merge($field_lists, $fields);
331
+            } else {
332
+                $field_list =$field_lists;
333
+            }
334
+        } else {
335
+            $first_array = array_splice($fields, 2, 0, $field);
336
+            $field_list = $fields;
337
+            if ($param['crmType'] == 2) {
338
+                $field = [
339
+                    '5' => [
340
+                        'name' => '相关联系人',
341
+                        'field' => 'contacts_ids',
342
+                        'form_type' => 'contacts_id',
343
+                    ],
344
+                    '6' => [
345
+                        'name' => '相关商机',
346
+                        'field' => 'business_ids',
347
+                        'form_type' => 'business_id',
348
+                    ]
349
+                ];
350
+                $field_list = array_merge($field_list, $field);
366
             }
351
             }
367
         }
352
         }
368
         return $field_list;
353
         return $field_list;
369
     }
354
     }
355
+    
370
     /**
356
     /**
371
      * 导入数据
357
      * 导入数据
372
      *
358
      *
374
      * @version     1.0 版本号
360
      * @version     1.0 版本号
375
      * @since       2021/4/10 0010 16:27
361
      * @since       2021/4/10 0010 16:27
376
      */
362
      */
377
-    public function excelImport(){
363
+    public function excelImport()
364
+    {
378
         $param = $this->param;
365
         $param = $this->param;
379
-        $field_list=$this->importData($param['label']);
366
+        $userInfo = $this->userInfo;
367
+        $param['user_id'] = $userInfo['id'];
368
+        $field_list = $this->importData($param);
380
         $excelModel = new \app\admin\model\Excel();
369
         $excelModel = new \app\admin\model\Excel();
381
         $file = request()->file('file');
370
         $file = request()->file('file');
382
-        switch ($param['label']){
371
+        switch ($param['crmType']) {
383
             case 1 :
372
             case 1 :
384
-                $param['types']='crm_leads';
385
-                $param['activity_type']=1;
373
+                $param['types'] = 'crm_leads';
374
+                $param['activity_type'] = 1;
386
                 break;
375
                 break;
387
             case 3:
376
             case 3:
388
-                $param['types']='crm_contacts';
389
-                $param['activity_type']=3;
377
+                $param['types'] = 'crm_contacts';
378
+                $param['activity_type'] = 3;
390
                 break;
379
                 break;
391
             case 5:
380
             case 5:
392
-                $param['types']='crm_business';
393
-                $param['activity_type']=5;
381
+                $param['types'] = 'crm_business';
382
+                $param['activity_type'] = 5;
394
                 break;
383
                 break;
395
             case 6:
384
             case 6:
396
-                $param['types']='crm_contract';
397
-                $param['activity_type']=6;
385
+                $param['types'] = 'crm_contract';
386
+                $param['activity_type'] = 6;
398
                 break;
387
                 break;
399
             case 2:
388
             case 2:
400
-                $param['types']='crm_customer';
401
-                $param['activity_type']=2;
389
+                $param['types'] = 'crm_customer';
390
+                $param['activity_type'] = 2;
402
                 break;
391
                 break;
403
         }
392
         }
404
-        $res = $excelModel->ActivityImport($file,$field_list, $param,$this);
393
+        $res = $excelModel->ActivityImport($file, $field_list, $param, $this);
405
         if (!$res) {
394
         if (!$res) {
406
             return resultArray(['error' => $excelModel->getError()]);
395
             return resultArray(['error' => $excelModel->getError()]);
407
         }
396
         }
417
      * @version     1.0 版本号
406
      * @version     1.0 版本号
418
      * @since       2021/4/13 0013 11:32
407
      * @since       2021/4/13 0013 11:32
419
      */
408
      */
420
-    public function excelExport(){
421
-       
422
-        $activityLogic=new ActivityLogic();
423
-        $indexLogic=new \app\crm\logic\IndexLogic();
409
+    public function excelExport()
410
+    {
411
+        
412
+        $activityLogic = new ActivityLogic();
413
+        $indexLogic = new \app\crm\logic\IndexLogic();
414
+        $userInfo = $this->userInfo;
424
         $param = $this->param;
415
         $param = $this->param;
425
-        $param['action']='crm_activity';
426
-        $list=$indexLogic->activityList($param);
427
-//        $param['down']=1;
428
-        $field_list=$this->importData($param);
429
-        $data=$activityLogic->excelExport($field_list,$list);
416
+        $param['action'] = 'crm_activity';
417
+        $param['is_excel'] = 1;
418
+        $param['id'] = $userInfo['id'];
419
+        $list = $indexLogic->activityList($param);
420
+        $field_list = $this->importData($param);
421
+        $data = $activityLogic->excelExport($field_list, $list);
430
         return $data;
422
         return $data;
431
     }
423
     }
432
 }
424
 }

+ 6
- 1
application/crm/controller/Business.php Bestand weergeven

190
             if (!$data) {
190
             if (!$data) {
191
                 return resultArray(['error' => $businessModel->getError()]);
191
                 return resultArray(['error' => $businessModel->getError()]);
192
             }
192
             }
193
+            // 删除客户扩展数据
194
+            db('crm_business_data')->whereIn('business_id', $delIds)->delete();
193
             //删除跟进记录
195
             //删除跟进记录
194
             $recordModel->delDataByTypes(5, $delIds);
196
             $recordModel->delDataByTypes(5, $delIds);
195
             //删除关联附件
197
             //删除关联附件
231
                 $list[$k]['statusList'] = $businessStatusModel->getDataList($v['type_id']);
233
                 $list[$k]['statusList'] = $businessStatusModel->getDataList($v['type_id']);
232
             }
234
             }
233
             cache($key, $list, config('business_status_cache_time'));
235
             cache($key, $list, config('business_status_cache_time'));
236
+        }else{
237
+            cache($key, NULL);
234
         }
238
         }
235
         
239
         
236
         return resultArray(['data' => $list]);
240
         return resultArray(['data' => $list]);
252
         $settingModel = model('Setting');
256
         $settingModel = model('Setting');
253
         $userModel = new \app\admin\model\User();
257
         $userModel = new \app\admin\model\User();
254
         $authIds = $userModel->getUserByPer(); //权限范围的user_id
258
         $authIds = $userModel->getUserByPer(); //权限范围的user_id
255
-        
256
         if (!$param['owner_user_id']) {
259
         if (!$param['owner_user_id']) {
257
             return resultArray(['error' => '变更负责人不能为空']);
260
             return resultArray(['error' => '变更负责人不能为空']);
258
         }
261
         }
278
             }
281
             }
279
             //权限判断
282
             //权限判断
280
             if (!in_array($businessInfo['owner_user_id'], $authIds)) {
283
             if (!in_array($businessInfo['owner_user_id'], $authIds)) {
284
+                
281
                 $errorMessage[] = $businessInfo['name'] . '"转移失败,错误原因:无权限;';
285
                 $errorMessage[] = $businessInfo['name'] . '"转移失败,错误原因:无权限;';
282
                 continue;
286
                 continue;
283
             }
287
             }
284
             
288
             
285
             //团队成员
289
             //团队成员
286
             teamUserId(
290
             teamUserId(
291
+                $param,
287
                 'crm_business',
292
                 'crm_business',
288
                 $business_id,
293
                 $business_id,
289
                 $type,
294
                 $type,

+ 4
- 2
application/crm/controller/BusinessStatus.php Bestand weergeven

105
         $businessStatusModel = model('BusinessStatus');
105
         $businessStatusModel = model('BusinessStatus');
106
         $param = $this->param;
106
         $param = $this->param;
107
         $userInfo = $this->userInfo;
107
         $userInfo = $this->userInfo;
108
-
108
+        $param['user_id']=$userInfo['id'];
109
         $res = $businessStatusModel->updateDataById($param, $param['type_id']);
109
         $res = $businessStatusModel->updateDataById($param, $param['type_id']);
110
         if ($res) {
110
         if ($res) {
111
             $key = 'BI_queryCache_StatusList_Data';
111
             $key = 'BI_queryCache_StatusList_Data';
156
     {
156
     {
157
         $businessStatusModel = model('BusinessStatus');
157
         $businessStatusModel = model('BusinessStatus');
158
         $param = $this->param;
158
         $param = $this->param;
159
-        $data = $businessStatusModel->delDataById($param['id'], true);       
159
+        $userInfo=$this->userInfo;
160
+        $param['user_id']=$userInfo['id'];
161
+        $data = $businessStatusModel->delDataById($param, true);
160
         if (!$data) {
162
         if (!$data) {
161
             return resultArray(['error' => $businessStatusModel->getError()]);
163
             return resultArray(['error' => $businessStatusModel->getError()]);
162
         } 
164
         } 

+ 34
- 35
application/crm/controller/Contacts.php Bestand weergeven

175
                 $delIds[] = $v;
175
                 $delIds[] = $v;
176
             }           
176
             }           
177
         }
177
         }
178
+        $dataInfo = $contactsModel->getDataById($v);
178
         if ($delIds) {
179
         if ($delIds) {
179
             $data = $contactsModel->delDatas($delIds);
180
             $data = $contactsModel->delDatas($delIds);
180
             if (!$data) {
181
             if (!$data) {
181
                 return resultArray(['error' => $contactsModel->getError()]);
182
                 return resultArray(['error' => $contactsModel->getError()]);
182
             }
183
             }
184
+            // 删除联系人扩展数据
185
+            db('crm_contacts_data')->whereIn('contacts_id', $delIds)->delete();
183
             //删除跟进记录
186
             //删除跟进记录
184
             $recordModel->delDataByTypes(3,$delIds);
187
             $recordModel->delDataByTypes(3,$delIds);
185
             //删除关联附件
188
             //删除关联附件
188
             $actionRecordModel->delDataById(['types'=>'crm_contacts','action_id'=>$delIds]);
191
             $actionRecordModel->delDataById(['types'=>'crm_contacts','action_id'=>$delIds]);
189
             $userInfo = $this->userInfo;
192
             $userInfo = $this->userInfo;
190
             foreach ($contacts_id as $k => $v) {
193
             foreach ($contacts_id as $k => $v) {
191
-                $data = $contactsModel->getDataById($v);
192
-                RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $data['name'], '', '', '删除了联系人:' . $data['name']);
194
+               
195
+                RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $dataInfo['name'], '', '', '删除了联系人:' . $dataInfo['name']);
193
             }
196
             }
194
         }        
197
         }        
195
         if ($errorMessage) {
198
         if ($errorMessage) {
270
      */ 
273
      */ 
271
     public function excelDownload($save_path = '') 
274
     public function excelDownload($save_path = '') 
272
     {
275
     {
276
+        # 下次升级
273
         $param = $this->param;
277
         $param = $this->param;
274
         $userInfo = $this->userInfo;
278
         $userInfo = $this->userInfo;
275
         $excelModel = new \app\admin\model\Excel();
279
         $excelModel = new \app\admin\model\Excel();
276
-    
280
+
277
         // 导出的字段列表
281
         // 导出的字段列表
278
         $fieldModel = new \app\admin\model\Field();
282
         $fieldModel = new \app\admin\model\Field();
279
         $fieldParam['types'] = 'crm_contacts';
283
         $fieldParam['types'] = 'crm_contacts';
280
         $fieldParam['action'] = 'excel';
284
         $fieldParam['action'] = 'excel';
281
         $field_list = $fieldModel->field($fieldParam);
285
         $field_list = $fieldModel->field($fieldParam);
282
-        $res = $excelModel->excelImportDownload($field_list, 'crm_contacts', $save_path);
283
-        # 下次升级
284
-//        $param = $this->param;
285
-//        $userInfo = $this->userInfo;
286
-//        $excelModel = new \app\admin\model\Excel();
287
-//
288
-//        // 导出的字段列表
289
-//        $fieldModel = new \app\admin\model\Field();
290
-//        $fieldParam['types'] = 'crm_contacts';
291
-//        $fieldParam['action'] = 'excel';
292
-//        $field_list = $fieldModel->field($fieldParam);
293
-//        $array=[];
294
-//        $field=[1=>[
295
-//            'field'=>'owner_user_id',
296
-//            'types'=>'crm_contacts',
297
-//            'name'=>'负责人',
298
-//            'form_type'=>'user',
299
-//            'default_value'=>'',
300
-//            'is_unique' => 1,
301
-//            'is_null' => 1,
302
-//            'input_tips' =>'',
303
-//            'setting' => Array(),
304
-//            'is_hidden'=>0,
305
-//            'writeStatus' => 1,
306
-//            'value' => '']
307
-//        ];
308
-//        $first_array = array_splice($field_list, 0, 2);
309
-//        $array = array_merge($first_array, $field, $field_list);
310
-//        $res = $excelModel->excelImportDownload($array, 'crm_contacts', $save_path);
286
+        $array=[];
287
+        $field=[1=>[
288
+            'field'=>'owner_user_id',
289
+            'types'=>'crm_contacts',
290
+            'name'=>'负责人',
291
+            'form_type'=>'user',
292
+            'default_value'=>'',
293
+            'is_null' => 1,
294
+            'input_tips' =>'',
295
+            'setting' => Array(),
296
+            'is_hidden'=>0,
297
+            'writeStatus' => 1,
298
+            'value' => '']
299
+        ];
300
+        $first_array = array_splice($field_list, 2,0, $field);
301
+        $excelModel->excelImportDownload($field_list, 'crm_contacts', $save_path);
311
     }  
302
     }  
312
 
303
 
313
     /**
304
     /**
331
         $excelModel = new \app\admin\model\Excel();
322
         $excelModel = new \app\admin\model\Excel();
332
         // 导出的字段列表
323
         // 导出的字段列表
333
         $fieldModel = new \app\admin\model\Field();
324
         $fieldModel = new \app\admin\model\Field();
334
-        $field_list = $fieldModel->getIndexFieldConfig('crm_contacts', $userInfo['id']);
325
+        $field_list = $fieldModel->getIndexFieldConfig('crm_contacts', $userInfo['id'],'','excel');
335
         // 文件名
326
         // 文件名
336
         $file_name = '5kcrm_contacts_'.date('Ymd');
327
         $file_name = '5kcrm_contacts_'.date('Ymd');
337
 
328
 
533
         $contactsId = $this->param['contacts_id'];
524
         $contactsId = $this->param['contacts_id'];
534
 
525
 
535
         $userInfo = $this->userInfo;
526
         $userInfo = $this->userInfo;
536
-
527
+    
528
+        # 团队成员
529
+        $contacts = Db::name('crm_contacts')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contacts_id', $contactsId)->find();
530
+        $contacts['ro_user_id'] = stringToArray($contacts['ro_user_id']);
531
+        $contacts['rw_user_id'] = stringToArray($contacts['rw_user_id']);
532
+        $contacts['owner_user_id'] = [$contacts['owner_user_id']];
533
+        $teamCount = array_filter(array_unique(array_merge($contacts['ro_user_id'], $contacts['rw_user_id'], $contacts['owner_user_id'])));
534
+        
537
         # 查询联系人和商机的关联表
535
         # 查询联系人和商机的关联表
538
         $businessIds = Db::name('crm_contacts_business')->where('contacts_id', $contactsId)->column('business_id');
536
         $businessIds = Db::name('crm_contacts_business')->where('contacts_id', $contactsId)->column('business_id');
539
 
537
 
548
 
546
 
549
         $data = [
547
         $data = [
550
             'businessCount' => $businessCount,
548
             'businessCount' => $businessCount,
551
-            'fileCount'     => $fileCount
549
+            'fileCount'     => $fileCount,
550
+            'memberCount'      => count($teamCount),
552
         ];
551
         ];
553
 
552
 
554
         return resultArray(['data' => $data]);
553
         return resultArray(['data' => $data]);

+ 3
- 1
application/crm/controller/Contract.php Bestand weergeven

343
             if (!$data) {
343
             if (!$data) {
344
                 return resultArray(['error' => $contractModel->getError()]);
344
                 return resultArray(['error' => $contractModel->getError()]);
345
             }
345
             }
346
+            // 删除合同扩展数据
347
+            db('crm_contract_data')->whereIn('contract_id', $delIds)->delete();
346
             //删除跟进记录
348
             //删除跟进记录
347
             $recordModel->delDataByTypes(6,$delIds);
349
             $recordModel->delDataByTypes(6,$delIds);
348
             //删除关联附件
350
             //删除关联附件
414
 
416
 
415
             //团队成员
417
             //团队成员
416
             teamUserId(
418
             teamUserId(
419
+                $param,
417
                 'crm_contract',
420
                 'crm_contract',
418
                 $contract_id,
421
                 $contract_id,
419
                 $type,
422
                 $type,
707
         $field_list = $fieldModel->getIndexFieldConfig('crm_contract', $userInfo['id']);
710
         $field_list = $fieldModel->getIndexFieldConfig('crm_contract', $userInfo['id']);
708
         // 文件名
711
         // 文件名
709
         $file_name = '5kcrm_contract_'.date('Ymd');
712
         $file_name = '5kcrm_contract_'.date('Ymd');
710
-
711
         $model = model('Contract');
713
         $model = model('Contract');
712
         $temp_file = $param['temp_file'];
714
         $temp_file = $param['temp_file'];
713
         unset($param['temp_file']);
715
         unset($param['temp_file']);

+ 31
- 38
application/crm/controller/Customer.php Bestand weergeven

82
         $customerModel = model('Customer');
82
         $customerModel = model('Customer');
83
         $param = $this->param;
83
         $param = $this->param;
84
         $userInfo = $this->userInfo;
84
         $userInfo = $this->userInfo;
85
+        $param['user_id'] = $userInfo['id'];
85
         $param['create_user_id'] = $userInfo['id'];
86
         $param['create_user_id'] = $userInfo['id'];
86
         $param['owner_user_id'] = $userInfo['id'];
87
         $param['owner_user_id'] = $userInfo['id'];
87
         if ($res = $customerModel->createData($param)) {
88
         if ($res = $customerModel->createData($param)) {
235
             if (!$delRes) {
236
             if (!$delRes) {
236
                 return resultArray(['error' => $customerModel->getError()]);
237
                 return resultArray(['error' => $customerModel->getError()]);
237
             }
238
             }
238
-            //删除跟进记录
239
+            // 删除客户扩展数据
240
+            db('crm_customer_data')->whereIn('customer_id', $delIds)->delete();
241
+            // 删除跟进记录
239
             $recordModel->delDataByTypes(2, $delIds);
242
             $recordModel->delDataByTypes(2, $delIds);
240
-            //删除关联附件
243
+            // 删除关联附件
241
             $fileModel->delRFileByModule('crm_customer', $delIds);
244
             $fileModel->delRFileByModule('crm_customer', $delIds);
242
-            //删除关联操作记录
245
+            // 删除关联操作记录
243
             $actionRecordModel->delDataById(['types' => 'crm_customer', 'action_id' => $delIds]);
246
             $actionRecordModel->delDataById(['types' => 'crm_customer', 'action_id' => $delIds]);
244
             foreach ($dataInfo as $k => $v) {
247
             foreach ($dataInfo as $k => $v) {
245
                 RecordActionLog($userInfo['id'], 'crm_customer', 'delete', $v['name'], '', '', '删除了客户:' . $v['name']);
248
                 RecordActionLog($userInfo['id'], 'crm_customer', 'delete', $v['name'], '', '', '删除了客户:' . $v['name']);
404
         $userId = $userInfo['id'];
407
         $userId = $userInfo['id'];
405
         $customerIds = $this->param['customer_id'];
408
         $customerIds = $this->param['customer_id'];
406
         $poolId = $this->param['pool_id'];
409
         $poolId = $this->param['pool_id'];
407
-
410
+        $customerModel=new \app\crm\model\Customer();
408
         # 消息数据
411
         # 消息数据
409
         $message = [];
412
         $message = [];
410
 
413
 
429
 
432
 
430
                 continue;
433
                 continue;
431
             }
434
             }
432
-
435
+            if (!$customerModel->checkData($value)) {
436
+                $message[] = '"' . $customerData[$value]['name'] . '"放入公海失败,错误原因:无权限';
437
+                continue;
438
+            }
433
             if (isset($customerData[$value]['owner_user_id']) && empty($customerData[$value]['owner_user_id'])) {
439
             if (isset($customerData[$value]['owner_user_id']) && empty($customerData[$value]['owner_user_id'])) {
434
                 $message[] = '将客户《' . $customerData[$value]['name'] . '》放入公海失败,错误原因:已经处于公海!';
440
                 $message[] = '将客户《' . $customerData[$value]['name'] . '》放入公海失败,错误原因:已经处于公海!';
435
                 unset($customerIds[(int)$key]);
441
                 unset($customerIds[(int)$key]);
482
                 'owner_user_id' => 0,
488
                 'owner_user_id' => 0,
483
                 'into_pool_time' => time()
489
                 'into_pool_time' => time()
484
             ]);
490
             ]);
485
-
491
+          
486
             # 删除联系人的负责人
492
             # 删除联系人的负责人
487
             Db::name('crm_contacts')->whereIn('customer_id', $customerIds)->update(['owner_user_id' => 0]);
493
             Db::name('crm_contacts')->whereIn('customer_id', $customerIds)->update(['owner_user_id' => 0]);
488
-
494
+           
489
             # 将客户放入公海
495
             # 将客户放入公海
490
             Db::name('crm_customer_pool_relation')->insertAll($poolRelationData);
496
             Db::name('crm_customer_pool_relation')->insertAll($poolRelationData);
491
-
497
+            
492
             # 公海操作记录
498
             # 公海操作记录
493
             Db::name('crm_customer_pool_record')->insertAll($poolRecordData);
499
             Db::name('crm_customer_pool_record')->insertAll($poolRecordData);
494
-
500
+           
495
             # 字段操作记录
501
             # 字段操作记录
496
             Db::name('admin_action_record')->insertAll($fieldRecordData);
502
             Db::name('admin_action_record')->insertAll($fieldRecordData);
497
 
503
 
767
         $excelModel = new \app\admin\model\Excel();
773
         $excelModel = new \app\admin\model\Excel();
768
         // 导出的字段列表
774
         // 导出的字段列表
769
         $fieldModel = new \app\admin\model\Field();
775
         $fieldModel = new \app\admin\model\Field();
770
-        $field_list = $fieldModel->getIndexFieldConfig('crm_customer', $userInfo['id']);
776
+        $field_list = $fieldModel->getIndexFieldConfig('crm_customer', $userInfo['id'],'','excel');
771
         // 文件名
777
         // 文件名
772
         $file_name = '5kcrm_customer_' . date('Ymd');
778
         $file_name = '5kcrm_customer_' . date('Ymd');
773
         
779
         
796
      */
802
      */
797
     public function excelDownload($save_path = '')
803
     public function excelDownload($save_path = '')
798
     {
804
     {
805
+        # 下次升级
799
         $param = $this->param;
806
         $param = $this->param;
800
         $userInfo = $this->userInfo;
807
         $userInfo = $this->userInfo;
801
         $excelModel = new \app\admin\model\Excel();
808
         $excelModel = new \app\admin\model\Excel();
802
-    
803
         // 导入的字段列表
809
         // 导入的字段列表
804
         $fieldModel = new \app\admin\model\Field();
810
         $fieldModel = new \app\admin\model\Field();
805
         $fieldParam['types'] = 'crm_customer';
811
         $fieldParam['types'] = 'crm_customer';
806
         $fieldParam['action'] = 'excel';
812
         $fieldParam['action'] = 'excel';
807
         $field_list = $fieldModel->field($fieldParam);
813
         $field_list = $fieldModel->field($fieldParam);
814
+        $field=[1=>[
815
+           'field'=>'owner_user_id',
816
+           'types'=>'crm_customer',
817
+           'name'=>'负责人',
818
+           'form_type'=>'user',
819
+           'default_value'=>'',
820
+           'is_null' => 1,
821
+           'input_tips' =>'',
822
+           'setting' => Array(),
823
+            'is_hidden'=>0,
824
+            'writeStatus' => 1,
825
+            'value' => '']
826
+        ];
827
+        $first_array = array_splice($field_list, 2,0, $field);
808
         $excelModel->excelImportDownload($field_list, 'crm_customer', $save_path);
828
         $excelModel->excelImportDownload($field_list, 'crm_customer', $save_path);
809
-        # 下次升级
810
-//        $param = $this->param;
811
-//        $userInfo = $this->userInfo;
812
-//        $excelModel = new \app\admin\model\Excel();
813
-//
814
-//        // 导入的字段列表
815
-//        $fieldModel = new \app\admin\model\Field();
816
-//        $fieldParam['types'] = 'crm_customer';
817
-//        $fieldParam['action'] = 'excel';
818
-//        $field_list = $fieldModel->field($fieldParam);
819
-//        $field=[1=>[
820
-//           'field'=>'owner_user_id',
821
-//           'types'=>'crm_customer',
822
-//           'name'=>'负责人',
823
-//           'form_type'=>'user',
824
-//           'default_value'=>'',
825
-//           'is_unique' => 1,
826
-//           'is_null' => 1,
827
-//           'input_tips' =>'',
828
-//           'setting' => Array(),
829
-//            'is_hidden'=>0,
830
-//            'writeStatus' => 1,
831
-//            'value' => '']
832
-//        ];
833
-//        $first_array = array_splice($field_list, 2,0, $field);
834
-//        $array = array_merge($first_array, $field, $field_list);
835
-//        $excelModel->excelImportDownload($field_list, 'crm_customer', $save_path);
836
     }
829
     }
837
     
830
     
838
     
831
     

+ 141
- 106
application/crm/controller/CustomerPool.php Bestand weergeven

44
                 'export'
44
                 'export'
45
             ]
45
             ]
46
         ];
46
         ];
47
-        Hook::listen('check_auth',$action);
47
+        Hook::listen('check_auth', $action);
48
         $request = Request::instance();
48
         $request = Request::instance();
49
         $a = strtolower($request->action());
49
         $a = strtolower($request->action());
50
         if (!in_array($a, $action['permission'])) {
50
         if (!in_array($a, $action['permission'])) {
51
             parent::_initialize();
51
             parent::_initialize();
52
         }
52
         }
53
     }
53
     }
54
-
54
+    
55
     /**
55
     /**
56
      * 公海列表
56
      * 公海列表
57
      *
57
      *
58
-     * @author fanqi
59
-     * @since 2021-04-14
60
      * @return Json
58
      * @return Json
59
+     * @since 2021-04-14
60
+     * @author fanqi
61
      */
61
      */
62
     public function index()
62
     public function index()
63
     {
63
     {
64
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
64
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
65
-
65
+        
66
         $data = (new CustomerPoolLogic())->getPoolList($this->param);
66
         $data = (new CustomerPoolLogic())->getPoolList($this->param);
67
-
67
+        
68
         return resultArray(['data' => $data]);
68
         return resultArray(['data' => $data]);
69
     }
69
     }
70
-
70
+    
71
     /**
71
     /**
72
      * 详情
72
      * 详情
73
      *
73
      *
74
-     * @author fanqi
75
-     * @since 2021-04-14
76
      * @return Json
74
      * @return Json
75
+     * @since 2021-04-14
76
+     * @author fanqi
77
      */
77
      */
78
     public function read()
78
     public function read()
79
     {
79
     {
80
         if (empty($this->param['pool_id']) || empty($this->param['customer_id'])) return resultArray(['error' => '参数错误!']);
80
         if (empty($this->param['pool_id']) || empty($this->param['customer_id'])) return resultArray(['error' => '参数错误!']);
81
-
81
+        
82
         $userInfo = $this->userInfo;
82
         $userInfo = $this->userInfo;
83
         $param = $this->param;
83
         $param = $this->param;
84
         $param['user_id'] = $userInfo['id'];
84
         $param['user_id'] = $userInfo['id'];
85
-
85
+        
86
         $data = (new CustomerPoolLogic())->getPoolData($param);
86
         $data = (new CustomerPoolLogic())->getPoolData($param);
87
-
87
+        
88
         return resultArray(['data' => $data]);
88
         return resultArray(['data' => $data]);
89
     }
89
     }
90
-
90
+    
91
     /**
91
     /**
92
      * 删除公海客户
92
      * 删除公海客户
93
      *
93
      *
94
-     * @author fanqi
95
-     * @since 2021-04-15
96
      * @return Json
94
      * @return Json
95
+     * @since 2021-04-15
96
+     * @author fanqi
97
      */
97
      */
98
     public function delete()
98
     public function delete()
99
     {
99
     {
100
         if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的客户!']);
100
         if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的客户!']);
101
-
101
+        
102
         $this->param['user_id'] = $this->userInfo['id'];
102
         $this->param['user_id'] = $this->userInfo['id'];
103
-
103
+        
104
         $result = (new CustomerPoolLogic())->deletePoolCustomer($this->param);
104
         $result = (new CustomerPoolLogic())->deletePoolCustomer($this->param);
105
-
105
+        
106
         if (!empty($result)) return resultArray(['error' => $result]);
106
         if (!empty($result)) return resultArray(['error' => $result]);
107
-
107
+        
108
         return resultArray(['data' => '删除成功!']);
108
         return resultArray(['data' => '删除成功!']);
109
     }
109
     }
110
-
110
+    
111
     /**
111
     /**
112
      * 公海池列表
112
      * 公海池列表
113
      *
113
      *
114
-     * @author fanqi
115
-     * @since 2021-04-13
116
      * @return Json
114
      * @return Json
115
+     * @since 2021-04-13
116
+     * @author fanqi
117
      */
117
      */
118
     public function pondList()
118
     public function pondList()
119
     {
119
     {
120
         $data = (new CustomerPoolLogic())->getPondList(['user_id' => $this->userInfo['id'], 'structure_id' => $this->userInfo['structure_id']]);
120
         $data = (new CustomerPoolLogic())->getPondList(['user_id' => $this->userInfo['id'], 'structure_id' => $this->userInfo['structure_id']]);
121
-
121
+        
122
         return resultArray(['data' => $data]);
122
         return resultArray(['data' => $data]);
123
     }
123
     }
124
-
124
+    
125
     /**
125
     /**
126
      * 公海字段
126
      * 公海字段
127
      *
127
      *
128
-     * @author fanqi
129
-     * @since 2021-04-13
130
      * @return Json
128
      * @return Json
129
+     * @since 2021-04-13
130
+     * @author fanqi
131
      */
131
      */
132
     public function field()
132
     public function field()
133
     {
133
     {
134
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
134
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
135
-
135
+        
136
         $userInfo = $this->userInfo;
136
         $userInfo = $this->userInfo;
137
         $param = $this->param;
137
         $param = $this->param;
138
         $param['user_id'] = $userInfo['id'];
138
         $param['user_id'] = $userInfo['id'];
139
-
139
+        
140
         $data = (new CustomerPoolLogic())->getFieldList($param);
140
         $data = (new CustomerPoolLogic())->getFieldList($param);
141
-
141
+        
142
         return resultArray(['data' => $data]);
142
         return resultArray(['data' => $data]);
143
     }
143
     }
144
-
144
+    
145
     /**
145
     /**
146
      * 高级筛选字段列表
146
      * 高级筛选字段列表
147
      *
147
      *
148
-     * @author fanqi
149
-     * @since 2021-04-14
150
      * @return Json
148
      * @return Json
149
+     * @since 2021-04-14
150
+     * @author fanqi
151
      */
151
      */
152
     public function advanced()
152
     public function advanced()
153
     {
153
     {
154
         if (empty($this->param['types'])) return resultArray(['error' => '缺少模块类型!']);
154
         if (empty($this->param['types'])) return resultArray(['error' => '缺少模块类型!']);
155
-
155
+        
156
         $data = (new CustomerPoolLogic())->getAdvancedFilterFieldList($this->param);
156
         $data = (new CustomerPoolLogic())->getAdvancedFilterFieldList($this->param);
157
-
157
+        
158
         return resultArray(['data' => $data]);
158
         return resultArray(['data' => $data]);
159
     }
159
     }
160
-
160
+    
161
     /**
161
     /**
162
      * 领取公海池客户
162
      * 领取公海池客户
163
      *
163
      *
164
-     * @author fanqi
165
-     * @since 2021-04-15
166
      * @return Json
164
      * @return Json
165
+     * @since 2021-04-15
166
+     * @author fanqi
167
      */
167
      */
168
     public function receive()
168
     public function receive()
169
     {
169
     {
170
         if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要领取的公海客户!']);
170
         if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要领取的公海客户!']);
171
-
171
+        
172
         $param = $this->param;
172
         $param = $this->param;
173
         $param['user_id'] = $this->userInfo['id'];
173
         $param['user_id'] = $this->userInfo['id'];
174
-
174
+        
175
         $result = (new CustomerPoolLogic())->receiveCustomers($param);
175
         $result = (new CustomerPoolLogic())->receiveCustomers($param);
176
-
176
+        
177
         if (!empty($result)) return resultArray(['error' => $result]);
177
         if (!empty($result)) return resultArray(['error' => $result]);
178
-
178
+        
179
         return resultArray(['data' => '领取成功!']);
179
         return resultArray(['data' => '领取成功!']);
180
     }
180
     }
181
-
181
+    
182
     /**
182
     /**
183
      * 分配公海客户
183
      * 分配公海客户
184
      *
184
      *
185
-     * @author fanqi
186
-     * @since 2021-04-15
187
      * @return Json
185
      * @return Json
186
+     * @since 2021-04-15
187
+     * @author fanqi
188
      */
188
      */
189
     public function distribute()
189
     public function distribute()
190
     {
190
     {
191
         if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要分配的公海客户!']);
191
         if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要分配的公海客户!']);
192
         if (empty($this->param['user_id'])) return resultArray(['error' => '请选择要分配的员工!']);
192
         if (empty($this->param['user_id'])) return resultArray(['error' => '请选择要分配的员工!']);
193
-
193
+        
194
         $result = (new CustomerPoolLogic())->distributeCustomer($this->param);
194
         $result = (new CustomerPoolLogic())->distributeCustomer($this->param);
195
-
195
+        
196
         if (!empty($result)) return resultArray(['error' => $result]);
196
         if (!empty($result)) return resultArray(['error' => $result]);
197
-
197
+        
198
         return resultArray(['data' => '分配成功!']);
198
         return resultArray(['data' => '分配成功!']);
199
     }
199
     }
200
-
200
+    
201
     // 公海客户导入模板下载
201
     // 公海客户导入模板下载
202
-    public function excelDownload($save_path='')
202
+    public function excelDownload($save_path = '')
203
     {
203
     {
204
         $excelModel = new \app\admin\model\Excel();
204
         $excelModel = new \app\admin\model\Excel();
205
-        $param=$this->param;
206
-        $field_list=$this->fieldsData($param);
207
-        $excelModel->excelImportDownload($field_list, 'crm_customer', $save_path);
205
+        $param = $this->param;
206
+        $field_list = $this->fieldsData($param);
207
+        $excelModel->excelImportDownload($field_list, 'crm_pool', $save_path);
208
     }
208
     }
209
-
209
+    
210
     // 导入
210
     // 导入
211
     public function import()
211
     public function import()
212
     {
212
     {
213
+        
213
         $param = $this->param;
214
         $param = $this->param;
214
         $userInfo = $this->userInfo;
215
         $userInfo = $this->userInfo;
215
         $excelModel = new \app\admin\model\Excel();
216
         $excelModel = new \app\admin\model\Excel();
216
         $param['create_user_id'] = $userInfo['id'];
217
         $param['create_user_id'] = $userInfo['id'];
217
-        $param['owner_user_id'] = $userInfo['id'];
218
         $param['deal_time'] = time();
218
         $param['deal_time'] = time();
219
         $param['types'] = 'crm_customer';
219
         $param['types'] = 'crm_customer';
220
+        $param['deal_status'] = '未成交';
220
         $file = request()->file('file');
221
         $file = request()->file('file');
221
         // $res = $excelModel->importExcel($file, $param, $this);
222
         // $res = $excelModel->importExcel($file, $param, $this);
222
         $res = $excelModel->batchImportData($file, $param, $this);
223
         $res = $excelModel->batchImportData($file, $param, $this);
223
-        RecordActionLog($userInfo['id'],'crm_customer','excel','导入公海客户','','','导入公海客户');
224
+        RecordActionLog($userInfo['id'], 'crm_customer', 'excel', '导入公海客户', '', '', '导入公海客户');
224
         return resultArray(['data' => $excelModel->getError()]);
225
         return resultArray(['data' => $excelModel->getError()]);
225
     }
226
     }
226
-
227
+    
227
     // 导出
228
     // 导出
228
     public function export()
229
     public function export()
229
     {
230
     {
230
         $param = $this->param;
231
         $param = $this->param;
231
         $userInfo = $this->userInfo;
232
         $userInfo = $this->userInfo;
232
-        $action_name='导出全部';
233
+        $action_name = '导出全部';
233
         if ($param['customer_id']) {
234
         if ($param['customer_id']) {
234
-            $action_name='导出选中';
235
+            $action_name = '导出选中';
235
         }
236
         }
236
         $param['is_excel'] = 1;
237
         $param['is_excel'] = 1;
237
         $excelModel = new \app\admin\model\Excel();
238
         $excelModel = new \app\admin\model\Excel();
238
         // 导出的字段列表
239
         // 导出的字段列表
239
-        $fieldModel = new \app\admin\model\Field();
240
-        $field_list=$this->fieldsData($param);
241
-        $field=[
242
-            1=>[
243
-            'field'=>'before_owner_user_name',
244
-            'types'=>'crm_customer',
245
-            'name'=>'前负责人',
246
-            ],
247
-            2=>[
248
-                'field'=>'into_pool_time',
249
-                'types'=>'crm_customer',
250
-                'name'=>'进入公海时间',
251
-            ]
252
-        ];
253
-        $field_list=array_merge($field_list,$field);
240
+        $field_list = $this->fieldsData($param);
254
         // 文件名
241
         // 文件名
255
         $file_name = '5kcrm_customer_' . date('Ymd');
242
         $file_name = '5kcrm_customer_' . date('Ymd');
256
         $model = model('Customer');
243
         $model = model('Customer');
259
         $page = $param['page'] ?: 1;
246
         $page = $param['page'] ?: 1;
260
         unset($param['page']);
247
         unset($param['page']);
261
         unset($param['export_queue_index']);
248
         unset($param['export_queue_index']);
262
-      
249
+//        p($field_list);
263
         return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
250
         return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
264
             $param['page'] = $page;
251
             $param['page'] = $page;
265
             $param['limit'] = $limit;
252
             $param['limit'] = $limit;
267
             $data['list'] = $model->exportHandle($data['list'], $field_list, 'customer');
254
             $data['list'] = $model->exportHandle($data['list'], $field_list, 'customer');
268
             return $data;
255
             return $data;
269
         });
256
         });
270
-        RecordActionLog($userInfo['id'],'crm_customer','excelexport',$action_name,'','','导出客户');
257
+        RecordActionLog($userInfo['id'], 'crm_customer', 'excelexport', $action_name, '', '', '导出客户');
271
         return resultArray(['error' => 'error']);
258
         return resultArray(['error' => 'error']);
272
     }
259
     }
273
-
260
+    
274
     /**
261
     /**
275
      * 公海权限
262
      * 公海权限
276
      *
263
      *
277
-     * @author fanqi
278
-     * @since 2021-04-14
279
      * @return Json
264
      * @return Json
265
+     * @since 2021-04-14
266
+     * @author fanqi
280
      */
267
      */
281
     public function authority()
268
     public function authority()
282
     {
269
     {
283
         $param = $this->param;
270
         $param = $this->param;
284
         $param['user_id'] = $this->userInfo['id'];
271
         $param['user_id'] = $this->userInfo['id'];
285
         $param['structure_id'] = $this->userInfo['structure_id'];
272
         $param['structure_id'] = $this->userInfo['structure_id'];
286
-
273
+        
287
         $data = (new CustomerPoolLogic())->getAuthorityData($param);
274
         $data = (new CustomerPoolLogic())->getAuthorityData($param);
288
-
275
+        
289
         return resultArray(['data' => $data]);
276
         return resultArray(['data' => $data]);
290
     }
277
     }
291
-
278
+    
292
     /**
279
     /**
293
      * 公海字段样式
280
      * 公海字段样式
294
      *
281
      *
295
-     * @author fanqi
296
-     * @since 2021-04-22
297
      * @return Json
282
      * @return Json
283
+     * @since 2021-04-22
284
+     * @author fanqi
298
      */
285
      */
299
     public function fieldConfig()
286
     public function fieldConfig()
300
     {
287
     {
301
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
288
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
302
-
289
+        
303
         $param = $this->param;
290
         $param = $this->param;
304
         $userInfo = $this->userInfo;
291
         $userInfo = $this->userInfo;
305
         $param['user_id'] = $userInfo['id'];
292
         $param['user_id'] = $userInfo['id'];
306
-
293
+        
307
         $data = (new CustomerPoolLogic())->getFieldConfigIndex($param);
294
         $data = (new CustomerPoolLogic())->getFieldConfigIndex($param);
308
-
295
+        
309
         return resultArray(['data' => $data]);
296
         return resultArray(['data' => $data]);
310
     }
297
     }
311
-
298
+    
312
     /**
299
     /**
313
      * 设置公海字段宽度
300
      * 设置公海字段宽度
314
      *
301
      *
315
-     * @author fanqi
316
-     * @since 2021-04-22
317
      * @return Json
302
      * @return Json
303
+     * @since 2021-04-22
304
+     * @author fanqi
318
      */
305
      */
319
     public function setFieldWidth()
306
     public function setFieldWidth()
320
     {
307
     {
321
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
308
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
322
         if (empty($this->param['field'])) return resultArray(['error' => '缺少字段名称!']);
309
         if (empty($this->param['field'])) return resultArray(['error' => '缺少字段名称!']);
323
         if (empty($this->param['width'])) return resultArray(['error' => '缺少宽度值!']);
310
         if (empty($this->param['width'])) return resultArray(['error' => '缺少宽度值!']);
324
-
311
+        
325
         $param = $this->param;
312
         $param = $this->param;
326
         $userInfo = $this->userInfo;
313
         $userInfo = $this->userInfo;
327
         $param['user_id'] = $userInfo['id'];
314
         $param['user_id'] = $userInfo['id'];
328
-
315
+        
329
         (new CustomerPoolLogic())->setFieldWidth($param);
316
         (new CustomerPoolLogic())->setFieldWidth($param);
330
-
317
+        
331
         return resultArray(['data' => '操作成功!']);
318
         return resultArray(['data' => '操作成功!']);
332
     }
319
     }
333
-
320
+    
334
     /**
321
     /**
335
      * 设置公海字段样式
322
      * 设置公海字段样式
336
      *
323
      *
337
-     * @author fanqi
338
-     * @since 2021-04-22
339
      * @return Json
324
      * @return Json
325
+     * @since 2021-04-22
326
+     * @author fanqi
340
      */
327
      */
341
     public function setFieldConfig()
328
     public function setFieldConfig()
342
     {
329
     {
343
         if (empty($this->param['pool_id'])) return resultArray(['缺少公海ID!']);
330
         if (empty($this->param['pool_id'])) return resultArray(['缺少公海ID!']);
344
         if (empty($this->param['value']) && empty($this->param['hide_value'])) return resultArray(['error' => '字段参数错误!']);
331
         if (empty($this->param['value']) && empty($this->param['hide_value'])) return resultArray(['error' => '字段参数错误!']);
345
-
332
+        
346
         $param = $this->param;
333
         $param = $this->param;
347
         $userInfo = $this->userInfo;
334
         $userInfo = $this->userInfo;
348
         $param['user_id'] = $userInfo['id'];
335
         $param['user_id'] = $userInfo['id'];
349
-
336
+        
350
         (new CustomerPoolLogic())->setFieldConfig($param);
337
         (new CustomerPoolLogic())->setFieldConfig($param);
351
-
338
+        
352
         return resultArray(['data' => '操作成功!']);
339
         return resultArray(['data' => '操作成功!']);
353
     }
340
     }
354
-    public function fieldsData($param){
355
-        $pool_list=db('crm_customer_pool_field_setting')->where(['pool_id'=>$param['pool_id'],'is_hidden'=>0])->select();
356
-        $fieldModel = new \app\admin\model\Field();
341
+    
342
+    /**
343
+     * 导入模板
344
+     * @param $param
345
+     *
346
+     * @author      alvin guogaobo
347
+     * @version     1.0 版本号
348
+     * @since       2021/5/17 0017 11:34
349
+     */
350
+    public function fieldsData($param)
351
+    {
352
+        $where=['pool_id' => $param['pool_id'], 'is_hidden' => 0,
353
+            'field_name' => ['not in', ['deal_status','create_user_id']]];
354
+        if($param['is_excel']==1){
355
+            $where=['pool_id' => $param['pool_id'], 'is_hidden' => 0,
356
+                'field_name' => ['not in', ['deal_status']]];
357
+        }
358
+        $pool_list = db('crm_customer_pool_field_setting')->where($where)->field('field_name as field,form_type,name')->select();
357
         $fieldParam['types'] = 'crm_customer';
359
         $fieldParam['types'] = 'crm_customer';
358
         $fieldParam['action'] = 'excel';
360
         $fieldParam['action'] = 'excel';
359
-        $merge_list = $fieldModel->field($fieldParam);
360
-        $field_list=array_intersect($merge_list,$pool_list);
361
-        return $field_list;
362
-        
361
+        $setting = [];
362
+        $list=[];
363
+        foreach ($pool_list as $k => &$v) {
364
+            switch ($v['field']) {
365
+                case 'address':
366
+                    if($param['is_excel']!=1){
367
+                        $v['field'] = 'customer_address';
368
+                        $v['form_type'] = 'map_address';
369
+                        $list[]=$v;
370
+                        unset($pool_list[$k]);
371
+                    }
372
+                    break;
373
+                case 'detail_address':
374
+                    unset($pool_list[$k]);
375
+                    break;
376
+                case ($v['form_type'] == 'select') || ($v['form_type'] == 'checkbox') :
377
+                    $set= db('admin_field')->where(['types' => 'crm_customer', 'field' => $v['field']])->find();
378
+                    $pool_list[$k]['setting'] = explode(chr(10), $set['setting']);
379
+                    break;
380
+                default :
381
+                    if($param['is_excel']!=1){
382
+                        $pool_list[$k]['setting'] = [];
383
+                    }
384
+                    break;
385
+            }
386
+//            if($param['is_excel']==1){
387
+//                foreach ( $pool_list as &$v){
388
+//                    if($v['field']=='create_user_id'){
389
+//                        $v['field'] = 'create_user_name';
390
+//                    }elseif($v['field']=='before_owner_user_id'){
391
+//                        $v['field'] = 'create_user_name';
392
+//                    }
393
+//                }
394
+//            }
395
+        }
396
+        $pool_list=array_merge($pool_list,$list);
397
+        return $pool_list;
363
     }
398
     }
364
-}
399
+}

+ 8
- 5
application/crm/controller/Index.php Bestand weergeven

46
                 'autonumberstatus',
46
                 'autonumberstatus',
47
                 'dashboard',
47
                 'dashboard',
48
                 'updatedashboard',
48
                 'updatedashboard',
49
-                'activitylist'
49
+                'activitylist',
50
             ]
50
             ]
51
         ];
51
         ];
52
         Hook::listen('check_auth', $action);
52
         Hook::listen('check_auth', $action);
316
             $achievement=Db::name('crm_achievement')->where($userWhere)->select();
316
             $achievement=Db::name('crm_achievement')->where($userWhere)->select();
317
             $data_time=date('m',strtotime($val['type']));
317
             $data_time=date('m',strtotime($val['type']));
318
             $num='';
318
             $num='';
319
-            foreach ($achievement as $val){
320
-                $num+=(int)$val[$this->monthName[$data_time]];
319
+            if($achievement){
320
+                foreach ($achievement as $val){
321
+                    $num+=(int)$val[$this->monthName[$data_time]];
321
                     $item['achievement']=$num;
322
                     $item['achievement']=$num;
323
+                }
324
+            }else{
325
+                $item['achievement']=0;
322
             }
326
             }
323
             $list[] = $item;
327
             $list[] = $item;
324
         }
328
         }
667
      */
671
      */
668
     public function ranking()
672
     public function ranking()
669
     {
673
     {
670
-        // Db::query('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;');
671
         $param = $this->param;
674
         $param = $this->param;
672
         $userInfo = $this->userInfo;
675
         $userInfo = $this->userInfo;
673
         $param['user_id'] = $param['user_id']?:$userInfo['id'];
676
         $param['user_id'] = $param['user_id']?:$userInfo['id'];
691
     }
694
     }
692
 
695
 
693
     /**
696
     /**
694
-     * 销售漏斗点击查看赢单输单
697
+     * 销售漏斗点击查看
695
      */
698
      */
696
     public function businessList()
699
     public function businessList()
697
     {
700
     {

+ 430
- 147
application/crm/controller/Invoice.php Bestand weergeven

11
 use app\admin\controller\ApiCommon;
11
 use app\admin\controller\ApiCommon;
12
 use app\admin\model\Message;
12
 use app\admin\model\Message;
13
 use app\admin\model\User;
13
 use app\admin\model\User;
14
+use app\admin\traits\FieldVerificationTrait;
14
 use app\crm\logic\InvoiceLogic;
15
 use app\crm\logic\InvoiceLogic;
15
 use app\crm\model\NumberSequence;
16
 use app\crm\model\NumberSequence;
16
 use app\crm\traits\AutoNumberTrait;
17
 use app\crm\traits\AutoNumberTrait;
20
 
21
 
21
 class Invoice extends ApiCommon
22
 class Invoice extends ApiCommon
22
 {
23
 {
23
-    use AutoNumberTrait;
24
-
24
+    use AutoNumberTrait, FieldVerificationTrait;
25
+    
25
     /**
26
     /**
26
      * 用于判断权限
27
      * 用于判断权限
27
      * @permission 无限制
28
      * @permission 无限制
32
     {
33
     {
33
         $action = [
34
         $action = [
34
             'permission' => [],
35
             'permission' => [],
35
-            'allow'      => ['check', 'revokecheck', 'count', 'read']
36
+            'allow' => ['check', 'revokecheck', 'count', 'read']
36
         ];
37
         ];
37
-        Hook::listen('check_auth',$action);
38
+        Hook::listen('check_auth', $action);
38
         $request = Request::instance();
39
         $request = Request::instance();
39
         $a = strtolower($request->action());
40
         $a = strtolower($request->action());
40
         if (!in_array($a, $action['permission'])) {
41
         if (!in_array($a, $action['permission'])) {
41
             parent::_initialize();
42
             parent::_initialize();
42
         }
43
         }
43
     }
44
     }
44
-
45
+    
45
     /**
46
     /**
46
      * 列表
47
      * 列表
47
      *
48
      *
53
     {
54
     {
54
         $param = $this->param;
55
         $param = $this->param;
55
         $param['user_id'] = $this->userInfo['id'];
56
         $param['user_id'] = $this->userInfo['id'];
56
-
57
-        $data = $invoiceLogic->index($param, true);
58
-
57
+        
58
+        $data = $invoiceLogic->index($param);
59
+        
59
         return resultArray(['data' => $data]);
60
         return resultArray(['data' => $data]);
60
     }
61
     }
61
-
62
+    
62
     /**
63
     /**
63
      * 创建
64
      * 创建
64
      *
65
      *
70
      */
71
      */
71
     public function save(InvoiceLogic $invoiceLogic)
72
     public function save(InvoiceLogic $invoiceLogic)
72
     {
73
     {
73
-        if (empty($this->param['customer_id']))          return resultArray(['error' => '请选择客户!']);
74
-        if (empty($this->param['contract_id']))          return resultArray(['error' => '请选择合同!']);
75
-        if (empty($this->param['invoice_money']))        return resultArray(['error' => '请填写开票金额!']);
76
-        if (empty($this->param['invoice_type']))         return resultArray(['error' => '请选择开票类型!']);
77
-        if (empty($this->param['title_type']))           return resultArray(['error' => '请选择抬头类型!']);
78
-
79
-        $param         = $this->param;
80
-        $userId        = $this->userInfo['id'];
74
+        if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择客户!']);
75
+        if (empty($this->param['contract_id'])) return resultArray(['error' => '请选择合同!']);
76
+        if (empty($this->param['invoice_money'])) return resultArray(['error' => '请填写开票金额!']);
77
+        if (empty($this->param['invoice_type'])) return resultArray(['error' => '请选择开票类型!']);
78
+        if (empty($this->param['title_type'])) return resultArray(['error' => '请选择抬头类型!']);
79
+        
80
+        $param = $this->param;
81
+        $userId = $this->userInfo['id'];
81
         # 审批是否停用
82
         # 审批是否停用
82
         $examineStatus = $param['examineStatus'];
83
         $examineStatus = $param['examineStatus'];
83
         # 删除无用参数
84
         # 删除无用参数
87
         unset($param['contract_number']);
88
         unset($param['contract_number']);
88
         # 设置创建人负责人ID
89
         # 设置创建人负责人ID
89
         $param['create_user_id'] = $userId;
90
         $param['create_user_id'] = $userId;
90
-        $param['owner_user_id']  = $userId;
91
+        $param['owner_user_id'] = $userId;
91
         # 创建更新日期
92
         # 创建更新日期
92
-        $param['create_time']    = time();
93
-        $param['update_time']    = time();
94
-
93
+        $param['create_time'] = time();
94
+        $param['update_time'] = time();
95
+        
95
         # 自动设置发票编号
96
         # 自动设置发票编号
96
         $numberInfo = [];
97
         $numberInfo = [];
97
         if (empty($param['invoice_apple_number'])) {
98
         if (empty($param['invoice_apple_number'])) {
103
         if ($invoiceLogic->getInvoiceId(['invoice_apple_number' => $param['invoice_apple_number']])) {
104
         if ($invoiceLogic->getInvoiceId(['invoice_apple_number' => $param['invoice_apple_number']])) {
104
             return resultArray(['error' => '发票编号重复!']);
105
             return resultArray(['error' => '发票编号重复!']);
105
         }
106
         }
106
-
107
+        
107
         if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) {
108
         if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) {
108
             $examineStepModel = new \app\admin\model\ExamineStep();
109
             $examineStepModel = new \app\admin\model\ExamineStep();
109
             # 审核判断(是否有符合条件的审批流)
110
             # 审核判断(是否有符合条件的审批流)
121
             if ($examineFlowData['config'] == 1) {
122
             if ($examineFlowData['config'] == 1) {
122
                 # 固定审批流
123
                 # 固定审批流
123
                 $nextStepData = $examineStepModel->nextStepUser($userId, $examineFlowData['flow_id'], 'crm_invoice', 0, 0, 0);
124
                 $nextStepData = $examineStepModel->nextStepUser($userId, $examineFlowData['flow_id'], 'crm_invoice', 0, 0, 0);
124
-                $next_user_ids = arrayToString($nextStepData['next_user_ids']) ? : '';
125
-                $check_user_id = $next_user_ids ? : [];
125
+                $next_user_ids = arrayToString($nextStepData['next_user_ids']) ?: '';
126
+                $check_user_id = $next_user_ids ?: [];
126
                 $param['order_id'] = 1;
127
                 $param['order_id'] = 1;
127
             } else {
128
             } else {
128
                 # 授权审批流
129
                 # 授权审批流
129
-                $check_user_id = $param['check_user_id'] ? ','.$param['check_user_id'].',' : '';
130
+                $check_user_id = $param['check_user_id'] ? ',' . $param['check_user_id'] . ',' : '';
130
             }
131
             }
131
             if (!$check_user_id) {
132
             if (!$check_user_id) {
132
                 return resultArray(['error' => '无可用审批人,请联系管理员']);
133
                 return resultArray(['error' => '无可用审批人,请联系管理员']);
133
             }
134
             }
134
-            $param['check_user_id'] = is_array($check_user_id) ? ','.implode(',',$check_user_id).',' : $check_user_id;
135
+            $param['check_user_id'] = is_array($check_user_id) ? ',' . implode(',', $check_user_id) . ',' : $check_user_id;
135
         } else {
136
         } else {
136
             # 审批流停用,将状态改为审核通过
137
             # 审批流停用,将状态改为审核通过
137
             $param['check_status'] = 2;
138
             $param['check_status'] = 2;
138
         }
139
         }
139
 
140
 
141
+        // 数据验证
142
+//        $validateResult = $this->fieldDataValidate($param, 'crm_invoice', $userId);
143
+//        if (!empty($validateResult)) {
144
+//            $this->error = $validateResult;
145
+//            return false;
146
+//        }
147
+
148
+        // 发票扩展表数据
149
+        $invoiceData = [];
150
+
151
+        $fieldModel = new \app\admin\model\Field();
152
+
153
+        // 处理部门、员工、附件、多选类型字段
154
+        $arrFieldAtt = $fieldModel->getArrayField('crm_invoice');
155
+        foreach ($arrFieldAtt as $k=>$v) {
156
+            $param[$v] = arrayToString($param[$v]);
157
+        }
158
+
159
+        // 处理日期(date)类型
160
+        $dateField = $fieldModel->getFieldByFormType('crm_invoice', 'date');
161
+        if (!empty($dateField)) {
162
+            foreach ($param AS $key => $value) {
163
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
164
+            }
165
+        }
166
+
167
+        // 处理手写签名类型
168
+        $handwritingField = $fieldModel->getFieldByFormType('crm_invoice', 'handwriting_sign');
169
+        if (!empty($handwritingField)) {
170
+            foreach ($param AS $key => $value) {
171
+                if (in_array($key, $handwritingField)) {
172
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
173
+                }
174
+            }
175
+        }
176
+
177
+        // 处理地址、定位、日期区间、明细表格类型字段
178
+        $positionField     = $fieldModel->getFieldByFormType('crm_invoice', 'position');
179
+        $locationField     = $fieldModel->getFieldByFormType('crm_invoice', 'location');
180
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_invoice', 'date_interval');
181
+        $detailTableField  = $fieldModel->getFieldByFormType('crm_invoice', 'detail_table');
182
+        foreach ($param AS $key => $value) {
183
+            // 处理地址类型字段数据
184
+            if (in_array($key, $positionField)) {
185
+                if (!empty($value)) {
186
+                    $invoiceData[] = [
187
+                        'field'       => $key,
188
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
189
+                        'create_time' => time()
190
+                    ];
191
+                    $positionNames = array_column($value, 'name');
192
+                    $param[$key] = implode(',', $positionNames);
193
+                } else {
194
+                    $param[$key] = '';
195
+                }
196
+            }
197
+            // 处理定位类型字段数据
198
+            if (in_array($key, $locationField)) {
199
+                if (!empty($value)) {
200
+                    $invoiceData[] = [
201
+                        'field'       => $key,
202
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
203
+                        'create_time' => time()
204
+                    ];
205
+                    $param[$key] = $value['address'];
206
+                } else {
207
+                    $param[$key] = '';
208
+                }
209
+            }
210
+            // 处理日期区间类型字段数据
211
+            if (in_array($key, $dateIntervalField)) {
212
+                if (!empty($value)) {
213
+                    $invoiceData[] = [
214
+                        'field'       => $key,
215
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
216
+                        'create_time' => time()
217
+                    ];
218
+                    $param[$key] = implode('_', $value);
219
+                } else {
220
+                    $param[$key] = '';
221
+                }
222
+            }
223
+            // 处理明细表格类型字段数据
224
+            if (in_array($key, $detailTableField)) {
225
+                if (!empty($value)) {
226
+                    $invoiceData[] = [
227
+                        'field'       => $key,
228
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
229
+                        'create_time' => time()
230
+                    ];
231
+                    $param[$key] = $key;
232
+                } else {
233
+                    $param[$key] = '';
234
+                }
235
+            }
236
+        }
237
+
238
+        
140
         if (!$invoice_id = $invoiceLogic->save($param)) {
239
         if (!$invoice_id = $invoiceLogic->save($param)) {
141
             return resultArray(['error' => '创建失败!']);
240
             return resultArray(['error' => '创建失败!']);
142
         }
241
         }
144
         (new Message())->send(
243
         (new Message())->send(
145
             Message::INVOICE_TO_DO,
244
             Message::INVOICE_TO_DO,
146
             [
245
             [
147
-                'title'     => $param['invoice_apple_number'],
246
+                'title' => $param['invoice_apple_number'],
148
                 'action_id' => $invoice_id
247
                 'action_id' => $invoice_id
149
             ],
248
             ],
150
             $send_user_id
249
             $send_user_id
152
         # 更新crm_number_sequence表中的last_date、create_time字段
251
         # 更新crm_number_sequence表中的last_date、create_time字段
153
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
252
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
154
         updateActionLog($param['create_user_id'], 'crm_invoice', $invoice_id, '', '', '创建了发票');
253
         updateActionLog($param['create_user_id'], 'crm_invoice', $invoice_id, '', '', '创建了发票');
155
-        RecordActionLog($param['create_user_id'],'crm_invoice','save',$param['invoice_apple_number'],'','','新增了发票'.$param['invoice_apple_number']);
156
-
254
+        RecordActionLog($param['create_user_id'], 'crm_invoice', 'save', $param['invoice_apple_number'], '', '', '新增了发票' . $param['invoice_apple_number']);
255
+        
157
         # 创建待办事项的关联数据
256
         # 创建待办事项的关联数据
158
         $checkUserIds = db('crm_invoice')->where('invoice_id', $invoice_id)->value('check_user_id');
257
         $checkUserIds = db('crm_invoice')->where('invoice_id', $invoice_id)->value('check_user_id');
159
         $checkUserIdArray = stringToArray($checkUserIds);
258
         $checkUserIdArray = stringToArray($checkUserIds);
160
         $dealtData = [];
259
         $dealtData = [];
161
-        foreach ($checkUserIdArray AS $kk => $vv) {
260
+        foreach ($checkUserIdArray as $kk => $vv) {
162
             $dealtData[] = [
261
             $dealtData[] = [
163
-                'types'    => 'crm_invoice',
262
+                'types' => 'crm_invoice',
164
                 'types_id' => $invoice_id,
263
                 'types_id' => $invoice_id,
165
-                'user_id'  => $vv
264
+                'user_id' => $vv
166
             ];
265
             ];
167
         }
266
         }
168
         if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
267
         if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
169
 
268
 
269
+        // 添加发票扩展数据
270
+        array_walk($invoiceData, function (&$val) use ($invoice_id) {
271
+            $val['invoice_id'] = $invoice_id;
272
+        });
273
+        db('crm_invoice_data')->insertAll($invoiceData);
274
+        
170
         return resultArray(['data' => '创建成功!']);
275
         return resultArray(['data' => '创建成功!']);
171
     }
276
     }
172
-
277
+    
173
     /**
278
     /**
174
      * 详情
279
      * 详情
175
      *
280
      *
183
     public function read(InvoiceLogic $invoiceLogic)
288
     public function read(InvoiceLogic $invoiceLogic)
184
     {
289
     {
185
         $invoiceId = $this->param['id'];
290
         $invoiceId = $this->param['id'];
186
-        $isUpdate  = !empty($this->param['is_update']) ? $this->param['is_update'] : 0;
187
-        $userInfo  = $this->userInfo;
188
-
291
+        $isUpdate = !empty($this->param['is_update']) ? $this->param['is_update'] : 0;
292
+        $userInfo = $this->userInfo;
293
+        
189
         $data = $invoiceLogic->read($invoiceId, $isUpdate);
294
         $data = $invoiceLogic->read($invoiceId, $isUpdate);
190
         $readStatus = false;
295
         $readStatus = false;
191
-
296
+        
192
         # 角色权限
297
         # 角色权限
193
         $authArray = db('admin_access')->alias('access')
298
         $authArray = db('admin_access')->alias('access')
194
             ->join('__ADMIN_GROUP__ group', 'group.id = access.group_id', 'left')
299
             ->join('__ADMIN_GROUP__ group', 'group.id = access.group_id', 'left')
195
             ->where('access.user_id', $userInfo['id'])->column('group.rules');
300
             ->where('access.user_id', $userInfo['id'])->column('group.rules');
196
-
301
+        
197
         # 详情权限ID
302
         # 详情权限ID
198
-        $invoiceAuthId     = db('admin_rule')->where(['types' => 2, 'name' => 'invoice', 'level' => 2])->value('id');
303
+        $invoiceAuthId = db('admin_rule')->where(['types' => 2, 'name' => 'invoice', 'level' => 2])->value('id');
199
         $invoiceReadAuthId = db('admin_rule')->where(['types' => 2, 'name' => 'read', 'level' => 3, 'pid' => $invoiceAuthId])->value('id');
304
         $invoiceReadAuthId = db('admin_rule')->where(['types' => 2, 'name' => 'read', 'level' => 3, 'pid' => $invoiceAuthId])->value('id');
200
-
201
-        foreach ($authArray AS $key => $value) {
305
+        
306
+        foreach ($authArray as $key => $value) {
202
             if (!empty($value) && in_array($invoiceReadAuthId, stringToArray($value))) $readStatus = true;
307
             if (!empty($value) && in_array($invoiceReadAuthId, stringToArray($value))) $readStatus = true;
203
         }
308
         }
204
-
309
+        
205
         if (!isSuperAdministrators($userInfo['id']) && $readStatus === false) {
310
         if (!isSuperAdministrators($userInfo['id']) && $readStatus === false) {
206
             $authData['dataAuth'] = (int)0;
311
             $authData['dataAuth'] = (int)0;
207
             return resultArray(['data' => $authData]);
312
             return resultArray(['data' => $authData]);
208
         }
313
         }
209
-
314
+        
210
         return resultArray(['data' => $data]);
315
         return resultArray(['data' => $data]);
211
     }
316
     }
212
-
317
+    
213
     /**
318
     /**
214
      * 编辑
319
      * 编辑
215
      *
320
      *
222
     public function update(InvoiceLogic $invoiceLogic)
327
     public function update(InvoiceLogic $invoiceLogic)
223
     {
328
     {
224
         $param = $this->param;
329
         $param = $this->param;
225
-        if (empty($param['invoice_id']))           return resultArray(['error' => '缺少发票ID!']);
226
-        if (empty($param['invoice_type']))         return resultArray(['error' => '请选择开票类型!']);
227
-        if (empty($param['title_type']))           return resultArray(['error' => '请选择抬头类型!']);
330
+        if (empty($param['invoice_id'])) return resultArray(['error' => '缺少发票ID!']);
331
+        if (empty($param['invoice_type'])) return resultArray(['error' => '请选择开票类型!']);
332
+        if (empty($param['title_type'])) return resultArray(['error' => '请选择抬头类型!']);
228
         $userId = $this->userInfo['id'];
333
         $userId = $this->userInfo['id'];
229
-        $dataInfo = $this->get($param['invoice_id']);
334
+        $dataInfo = db('crm_invoice')->where('invoice_id',$param['invoice_id'])->find();
230
         # 审批是否停用
335
         # 审批是否停用
231
         $examineStatus = $param['examineStatus'];
336
         $examineStatus = $param['examineStatus'];
232
         # 删除无用参数
337
         # 删除无用参数
236
         unset($param['contract_number']);
341
         unset($param['contract_number']);
237
         # 设置负责人ID
342
         # 设置负责人ID
238
         $param['update_time'] = time();
343
         $param['update_time'] = time();
239
-
344
+        
240
         # 已进行审批,不能编辑
345
         # 已进行审批,不能编辑
241
         // $dataInfo = $invoiceLogic->read($param['invoice_id'], '');
346
         // $dataInfo = $invoiceLogic->read($param['invoice_id'], '');
242
         // if (!$dataInfo) {
347
         // if (!$dataInfo) {
243
         //     $this->error = '数据不存在或已删除';
348
         //     $this->error = '数据不存在或已删除';
244
         //     return false;
349
         //     return false;
245
         // }            
350
         // }            
246
-     
351
+        
247
         $checkStatus = $invoiceLogic->getExamineStatus($param['invoice_id']);
352
         $checkStatus = $invoiceLogic->getExamineStatus($param['invoice_id']);
248
         if (!in_array($checkStatus, ['3', '4', '5', '6'])) return resultArray(['error' => '当前状态为审批中或已审批通过,不可编辑']);
353
         if (!in_array($checkStatus, ['3', '4', '5', '6'])) return resultArray(['error' => '当前状态为审批中或已审批通过,不可编辑']);
249
-
354
+        
250
         # 自动设置发票编号
355
         # 自动设置发票编号
251
         $numberInfo = [];
356
         $numberInfo = [];
252
         if (empty($param['invoice_apple_number'])) {
357
         if (empty($param['invoice_apple_number'])) {
254
             if (empty($numberInfo['number'])) return resultArray(['error' => '请填写发票编号!']);
359
             if (empty($numberInfo['number'])) return resultArray(['error' => '请填写发票编号!']);
255
             $param['invoice_apple_number'] = $numberInfo['number'];
360
             $param['invoice_apple_number'] = $numberInfo['number'];
256
         }
361
         }
257
-
362
+        
258
         # 检查发票编号是否重复
363
         # 检查发票编号是否重复
259
         $invoiceWhere['invoice_apple_number'] = $param['invoice_apple_number'];
364
         $invoiceWhere['invoice_apple_number'] = $param['invoice_apple_number'];
260
         $invoiceWhere['invoice_id'] = ['neq', $this->param['invoice_id']];
365
         $invoiceWhere['invoice_id'] = ['neq', $this->param['invoice_id']];
261
         if ($invoiceLogic->getInvoiceId($invoiceWhere)) return resultArray(['error' => '发票编号重复!']);
366
         if ($invoiceLogic->getInvoiceId($invoiceWhere)) return resultArray(['error' => '发票编号重复!']);
262
-
367
+        
263
         if ($param['is_draft'] || (!empty($param['check_status']) && $param['check_status'] == 5)) {
368
         if ($param['is_draft'] || (!empty($param['check_status']) && $param['check_status'] == 5)) {
264
             //保存为草稿
369
             //保存为草稿
265
             $param['check_status'] = 5; //草稿(未提交)
370
             $param['check_status'] = 5; //草稿(未提交)
266
-            $param['check_user_id'] = $param['check_user_id'] ? ','.$param['check_user_id'].',' : '';
371
+            $param['check_user_id'] = $param['check_user_id'] ? ',' . $param['check_user_id'] . ',' : '';
267
         } else {
372
         } else {
268
             # 将合同审批状态至为待审核,提交后重新进行审批
373
             # 将合同审批状态至为待审核,提交后重新进行审批
269
             if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) {
374
             if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) {
283
                 if ($examineFlowData['config'] == 1) {
388
                 if ($examineFlowData['config'] == 1) {
284
                     # 固定审批流
389
                     # 固定审批流
285
                     $nextStepData = $examineStepModel->nextStepUser($userId, $examineFlowData['flow_id'], 'crm_invoice', 0, 0, 0);
390
                     $nextStepData = $examineStepModel->nextStepUser($userId, $examineFlowData['flow_id'], 'crm_invoice', 0, 0, 0);
286
-                    $next_user_ids = arrayToString($nextStepData['next_user_ids']) ? : '';
287
-                    $check_user_id = $next_user_ids ? : [];
391
+                    $next_user_ids = arrayToString($nextStepData['next_user_ids']) ?: '';
392
+                    $check_user_id = $next_user_ids ?: [];
288
                     $param['order_id'] = 1;
393
                     $param['order_id'] = 1;
289
                 } else {
394
                 } else {
290
                     # 授权审批流
395
                     # 授权审批流
291
-                    $check_user_id = $param['check_user_id'] ? ','.$param['check_user_id'].',' : '';
396
+                    $check_user_id = $param['check_user_id'] ? ',' . $param['check_user_id'] . ',' : '';
292
                 }
397
                 }
293
                 if ($param['is_draft']) {
398
                 if ($param['is_draft']) {
294
                     //保存为草稿
399
                     //保存为草稿
295
                     $param['check_status'] = 5;
400
                     $param['check_status'] = 5;
296
-                    $param['check_user_id'] = $param['check_user_id'] ? ','.$param['check_user_id'].',' : '';
401
+                    $param['check_user_id'] = $param['check_user_id'] ? ',' . $param['check_user_id'] . ',' : '';
297
                 } else {
402
                 } else {
298
                     if (!$check_user_id) {
403
                     if (!$check_user_id) {
299
                         return resultArray(['error' => '无可用审批人,请联系管理员']);
404
                         return resultArray(['error' => '无可用审批人,请联系管理员']);
300
                     }
405
                     }
301
-                    $param['check_user_id'] = is_array($check_user_id) ? ','.implode(',',$check_user_id).',' : $check_user_id;
406
+                    $param['check_user_id'] = is_array($check_user_id) ? ',' . implode(',', $check_user_id) . ',' : $check_user_id;
302
                     $param['check_status'] = 0;
407
                     $param['check_status'] = 0;
303
                 }
408
                 }
304
                 $param['flow_user_id'] = '';
409
                 $param['flow_user_id'] = '';
305
             }
410
             }
306
         }
411
         }
307
 
412
 
413
+        // 数据验证
414
+//        $validateResult = $this->fieldDataValidate($param, 'crm_invoice', $userId);
415
+//        if (!empty($validateResult)) {
416
+//            $this->error = $validateResult;
417
+//            return false;
418
+//        }
419
+
420
+        // 发票扩展表数据
421
+        $invoiceData = [];
422
+
423
+        $fieldModel = new \app\admin\model\Field();
424
+
425
+        // 处理部门、员工、附件、多选类型字段
426
+        $arrFieldAtt = $fieldModel->getArrayField('crm_invoice');
427
+        foreach ($arrFieldAtt as $k=>$v) {
428
+            $param[$v] = arrayToString($param[$v]);
429
+        }
430
+
431
+        // 处理日期(date)类型
432
+        $dateField = $fieldModel->getFieldByFormType('crm_invoice', 'date');
433
+        if (!empty($dateField)) {
434
+            foreach ($param AS $key => $value) {
435
+                if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
436
+            }
437
+        }
438
+
439
+        // 处理手写签名类型
440
+        $handwritingField = $fieldModel->getFieldByFormType('crm_invoice', 'handwriting_sign');
441
+        if (!empty($handwritingField)) {
442
+            foreach ($param AS $key => $value) {
443
+                if (in_array($key, $handwritingField)) {
444
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
445
+                }
446
+            }
447
+        }
448
+
449
+        // 处理地址、定位、日期区间、明细表格类型字段
450
+        $positionField     = $fieldModel->getFieldByFormType('crm_invoice', 'position');
451
+        $locationField     = $fieldModel->getFieldByFormType('crm_invoice', 'location');
452
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_invoice', 'date_interval');
453
+        $detailTableField  = $fieldModel->getFieldByFormType('crm_invoice', 'detail_table');
454
+        foreach ($param AS $key => $value) {
455
+            // 处理地址类型字段数据
456
+            if (in_array($key, $positionField)) {
457
+                if (!empty($value)) {
458
+                    $invoiceData[] = [
459
+                        'field'       => $key,
460
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
461
+                        'create_time' => time()
462
+                    ];
463
+                    $positionNames = array_column($value, 'name');
464
+                    $param[$key] = implode(',', $positionNames);
465
+                } else {
466
+                    $param[$key] = '';
467
+                }
468
+            }
469
+            // 处理定位类型字段数据
470
+            if (in_array($key, $locationField)) {
471
+                if (!empty($value)) {
472
+                    $invoiceData[] = [
473
+                        'field'       => $key,
474
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
475
+                        'create_time' => time()
476
+                    ];
477
+                    $param[$key] = $value['address'];
478
+                } else {
479
+                    $param[$key] = '';
480
+                }
481
+            }
482
+            // 处理日期区间类型字段数据
483
+            if (in_array($key, $dateIntervalField)) {
484
+                if (!empty($value)) {
485
+                    $invoiceData[] = [
486
+                        'field'       => $key,
487
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
488
+                        'create_time' => time()
489
+                    ];
490
+                    $param[$key] = implode('_', $value);
491
+                } else {
492
+                    $param[$key] = '';
493
+                }
494
+            }
495
+            // 处理明细表格类型字段数据
496
+            if (in_array($key, $detailTableField)) {
497
+                if (!empty($value)) {
498
+                    $invoiceData[] = [
499
+                        'field'       => $key,
500
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
501
+                        'create_time' => time()
502
+                    ];
503
+                    $param[$key] = $key;
504
+                } else {
505
+                    $param[$key] = '';
506
+                }
507
+            }
508
+        }
509
+        
308
         if (!$invoiceLogic->update($param)) {
510
         if (!$invoiceLogic->update($param)) {
309
             return resultArray(['error' => '编辑失败!']);
511
             return resultArray(['error' => '编辑失败!']);
310
         }
512
         }
311
-
513
+        
312
         //将审批记录至为无效
514
         //将审批记录至为无效
313
         $examineRecordModel = new \app\admin\model\ExamineRecord();
515
         $examineRecordModel = new \app\admin\model\ExamineRecord();
314
-        $examineRecordModel->setEnd(['types' => 'crm_invoice','types_id' => $param['invoice_id']]);
315
-
516
+        $examineRecordModel->setEnd(['types' => 'crm_invoice', 'types_id' => $param['invoice_id']]);
517
+        
316
         # 更新crm_number_sequence表中的last_date、create_time字段
518
         # 更新crm_number_sequence表中的last_date、create_time字段
317
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
519
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
318
         //修改记录
520
         //修改记录
319
         updateActionLog($param['user_id'], 'crm_invoice', $param['invoice_id'], $dataInfo, $param);
521
         updateActionLog($param['user_id'], 'crm_invoice', $param['invoice_id'], $dataInfo, $param);
320
-        RecordActionLog($param['user_id'], 'crm_invoice', 'update',$dataInfo['invoice_apple_number'], $dataInfo, $param);
522
+        RecordActionLog($param['user_id'], 'crm_invoice', 'update', $dataInfo['invoice_apple_number'], $dataInfo, $param);
321
         # 删除待办事项的关联数据
523
         # 删除待办事项的关联数据
322
         db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'types_id' => ['eq', $param['invoice_id']]])->delete();
524
         db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'types_id' => ['eq', $param['invoice_id']]])->delete();
323
         # 创建待办事项的关联数据
525
         # 创建待办事项的关联数据
324
         $checkUserIds = db('crm_invoice')->where('invoice_id', $param['invoice_id'])->value('check_user_id');
526
         $checkUserIds = db('crm_invoice')->where('invoice_id', $param['invoice_id'])->value('check_user_id');
325
         $checkUserIdArray = stringToArray($checkUserIds);
527
         $checkUserIdArray = stringToArray($checkUserIds);
326
         $dealtData = [];
528
         $dealtData = [];
327
-        foreach ($checkUserIdArray AS $kk => $vv) {
529
+        foreach ($checkUserIdArray as $kk => $vv) {
328
             $dealtData[] = [
530
             $dealtData[] = [
329
-                'types'    => 'crm_invoice',
531
+                'types' => 'crm_invoice',
330
                 'types_id' => $param['invoice_id'],
532
                 'types_id' => $param['invoice_id'],
331
-                'user_id'  => $vv
533
+                'user_id' => $vv
332
             ];
534
             ];
333
         }
535
         }
334
         if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
536
         if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
335
 
537
 
538
+        // 添加客户扩展数据
539
+        $invoiceId = $param['invoice_id'];
540
+        db('crm_invoice_data')->where('invoice_id', $invoiceId)->delete();
541
+        array_walk($invoiceData, function (&$val) use ($invoiceId) {
542
+            $val['invoice_id'] = $invoiceId;
543
+        });
544
+        db('crm_invoice_data')->insertAll($invoiceData);
545
+        
336
         return resultArray(['data' => '编辑成功!']);
546
         return resultArray(['data' => '编辑成功!']);
337
     }
547
     }
338
-
548
+    
339
     /**
549
     /**
340
      * 删除
550
      * 删除
341
      *
551
      *
349
     {
559
     {
350
         $actionRecordModel = new \app\admin\model\ActionRecord();
560
         $actionRecordModel = new \app\admin\model\ActionRecord();
351
         $fileModel = new \app\admin\model\File();
561
         $fileModel = new \app\admin\model\File();
352
-        $idArray  = $this->param['id'];
562
+        $idArray = $this->param['id'];
353
         $userinfo = $this->userInfo['id'];
563
         $userinfo = $this->userInfo['id'];
354
-
564
+        
355
         if (!is_array($idArray)) return resultArray(['error' => '发票ID类型错误!']);
565
         if (!is_array($idArray)) return resultArray(['error' => '发票ID类型错误!']);
356
-
566
+        
357
         $idString = implode(',', $idArray);
567
         $idString = implode(',', $idArray);
358
-        $status   = true;
359
-
568
+        $status = true;
569
+        
360
         if (!isSuperAdministrators($userinfo['id'])) {
570
         if (!isSuperAdministrators($userinfo['id'])) {
361
             $list = $invoiceLogic->getExamineStatus($idString, true);
571
             $list = $invoiceLogic->getExamineStatus($idString, true);
362
-            foreach ($list AS $key => $value) {
363
-                if (!in_array($value['check_status'],  [4, 5])) {
572
+            foreach ($list as $key => $value) {
573
+                if (!in_array($value['check_status'], [4, 5])) {
364
                     $status = false;
574
                     $status = false;
365
                     break;
575
                     break;
366
                 }
576
                 }
367
             }
577
             }
368
         }
578
         }
369
-
579
+        
370
         if (!$status) return resultArray(['error' => '不能删除审批中或审批结束的发票信息!']);
580
         if (!$status) return resultArray(['error' => '不能删除审批中或审批结束的发票信息!']);
371
-        $dataInfo=db('crm_invoice')->where('invoice_id',['in',$idArray])->select();
581
+        $dataInfo = db('crm_invoice')->where('invoice_id', ['in', $idArray])->select();
372
         if (!$invoiceLogic->delete($idArray)) return resultArray(['error' => '删除失败!']);
582
         if (!$invoiceLogic->delete($idArray)) return resultArray(['error' => '删除失败!']);
373
-
583
+        
374
         # 删除附件
584
         # 删除附件
375
         $fileModel->delRFileByModule('crm_invoice', $idArray);
585
         $fileModel->delRFileByModule('crm_invoice', $idArray);
376
         //删除关联操作记录
586
         //删除关联操作记录
377
-        $actionRecordModel->delDataById(['types'=>'crm_invoice','action_id'=>$idArray]);
587
+        $actionRecordModel->delDataById(['types' => 'crm_invoice', 'action_id' => $idArray]);
378
         $userInfo = $this->userInfo;
588
         $userInfo = $this->userInfo;
379
         foreach ($dataInfo as $k => $v) {
589
         foreach ($dataInfo as $k => $v) {
380
             RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['invoice_apple_number'], '', '', '删除了回款:' . $v['invoice_apple_number']);
590
             RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['invoice_apple_number'], '', '', '删除了回款:' . $v['invoice_apple_number']);
381
         }
591
         }
382
         return resultArray(['data' => '删除成功!']);
592
         return resultArray(['data' => '删除成功!']);
383
     }
593
     }
384
-
594
+    
385
     /**
595
     /**
386
      * 转移(变更负责人)
596
      * 转移(变更负责人)
387
      *
597
      *
391
     public function transfer(InvoiceLogic $invoiceLogic)
601
     public function transfer(InvoiceLogic $invoiceLogic)
392
     {
602
     {
393
         $ownerUserId = $this->param['owner_user_id'];
603
         $ownerUserId = $this->param['owner_user_id'];
394
-        $invoiceIds  = $this->param['invoice_id'];
604
+        $invoiceIds = $this->param['invoice_id'];
395
         $userModel = new \app\admin\model\User();
605
         $userModel = new \app\admin\model\User();
396
-        $userInfo=$this->userInfo;
397
-        if (empty($ownerUserId))    return resultArray(['error' => '请选择负责人!']);
398
-        if (empty($invoiceIds))     return resultArray(['error' => '请选择发票!']);
606
+        $userInfo = $this->userInfo;
607
+        if (empty($ownerUserId)) return resultArray(['error' => '请选择负责人!']);
608
+        if (empty($invoiceIds)) return resultArray(['error' => '请选择发票!']);
399
         if (!is_array($invoiceIds)) return resultArray(['error' => '发票ID类型错误!']);
609
         if (!is_array($invoiceIds)) return resultArray(['error' => '发票ID类型错误!']);
400
-
610
+        
401
         if ($invoiceLogic->transfer($invoiceIds, $ownerUserId) === false) return resultArray(['error' => '操作失败!']);
611
         if ($invoiceLogic->transfer($invoiceIds, $ownerUserId) === false) return resultArray(['error' => '操作失败!']);
402
         $owner_user_info = $userModel->getUserById($ownerUserId);
612
         $owner_user_info = $userModel->getUserById($ownerUserId);
403
-        foreach ($invoiceIds as $v){
404
-            $invoice_info=db('crm_invoice')->where('invoice_id',$v)->find();
613
+        foreach ($invoiceIds as $v) {
614
+            $invoice_info = db('crm_invoice')->where('invoice_id', $v)->find();
405
             updateActionLog($userInfo['id'], 'crm_invoice', $v, '', '', '将发票转移给:' . $owner_user_info['realname']);
615
             updateActionLog($userInfo['id'], 'crm_invoice', $v, '', '', '将发票转移给:' . $owner_user_info['realname']);
406
-            RecordActionLog($userInfo['id'], 'crm_invoice', 'transfer',$invoice_info['invoice_apple_number'], '','','将发票:'.$invoice_info['invoice_apple_number'].'转移给:' . $owner_user_info['realname']);
616
+            RecordActionLog($userInfo['id'], 'crm_invoice', 'transfer', $invoice_info['invoice_apple_number'], '', '', '将发票:' . $invoice_info['invoice_apple_number'] . '转移给:' . $owner_user_info['realname']);
407
         }
617
         }
408
         return resultArray(['data' => '操作成功!']);
618
         return resultArray(['data' => '操作成功!']);
409
     }
619
     }
410
-
620
+    
411
     /**
621
     /**
412
      * 设置开票
622
      * 设置开票
413
      *
623
      *
416
      */
626
      */
417
     public function setInvoice(InvoiceLogic $invoiceLogic)
627
     public function setInvoice(InvoiceLogic $invoiceLogic)
418
     {
628
     {
419
-        if (empty($this->param['invoice_id']))        return resultArray(['error' => '参数错误!']);
629
+        if (empty($this->param['invoice_id'])) return resultArray(['error' => '参数错误!']);
420
 //        if (empty($this->param['invoice_number']))    return resultArray(['error' => '请填写发票号码!']);
630
 //        if (empty($this->param['invoice_number']))    return resultArray(['error' => '请填写发票号码!']);
421
 //        if (empty($this->param['logistics_number']))  return resultArray(['error' => '请填写物流单号!']);
631
 //        if (empty($this->param['logistics_number']))  return resultArray(['error' => '请填写物流单号!']);
422
 //        if (empty($this->param['real_invoice_date'])) return resultArray(['error' => '请选择开票日期!']);
632
 //        if (empty($this->param['real_invoice_date'])) return resultArray(['error' => '请选择开票日期!']);
423
-
633
+        
424
         $this->param['real_invoice_date'] = !empty($this->param['real_invoice_date']) ? $this->param['real_invoice_date'] : date('Y-m-d');
634
         $this->param['real_invoice_date'] = !empty($this->param['real_invoice_date']) ? $this->param['real_invoice_date'] : date('Y-m-d');
425
-
635
+        
426
         # 开票状态
636
         # 开票状态
427
         $this->param['invoice_status'] = 1;
637
         $this->param['invoice_status'] = 1;
428
-
638
+        
429
         # 设置开票信息
639
         # 设置开票信息
430
         if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']);
640
         if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']);
431
-
641
+        
432
         return resultArray(['data' => '操作成功!']);
642
         return resultArray(['data' => '操作成功!']);
433
     }
643
     }
434
-
644
+    
435
     /**
645
     /**
436
      * 审核
646
      * 审核
437
      *
647
      *
443
      */
653
      */
444
     public function check(InvoiceLogic $invoiceLogic)
654
     public function check(InvoiceLogic $invoiceLogic)
445
     {
655
     {
446
-        $param              = $this->param;
447
-        $user_id            = $this->userInfo['id'];
448
-
449
-        $examineStepModel   = new \app\admin\model\ExamineStep();
656
+        $param = $this->param;
657
+        $user_id = $this->userInfo['id'];
658
+        
659
+        $examineStepModel = new \app\admin\model\ExamineStep();
450
         $examineRecordModel = new \app\admin\model\ExamineRecord();
660
         $examineRecordModel = new \app\admin\model\ExamineRecord();
451
-        $examineFlowModel   = new \app\admin\model\ExamineFlow();
452
-
661
+        $examineFlowModel = new \app\admin\model\ExamineFlow();
662
+        
453
         $invoiceData = [];
663
         $invoiceData = [];
454
-        $invoiceData['invoice_id']   = $param['id'];
455
-        $invoiceData['update_time']  = time();
664
+        $invoiceData['invoice_id'] = $param['id'];
665
+        $invoiceData['update_time'] = time();
456
         $invoiceData['check_status'] = 1;
666
         $invoiceData['check_status'] = 1;
457
         # 权限判断
667
         # 权限判断
458
         if (!$examineStepModel->checkExamine($user_id, 'crm_invoice', $param['id'])) {
668
         if (!$examineStepModel->checkExamine($user_id, 'crm_invoice', $param['id'])) {
459
             return resultArray(['error' => $examineStepModel->getError()]);
669
             return resultArray(['error' => $examineStepModel->getError()]);
460
         }
670
         }
461
-
671
+        
462
         # 审批主体详情
672
         # 审批主体详情
463
         $dataInfo = $invoiceLogic->getExamineInfo($param['id']);
673
         $dataInfo = $invoiceLogic->getExamineInfo($param['id']);
464
         $flowInfo = $examineFlowModel->getDataById($dataInfo['flow_id']);
674
         $flowInfo = $examineFlowModel->getDataById($dataInfo['flow_id']);
465
-
675
+        
466
         # 1审批结束
676
         # 1审批结束
467
         $is_end = 0;
677
         $is_end = 0;
468
-
678
+        
469
         # 1通过,0驳回
679
         # 1通过,0驳回
470
         $status = !empty($param['status']) && $param['status'] == 1 ? 1 : 0;
680
         $status = !empty($param['status']) && $param['status'] == 1 ? 1 : 0;
471
-
681
+        
472
         # 审批记录
682
         # 审批记录
473
-        $checkData                  = [];
683
+        $checkData = [];
474
         $checkData['check_user_id'] = $user_id;
684
         $checkData['check_user_id'] = $user_id;
475
-        $checkData['types']         = 'crm_invoice';
476
-        $checkData['types_id']      = $param['id'];
477
-        $checkData['check_time']    = time();
478
-        $checkData['content']       = $param['content'];
479
-        $checkData['flow_id']       = $dataInfo['flow_id'];
480
-        $checkData['order_id']      = $dataInfo['order_id'] ? : 1;
481
-        $checkData['status']        = $status;
482
-
685
+        $checkData['types'] = 'crm_invoice';
686
+        $checkData['types_id'] = $param['id'];
687
+        $checkData['check_time'] = time();
688
+        $checkData['content'] = $param['content'];
689
+        $checkData['flow_id'] = $dataInfo['flow_id'];
690
+        $checkData['order_id'] = $dataInfo['order_id'] ?: 1;
691
+        $checkData['status'] = $status;
692
+        
483
         if ($status == 1) {
693
         if ($status == 1) {
484
             if ($flowInfo['config'] == 1) {
694
             if ($flowInfo['config'] == 1) {
485
                 # 固定流程
695
                 # 固定流程
486
                 # 获取下一审批信息
696
                 # 获取下一审批信息
487
                 $nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $dataInfo['flow_id'], 'crm_invoice', $param['id'], $dataInfo['order_id'], $user_id);
697
                 $nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $dataInfo['flow_id'], 'crm_invoice', $param['id'], $dataInfo['order_id'], $user_id);
488
-                $next_user_ids = $nextStepData['next_user_ids'] ? : [];
489
-                $invoiceData['order_id'] = $nextStepData['order_id'] ? : '';
698
+                $next_user_ids = $nextStepData['next_user_ids'] ?: [];
699
+                $invoiceData['order_id'] = $nextStepData['order_id'] ?: '';
490
                 if (!$next_user_ids) {
700
                 if (!$next_user_ids) {
491
                     $is_end = 1;
701
                     $is_end = 1;
492
                     # 审批结束
702
                     # 审批结束
493
-                    $checkData['check_status']    = !empty($status) ? 2 : 3;
703
+                    $checkData['check_status'] = !empty($status) ? 2 : 3;
494
                     $invoiceData['check_user_id'] = '';
704
                     $invoiceData['check_user_id'] = '';
495
                 } else {
705
                 } else {
496
                     # 修改主体相关审批信息
706
                     # 修改主体相关审批信息
498
                 }
708
                 }
499
             } else {
709
             } else {
500
                 # 自选流程
710
                 # 自选流程
501
-                $is_end        = $param['is_end'] ? 1 : '';
502
-                $check_user_id = $param['check_user_id'] ? : '';
711
+                $is_end = $param['is_end'] ? 1 : '';
712
+                $check_user_id = $param['check_user_id'] ?: '';
503
                 if ($is_end !== 1 && empty($check_user_id)) {
713
                 if ($is_end !== 1 && empty($check_user_id)) {
504
                     return resultArray(['error' => '请选择下一审批人']);
714
                     return resultArray(['error' => '请选择下一审批人']);
505
                 }
715
                 }
506
                 $invoiceData['check_user_id'] = arrayToString($param['check_user_id']);
716
                 $invoiceData['check_user_id'] = arrayToString($param['check_user_id']);
507
             }
717
             }
508
             if ($is_end == 1) {
718
             if ($is_end == 1) {
509
-                $checkData['check_status']    = !empty($status) ? 2 : 3;
719
+                $checkData['check_status'] = !empty($status) ? 2 : 3;
510
                 $invoiceData['check_user_id'] = '';
720
                 $invoiceData['check_user_id'] = '';
511
-                $invoiceData['check_status']  = 2;
721
+                $invoiceData['check_status'] = 2;
512
             }
722
             }
513
         } else {
723
         } else {
514
             # 审批驳回
724
             # 审批驳回
516
             $invoiceData['check_status'] = 3;
726
             $invoiceData['check_status'] = 3;
517
         }
727
         }
518
         # 已审批人ID
728
         # 已审批人ID
519
-        $invoiceData['flow_user_id'] = stringToArray($dataInfo['flow_user_id']) ? arrayToString(array_merge(stringToArray($dataInfo['flow_user_id']),[$user_id])) : arrayToString([$user_id]);
729
+        $invoiceData['flow_user_id'] = stringToArray($dataInfo['flow_user_id']) ? arrayToString(array_merge(stringToArray($dataInfo['flow_user_id']), [$user_id])) : arrayToString([$user_id]);
520
         $resContract = $invoiceLogic->setExamineInfo($invoiceData);
730
         $resContract = $invoiceLogic->setExamineInfo($invoiceData);
521
         if ($resContract) {
731
         if ($resContract) {
522
             # 审批记录
732
             # 审批记录
523
             $examineRecordModel->createData($checkData);
733
             $examineRecordModel->createData($checkData);
524
-
734
+            
525
             # 发送站内信
735
             # 发送站内信
526
             if ($is_end == 1 && !empty($status)) {
736
             if ($is_end == 1 && !empty($status)) {
527
                 # 审批流程结束,将审批通过消息告知负责人
737
                 # 审批流程结束,将审批通过消息告知负责人
528
                 (new Message())->send(
738
                 (new Message())->send(
529
                     Message::INVOICE_PASS,
739
                     Message::INVOICE_PASS,
530
                     [
740
                     [
531
-                        'title'     => $dataInfo['invoice_apple_number'],
741
+                        'title' => $dataInfo['invoice_apple_number'],
532
                         'action_id' => $param['id']
742
                         'action_id' => $param['id']
533
                     ],
743
                     ],
534
                     stringToArray($dataInfo['owner_user_id'])
744
                     stringToArray($dataInfo['owner_user_id'])
540
                         Message::INVOICE_TO_DO,
750
                         Message::INVOICE_TO_DO,
541
                         [
751
                         [
542
                             'from_user' => User::where(['id' => $dataInfo['owner_user_id']])->value('realname'),
752
                             'from_user' => User::where(['id' => $dataInfo['owner_user_id']])->value('realname'),
543
-                            'title'     => $dataInfo['invoice_apple_number'],
753
+                            'title' => $dataInfo['invoice_apple_number'],
544
                             'action_id' => $param['id']
754
                             'action_id' => $param['id']
545
                         ],
755
                         ],
546
                         stringToArray($invoiceData['check_user_id'])
756
                         stringToArray($invoiceData['check_user_id'])
550
                     (new Message())->send(
760
                     (new Message())->send(
551
                         Message::INVOICE_REJECT,
761
                         Message::INVOICE_REJECT,
552
                         [
762
                         [
553
-                            'title'     => $dataInfo['invoice_apple_number'],
763
+                            'title' => $dataInfo['invoice_apple_number'],
554
                             'action_id' => $param['id']
764
                             'action_id' => $param['id']
555
                         ],
765
                         ],
556
                         stringToArray($dataInfo['owner_user_id'])
766
                         stringToArray($dataInfo['owner_user_id'])
557
                     );
767
                     );
558
                 }
768
                 }
559
             }
769
             }
560
-
770
+            
561
             return resultArray(['data' => '审批成功']);
771
             return resultArray(['data' => '审批成功']);
562
         } else {
772
         } else {
563
             return resultArray(['error' => '审批失败,请重试!']);
773
             return resultArray(['error' => '审批失败,请重试!']);
564
         }
774
         }
565
     }
775
     }
566
-
776
+    
567
     /**
777
     /**
568
      * 撤销审核
778
      * 撤销审核
569
      *
779
      *
576
     public function revokeCheck(InvoiceLogic $invoiceLogic)
786
     public function revokeCheck(InvoiceLogic $invoiceLogic)
577
     {
787
     {
578
         $invoiceId = $this->param['id'];
788
         $invoiceId = $this->param['id'];
579
-        $content   = $this->param['content'];
580
-        $realname  = $this->userInfo['realname'];
581
-        $userInfo  = $this->userInfo;
582
-        $user_id   = $userInfo['id'];
583
-
789
+        $content = $this->param['content'];
790
+        $realname = $this->userInfo['realname'];
791
+        $userInfo = $this->userInfo;
792
+        $user_id = $userInfo['id'];
793
+        
584
         if (empty($invoiceId)) return resultArray(['error' => '请选择要撤回审核的发票!']);
794
         if (empty($invoiceId)) return resultArray(['error' => '请选择要撤回审核的发票!']);
585
-
795
+        
586
         $examineInfo = $invoiceLogic->getExamineInfo($invoiceId);
796
         $examineInfo = $invoiceLogic->getExamineInfo($invoiceId);
587
-
797
+        
588
         if ($examineInfo['check_status'] == 2) {
798
         if ($examineInfo['check_status'] == 2) {
589
             return resultArray(['error' => '已审批结束,不能撤销']);
799
             return resultArray(['error' => '已审批结束,不能撤销']);
590
         }
800
         }
596
         if ($examineInfo['owner_user_id'] !== $user_id && !in_array($user_id, $admin_user_ids)) {
806
         if ($examineInfo['owner_user_id'] !== $user_id && !in_array($user_id, $admin_user_ids)) {
597
             return resultArray(['error' => '没有权限']);
807
             return resultArray(['error' => '没有权限']);
598
         }
808
         }
599
-
809
+        
600
         # 修改发票审核状态
810
         # 修改发票审核状态
601
         if (!$invoiceLogic->update(['invoice_id' => $invoiceId, 'check_status' => 4, 'check_user_id' => '', 'flow_user_id' => ''])) {
811
         if (!$invoiceLogic->update(['invoice_id' => $invoiceId, 'check_status' => 4, 'check_user_id' => '', 'flow_user_id' => ''])) {
602
             return resultArray(['error' => '操作失败!']);
812
             return resultArray(['error' => '操作失败!']);
603
         }
813
         }
604
-
814
+        
605
         # 添加撤销审核的记录
815
         # 添加撤销审核的记录
606
         $invoiceLogic->createExamineRecord($invoiceId, $examineInfo, $realname, $content, $user_id);
816
         $invoiceLogic->createExamineRecord($invoiceId, $examineInfo, $realname, $content, $user_id);
607
-
817
+        
608
         return resultArray(['data' => '操作成功!']);
818
         return resultArray(['data' => '操作成功!']);
609
     }
819
     }
610
-
820
+    
611
     /**
821
     /**
612
      * table栏数量统计
822
      * table栏数量统计
613
      *
823
      *
617
     public function count()
827
     public function count()
618
     {
828
     {
619
         if (empty($this->param['invoice_id'])) return resultArray(['error' => '参数错误!']);
829
         if (empty($this->param['invoice_id'])) return resultArray(['error' => '参数错误!']);
620
-
830
+        
621
         # 附件
831
         # 附件
622
         $fileCount = Db::name('crm_invoice_file')->alias('invoice')->join('__ADMIN_FILE__ file', 'file.file_id = invoice.file_id', 'LEFT')->where('invoice_id', $this->param['invoice_id'])->count();
832
         $fileCount = Db::name('crm_invoice_file')->alias('invoice')->join('__ADMIN_FILE__ file', 'file.file_id = invoice.file_id', 'LEFT')->where('invoice_id', $this->param['invoice_id'])->count();
623
-
833
+        
624
         return resultArray(['data' => ['fileCount' => $fileCount]]);
834
         return resultArray(['data' => ['fileCount' => $fileCount]]);
625
     }
835
     }
626
-
836
+    
627
     /**
837
     /**
628
      * 重置开票信息
838
      * 重置开票信息
629
      *
839
      *
635
         if (empty($this->param['invoice_id'])) resultArray(['error' => '参数错误!']);
845
         if (empty($this->param['invoice_id'])) resultArray(['error' => '参数错误!']);
636
         $userInfo = $this->userInfo;
846
         $userInfo = $this->userInfo;
637
         $this->param['real_invoice_date'] = !empty($this->param['real_invoice_date']) ? $this->param['real_invoice_date'] : date('Y-m-d');
847
         $this->param['real_invoice_date'] = !empty($this->param['real_invoice_date']) ? $this->param['real_invoice_date'] : date('Y-m-d');
638
-
848
+        
639
         # 开票状态
849
         # 开票状态
640
         $this->param['invoice_status'] = 1;
850
         $this->param['invoice_status'] = 1;
641
-        $invoice_info=db('crm_invoice')->where('invoice_id',$this->param['invoice_id'])->find();
851
+        $invoice_info = db('crm_invoice')->where('invoice_id', $this->param['invoice_id'])->find();
642
         if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']);
852
         if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']);
643
-        RecordActionLog($userInfo['id'], 'crm_invoice', 'update',$invoice_info['invoice_apple_number'], '','','将发票:'.$invoice_info['invoice_apple_number'].'重置开票状态');
853
+        RecordActionLog($userInfo['id'], 'crm_invoice', 'update', $invoice_info['invoice_apple_number'], '', '', '将发票:' . $invoice_info['invoice_apple_number'] . '重置开票状态');
644
         return resultArray(['data' => '操作成功!']);
854
         return resultArray(['data' => '操作成功!']);
645
-
855
+        
856
+    }
857
+    
858
+    /**
859
+     * 导出
860
+     *
861
+     * @author      alvin guogaobo
862
+     * @version     1.0 版本号
863
+     * @since       2021/5/22 0022 14:34
864
+     */
865
+    public function excelExport()
866
+    {
867
+        $param = $this->param;
868
+        $userInfo = $this->userInfo;
869
+        $action_name = '导出全部';
870
+        $param['is_excel'] = 1;
871
+        $invoiceLogic=new InvoiceLogic();
872
+        $excelModel = new \app\admin\model\Excel();
873
+        // 导出的字段列表
874
+        $fieldModel = new \app\admin\model\Field();
875
+        $field_list = $fieldModel->getIndexFieldConfig('crm_invoice', $userInfo['id'],'','excel');
876
+        if ($param['invoice_id']) {
877
+            $param['invoice_id'] = ['condition' => 'in', 'value' => $param['invoice_id'], 'form_type' => 'text', 'name' => ''];
878
+            $action_name = '导出选中';
879
+        }
880
+        $field = [
881
+            0 => [
882
+                'field' => 'check_status',
883
+                'name' => '审核状态',
884
+                'form_type' => 'text',
885
+                'is_hidden' => 0,
886
+            ],
887
+            1 => [
888
+                'field' => 'invoice_status',
889
+                'name' => '开票状态',
890
+                'form_type' => 'text',
891
+                'is_hidden' => 0
892
+            ],
893
+            2 => [
894
+                'field' => 'real_invoice_date',
895
+                'name' => '实际开票日期',
896
+                'form_type' => 'date',
897
+                'is_hidden' => 0
898
+            ],
899
+            3 => [
900
+                'field' => 'invoice_number',
901
+                'name' => '发票号码',
902
+                'form_type' => 'text',
903
+                'is_hidden' => 0
904
+            ],
905
+            4 => [
906
+                'field' => 'logistics_number',
907
+                'name' => '物流单号',
908
+                'form_type' => 'text',
909
+                'is_hidden' => 0,
910
+            ]
911
+        ];
912
+        $field_list=array_merge($field_list,$field);
913
+        // 文件名
914
+        $file_name = '5kcrm_invoice_' . date('Ymd');
915
+        $model = model('Invoice');
916
+        $temp_file = $param['temp_file'];
917
+        unset($param['temp_file']);
918
+        $page = $param['page']?: 1;
919
+        unset($param['page']);
920
+        unset($param['export_queue_index']);
921
+//        RecordActionLog($userInfo['id'],'crm_invoice','excelexport',$action_name,'','','导出客户');
922
+        return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list,$invoiceLogic) {
923
+            $param['page'] = $page;
924
+            $param['limit'] = $limit;
925
+            $data = $invoiceLogic->index($param);
926
+            $data['list'] = $model->exportHandle($data['list'], $field_list, 'invoice');
927
+            return $data;
928
+        });
646
     }
929
     }
647
 }
930
 }

+ 19
- 33
application/crm/controller/Leads.php Bestand weergeven

181
             if (!$data) {
181
             if (!$data) {
182
                 return resultArray(['error' => $leadsModel->getError()]);
182
                 return resultArray(['error' => $leadsModel->getError()]);
183
             }
183
             }
184
+            // 删除线索扩展数据
185
+            db('crm_leads_data')->whereIn('leads_id', $delIds)->delete();
184
             //删除跟进记录
186
             //删除跟进记录
185
             $recordModel->delDataByTypes(1, $delIds);
187
             $recordModel->delDataByTypes(1, $delIds);
186
             //删除关联附件
188
             //删除关联附件
346
      */
348
      */
347
     public function excelDownload($save_path = '')
349
     public function excelDownload($save_path = '')
348
     {
350
     {
349
-    
351
+        # 下次升级使用
350
         $param = $this->param;
352
         $param = $this->param;
351
         $userInfo = $this->userInfo;
353
         $userInfo = $this->userInfo;
352
         $excelModel = new \app\admin\model\Excel();
354
         $excelModel = new \app\admin\model\Excel();
355
         $fieldParam['types'] = 'crm_leads';
357
         $fieldParam['types'] = 'crm_leads';
356
         $fieldParam['action'] = 'excel';
358
         $fieldParam['action'] = 'excel';
357
         $field_list = $fieldModel->field($fieldParam);
359
         $field_list = $fieldModel->field($fieldParam);
358
-        // $field_list = $fieldModel->getIndexFieldList('crm_leads', $userInfo['id']);
359
-        $data = $excelModel->excelImportDownload($field_list, 'crm_leads', $save_path);
360
-        
361
-        # 下次升级使用
362
-//        $param = $this->param;
363
-//        $userInfo = $this->userInfo;
364
-//        $excelModel = new \app\admin\model\Excel();
365
-//        // 导出的字段列表
366
-//        $fieldModel = new \app\admin\model\Field();
367
-//        $fieldParam['types'] = 'crm_leads';
368
-//        $fieldParam['action'] = 'excel';
369
-//        $field_list = $fieldModel->field($fieldParam);
370
-//        $field=[1=>[
371
-//            'field'=>'owner_user_id',
372
-//            'types'=>'crm_leads',
373
-//            'name'=>'负责人',
374
-//            'form_type'=>'user',
375
-//            'default_value'=>'',
376
-//            'is_unique' => 1,
377
-//            'is_null' => 1,
378
-//            'input_tips' =>'',
379
-//            'setting' => Array(),
380
-//            'is_hidden'=>0,
381
-//            'writeStatus' => 1,
382
-//            'value' => '']
383
-//        ];
384
-//        $first_array = array_splice($field_list, 0, 2);
385
-//        $array = array_merge($first_array, $field, $field_list);
386
-//        $data = $excelModel->excelImportDownload($array, 'crm_leads', $save_path);
387
-
388
-        return resultArray(['data' => $data]);
360
+        $field=[1=>[
361
+            'field'=>'owner_user_id',
362
+            'types'=>'crm_leads',
363
+            'name'=>'负责人',
364
+            'form_type'=>'user',
365
+            'default_value'=>'',
366
+            'is_null' => 1,
367
+            'input_tips' =>'',
368
+            'setting' => Array(),
369
+            'is_hidden'=>0,
370
+            'writeStatus' => 1,
371
+            'value' => '']
372
+        ];
373
+        $first_array = array_splice($field_list, 2,0, $field);
374
+        $excelModel->excelImportDownload($field_list, 'crm_leads', $save_path);
389
     }
375
     }
390
 
376
 
391
     /**
377
     /**
409
         $excelModel = new \app\admin\model\Excel();
395
         $excelModel = new \app\admin\model\Excel();
410
         // 导出的字段列表
396
         // 导出的字段列表
411
         $fieldModel = new \app\admin\model\Field();
397
         $fieldModel = new \app\admin\model\Field();
412
-        $field_list = $fieldModel->getIndexFieldConfig('crm_leads', $userInfo['id']);
398
+        $field_list = $fieldModel->getIndexFieldConfig('crm_leads', $userInfo['id'],'','excel');
413
         // 文件名
399
         // 文件名
414
         $file_name = '5kcrm_leads_' . date('Ymd');
400
         $file_name = '5kcrm_leads_' . date('Ymd');
415
 
401
 

+ 137
- 273
application/crm/controller/Message.php Bestand weergeven

9
 
9
 
10
 use app\admin\controller\ApiCommon;
10
 use app\admin\controller\ApiCommon;
11
 use app\crm\logic\InvoiceLogic;
11
 use app\crm\logic\InvoiceLogic;
12
+use app\crm\logic\MessageLogic;
13
+use think\Cache;
12
 use think\cache\driver\Redis;
14
 use think\cache\driver\Redis;
13
 use think\Db;
15
 use think\Db;
14
 use think\Hook;
16
 use think\Hook;
16
 
18
 
17
 class Message extends ApiCommon
19
 class Message extends ApiCommon
18
 {
20
 {
19
-	/**
21
+    /**
20
      * 用于判断权限
22
      * 用于判断权限
21
      * @permission 无限制
23
      * @permission 无限制
22
      * @allow 登录用户可访问
24
      * @allow 登录用户可访问
23
      * @other 其他根据系统设置
25
      * @other 其他根据系统设置
24
-    **/    
26
+     **/
25
     public function _initialize()
27
     public function _initialize()
26
     {
28
     {
27
         $action = [
29
         $action = [
45
         ];
47
         ];
46
         Hook::listen('check_auth',$action);
48
         Hook::listen('check_auth',$action);
47
         $request = Request::instance();
49
         $request = Request::instance();
48
-        $a = strtolower($request->action());        
50
+        $a = strtolower($request->action());
49
         if (!in_array($a, $action['permission'])) {
51
         if (!in_array($a, $action['permission'])) {
50
             parent::_initialize();
52
             parent::_initialize();
51
         }
53
         }
52
-    } 
53
-
54
+    }
55
+    
54
     /**
56
     /**
55
      * 系统通知
57
      * 系统通知
56
      *
58
      *
57
      * @author Michael_xu
59
      * @author Michael_xu
58
-     * @return 
60
+     * @return
59
      */
61
      */
60
     public function index()
62
     public function index()
61
     {
63
     {
62
-    	$messageModel = model('Message');
63
-		$param = $this->param;
64
+        $messageModel = model('Message');
65
+        $param = $this->param;
64
         $userInfo = $this->userInfo;
66
         $userInfo = $this->userInfo;
65
-        $param['user_id'] = $userInfo['id']; 
66
-        $param['module_name'] = 'crm';       
67
+        $param['user_id'] = $userInfo['id'];
68
+        $param['module_name'] = 'crm';
67
         $data = $messageModel->getDataList($param);
69
         $data = $messageModel->getDataList($param);
68
-        return resultArray(['data' => $data]);    	
70
+        return resultArray(['data' => $data]);
69
     }
71
     }
70
-
72
+    
71
     /**
73
     /**
72
      * 消息数
74
      * 消息数
73
      *
75
      *
80
         $configDataModel = model('ConfigData');
82
         $configDataModel = model('ConfigData');
81
         $configData = $configDataModel->getData();
83
         $configData = $configDataModel->getData();
82
         $data = [];
84
         $data = [];
83
-
84
         # 今日需联系线索
85
         # 今日需联系线索
85
         $todayLeadsTime  = cache('todayLeadsTime'.$userInfo['id']);
86
         $todayLeadsTime  = cache('todayLeadsTime'.$userInfo['id']);
86
         $todayLeadsCount = cache('todayLeadsCount'.$userInfo['id']);
87
         $todayLeadsCount = cache('todayLeadsCount'.$userInfo['id']);
106
         # 今日需联系商机
107
         # 今日需联系商机
107
         $todayBusinessTime  = cache('todayBusinessTime'.$userInfo['id']);
108
         $todayBusinessTime  = cache('todayBusinessTime'.$userInfo['id']);
108
         $todayBusinessCount = cache('todayBusinessCount'.$userInfo['id']);
109
         $todayBusinessCount = cache('todayBusinessCount'.$userInfo['id']);
109
-        if ($todayBusinessTime <= time()) {
110
+        if (time() <= $todayBusinessTime) {
110
             $data['todayBusiness'] = (int)$todayBusinessCount;
111
             $data['todayBusiness'] = (int)$todayBusinessCount;
111
         } else {
112
         } else {
112
             $todayBusiness = $this->todayBusiness(true);
113
             $todayBusiness = $this->todayBusiness(true);
163
         $checkInvoiceCount = cache('checkInvoiceCount'.$userInfo['id']);
164
         $checkInvoiceCount = cache('checkInvoiceCount'.$userInfo['id']);
164
         if (time() <= $checkInvoiceTime) {
165
         if (time() <= $checkInvoiceTime) {
165
             $data['checkInvoice'] = (int)$checkInvoiceCount;
166
             $data['checkInvoice'] = (int)$checkInvoiceCount;
167
+
166
         } else {
168
         } else {
167
             $checkInvoice = $this->checkInvoice(true);
169
             $checkInvoice = $this->checkInvoice(true);
168
             $data['checkInvoice'] = $checkInvoice['dataCount'] ? : 0;
170
             $data['checkInvoice'] = $checkInvoice['dataCount'] ? : 0;
171
+
169
             cache('checkInvoiceCount'.$userInfo['id'], $data['checkInvoice']);
172
             cache('checkInvoiceCount'.$userInfo['id'], $data['checkInvoice']);
170
             cache('checkInvoiceTime'.$userInfo['id'], time() + 180);
173
             cache('checkInvoiceTime'.$userInfo['id'], time() + 180);
171
         }
174
         }
220
                 cache('remindCustomerTime'.$userInfo['id'], time() + 180);
223
                 cache('remindCustomerTime'.$userInfo['id'], time() + 180);
221
             }
224
             }
222
         }
225
         }
223
-
226
+        
224
         return resultArray(['data' => $data]);
227
         return resultArray(['data' => $data]);
225
     }
228
     }
226
-
229
+    
227
     /**
230
     /**
228
      * 今日需联系线索
231
      * 今日需联系线索
229
      *
232
      *
232
      */
235
      */
233
     public function todayLeads($getCount = false)
236
     public function todayLeads($getCount = false)
234
     {
237
     {
235
-        $param     = $this->param;
236
-        $userId    = $this->userInfo['id'];
237
-        $types     = $param['types'];
238
-        $type      = !empty($param['type'])  ? $param['type']  : 1;
239
-        $isSub     = !empty($param['isSub']) ? $param['isSub'] : 0;
240
-        $todayTime = getTimeByType('today');
238
+        $param  = $this->param;
239
+        $userId = $this->userInfo['id'];
240
+        $types  = $param['types'];
241
         unset($param['types']);
241
         unset($param['types']);
242
-        unset($param['type']);
243
-        unset($param['isSub']);
244
-
245
-        if ($getCount == true) $param['getCount'] = 1;
246
-
247
-        $leadsModel = new \app\crm\model\Leads();
248
-
249
-        # 负责人
250
-        $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userId)] : $userId;
251
-        # 类型:1今日需联系;2已逾期;3已联系
252
-        switch ($type) {
253
-            case '1' :
254
-                $param['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
255
-                $param['is_dealt'] = ['neq', 1];
256
-                break;
257
-            case '2' :
258
-                $param['next_time'] = ['between', [1, time()]];
259
-                $param['is_dealt'] = ['neq', 1];
260
-                break;
261
-            case '3' :
262
-                $param['last_time'] = ['between', [$todayTime[0], $todayTime[1]]];
263
-                $param['is_dealt'] = ['eq', 1];
264
-                break;
265
-        }
266
-
267
         $param['user_id'] = $userId;
242
         $param['user_id'] = $userId;
268
-        $data = $leadsModel->getDataList($param);
243
+        if ($getCount == true) $param['getCount'] = 1;
244
+        $messageLogic= new MessageLogic();
269
 
245
 
246
+        $data = $messageLogic->todayLeads($param);
247
+      
270
         if ($types == 'list') return resultArray(['data' => $data]);
248
         if ($types == 'list') return resultArray(['data' => $data]);
271
-
249
+        
272
         return $data;
250
         return $data;
273
     }
251
     }
274
-
252
+    
275
     /**
253
     /**
276
      * 今日需联系客户
254
      * 今日需联系客户
277
      *
255
      *
281
     public function todayCustomer($getCount = false)
259
     public function todayCustomer($getCount = false)
282
     {
260
     {
283
         $param = $this->param;
261
         $param = $this->param;
284
-        $userInfo = $this->userInfo;
262
+        $userId = $this->userInfo['id'];
285
         $types = $param['types'];
263
         $types = $param['types'];
286
-        $type = $param['type'] ? : 1;
287
-        $isSub = $param['isSub'] ? : '';
288
         if ($getCount == true) {
264
         if ($getCount == true) {
289
             $param['getCount'] = 1;
265
             $param['getCount'] = 1;
290
         }
266
         }
291
         unset($param['types']);
267
         unset($param['types']);
292
-        unset($param['type']);
293
-        unset($param['isSub']);
294
-        $customerModel = model('Customer');
295
-        $todayTime = getTimeByType('today');
296
-
297
-        $param['owner_user_id'] = !empty($isSub) ? ['in',getSubUserId(false, 0, $userInfo['id'])] : $userInfo['id'];
298
-
299
-        switch ($type) {
300
-            case '1' : 
301
-                $param['next_time'] = ['between',array($todayTime[0],$todayTime[1])];
302
-                $param['is_dealt'] = ['neq', 1];
303
-                break;
304
-            case '2' : 
305
-                $param['next_time'] = ['between',array(1,time())];
306
-                $param['is_dealt'] = ['neq', 1];
307
-                break;
308
-            case '3' : 
309
-                $param['last_time'] = ['between',array($todayTime[0],$todayTime[1])];
310
-                $param['is_dealt'] = ['eq', 1];
311
-                break;
312
-        }
313
-        $data = $customerModel->getDataList($param);
268
+        $param['user_id'] = $userId;
269
+        $messageLogic= new MessageLogic();
270
+        $data = $messageLogic->remindCustomer($param);
314
         if ($types == 'list') {
271
         if ($types == 'list') {
315
             return resultArray(['data' => $data]);
272
             return resultArray(['data' => $data]);
316
         }
273
         }
317
         return $data;
274
         return $data;
318
     }
275
     }
319
-
276
+    
320
     /**
277
     /**
321
      * 今日需联系商机
278
      * 今日需联系商机
322
      *
279
      *
331
         $param     = $this->param;
288
         $param     = $this->param;
332
         $userId    = $this->userInfo['id'];
289
         $userId    = $this->userInfo['id'];
333
         $types     = $param['types'];
290
         $types     = $param['types'];
334
-        $type      = !empty($param['type'])  ? $param['type']  : 1;
335
-        $isSub     = !empty($param['isSub']) ? $param['isSub'] : 0;
336
-        $todayTime = getTimeByType('today');
337
         unset($param['types']);
291
         unset($param['types']);
338
-        unset($param['type']);
339
-        unset($param['isSub']);
340
-
341
         if ($getCount == true) $param['getCount'] = 1;
292
         if ($getCount == true) $param['getCount'] = 1;
342
-
343
-        $businessModel = new \app\crm\model\Business();
344
-
345
-        # 负责人
346
-        $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userId)] : $userId;
347
-        # 类型:1今日需联系;2已逾期;3已联系
348
-        switch ($type) {
349
-            case '1' :
350
-                $param['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
351
-                $param['is_dealt'] = ['neq', 1];
352
-                break;
353
-            case '2' :
354
-                $param['next_time'] = ['between', [1, time()]];
355
-                $param['is_dealt'] = ['neq', 1];
356
-                break;
357
-            case '3' :
358
-                $param['last_time'] = ['between', [$todayTime[0], $todayTime[1]]];
359
-                $param['is_dealt'] = ['eq', 1];
360
-                break;
361
-        }
362
-
293
+        $messageLogic= new MessageLogic();
363
         $param['user_id'] = $userId;
294
         $param['user_id'] = $userId;
364
-        $data = $businessModel->getDataList($param);
365
-
295
+        $data = $messageLogic->todayBusiness($param);
296
+        
366
         if ($types == 'list') return resultArray(['data' => $data]);
297
         if ($types == 'list') return resultArray(['data' => $data]);
367
-
298
+        
368
         return $data;
299
         return $data;
369
     }
300
     }
370
-
301
+    
371
     /**
302
     /**
372
      * 分配给我的线索
303
      * 分配给我的线索
373
      * @author Michael_xu
304
      * @author Michael_xu
374
-     * @return 
305
+     * @return
375
      */
306
      */
376
     public function followLeads($getCount = false)
307
     public function followLeads($getCount = false)
377
     {
308
     {
378
         $param = $this->param;
309
         $param = $this->param;
379
         $userInfo = $this->userInfo;
310
         $userInfo = $this->userInfo;
380
         $types = $param['types'];
311
         $types = $param['types'];
381
-        $type = $param['type'] ? : 1;
382
-        $isSub = $param['isSub'] ? : '';
383
         unset($param['types']);
312
         unset($param['types']);
384
-        unset($param['type']);        
385
-        unset($param['isSub']);        
386
-        $leadsModel = model('Leads');
387
-
388
         if ($getCount == true) $param['getCount'] = 1;
313
         if ($getCount == true) $param['getCount'] = 1;
389
-
390
-        $param['owner_user_id'] = $userInfo['id'];
391
-
392
-        switch ($type) {
393
-            case '1' :
394
-                $param['follow'] = [['neq','已跟进'], null, 'or'];
395
-                $param['is_allocation'] = 1;
396
-                break;
397
-            case '2' :
398
-                $param['follow'] = ['eq','已跟进'];
399
-                $param['is_allocation'] = 1;
400
-                break;
401
-        }
402
         $param['user_id'] = $userInfo['id'];
314
         $param['user_id'] = $userInfo['id'];
403
-        $data = $leadsModel->getDataList($param);
315
+        $messageLogic=new MessageLogic();
316
+        $data = $messageLogic->followLeads($param);
404
         if ($types == 'list') {
317
         if ($types == 'list') {
405
             return resultArray(['data' => $data]);
318
             return resultArray(['data' => $data]);
406
         }
319
         }
407
-        return $data;        
408
-    }        
409
-
320
+        return $data;
321
+    }
322
+    
410
     /**
323
     /**
411
      * 分配给我的客户
324
      * 分配给我的客户
412
      * @author Michael_xu
325
      * @author Michael_xu
413
-     * @return 
326
+     * @return
414
      */
327
      */
415
     public function followCustomer($getCount = false)
328
     public function followCustomer($getCount = false)
416
     {
329
     {
417
         $param = $this->param;
330
         $param = $this->param;
418
         $userInfo = $this->userInfo;
331
         $userInfo = $this->userInfo;
419
         $types = $param['types'];
332
         $types = $param['types'];
420
-        $type = $param['type'] ? : 1;
421
-        $isSub = $param['isSub'] ? : '';
422
         if ($getCount == true) {
333
         if ($getCount == true) {
423
             $param['getCount'] = 1;
334
             $param['getCount'] = 1;
424
-        }        
425
-        unset($param['types']);
426
-        unset($param['type']);  
427
-        unset($param['isSub']);         
428
-        $customerModel = model('Customer');
429
-
430
-        $param['owner_user_id'] = $userInfo['id'];
431
-
432
-        switch ($type) {
433
-            case '1' :
434
-                $param['follow'] = [['eq','待跟进'], null, 'or'];
435
-                $param['is_allocation'] = 1;
436
-                break;
437
-            case '2' :
438
-                $param['follow'] = ['eq','已跟进'];
439
-                $param['is_allocation'] = 1;
440
-                break;
441
         }
335
         }
442
-        $data = $customerModel->getDataList($param);
336
+        unset($param['types']);
337
+        $messageLogic=new MessageLogic();
338
+        $param['user_id'] = $userInfo['id'];
339
+        $data = $messageLogic->followCustomer($param);
443
         if ($types == 'list') {
340
         if ($types == 'list') {
444
             return resultArray(['data' => $data]);
341
             return resultArray(['data' => $data]);
445
         }
342
         }
446
         return $data;
343
         return $data;
447
     }
344
     }
448
-
345
+    
449
     /**
346
     /**
450
      * 待审核合同
347
      * 待审核合同
451
      *
348
      *
457
         $param = $this->param;
354
         $param = $this->param;
458
         $userInfo = $this->userInfo;
355
         $userInfo = $this->userInfo;
459
         $types = $param['types'];
356
         $types = $param['types'];
460
-        $type = $param['type'] ? : 1;
461
-        $isSub = $param['isSub'] ? : '';
462
         unset($param['types']);
357
         unset($param['types']);
463
-        unset($param['type']); 
464
-        unset($param['isSub']);        
465
-        $contractModel = model('Contract');
466
         if ($getCount == true) {
358
         if ($getCount == true) {
467
             $param['getCount'] = 1;
359
             $param['getCount'] = 1;
468
         }
360
         }
469
-
470
-        switch ($type) {
471
-            case '1' : 
472
-                $param['check_status'] = ['lt','2']; 
473
-                $param['check_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
474
-                # 要提醒的合同ID
475
-                $contractIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_contract'], 'user_id' => ['eq', $userInfo['id']]])->column('types_id');
476
-                $param['contractIdArray'] = !empty($contractIdArray) ? $contractIdArray : -1;
477
-                break;
478
-            case '2' :
479
-                $param['flow_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
480
-                break;
481
-        }
361
+        $messageLogic=new MessageLogic();
482
         $param['user_id'] = $userInfo['id'];
362
         $param['user_id'] = $userInfo['id'];
483
-        $data = $contractModel->getDataList($param);
484
-
363
+        $data = $messageLogic->checkContract($param);
485
         if ($types == 'list') {
364
         if ($types == 'list') {
486
             return resultArray(['data' => $data]);
365
             return resultArray(['data' => $data]);
487
         }
366
         }
488
         return $data;
367
         return $data;
489
     }
368
     }
490
-
369
+    
491
     /**
370
     /**
492
      * 待审核回款
371
      * 待审核回款
493
      * @author Michael_xu
372
      * @author Michael_xu
494
-     * @return 
373
+     * @return
495
      */
374
      */
496
     public function checkReceivables($getCount = false)
375
     public function checkReceivables($getCount = false)
497
     {
376
     {
498
         $param = $this->param;
377
         $param = $this->param;
499
         $userInfo = $this->userInfo;
378
         $userInfo = $this->userInfo;
500
         $types = $param['types'];
379
         $types = $param['types'];
501
-        $type = $param['type'] ? : 1;
502
-        $isSub = $param['isSub'] ? : '';
503
         unset($param['types']);
380
         unset($param['types']);
504
-        unset($param['type']);
505
-        unset($param['isSub']);
506
-        $receivablesModel = model('Receivables');
507
         if ($getCount == true) $param['getCount'] = 1;
381
         if ($getCount == true) $param['getCount'] = 1;
508
-
509
-        switch ($type) {
510
-            case '1' :
511
-                # 待审核、审核中
512
-                $param['check_status'] = ['lt','2']; 
513
-                $param['check_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
514
-                # 要提醒的回款ID
515
-                $receivablesIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_receivables'], 'user_id' => ['eq', $userInfo['id']]])->column('types_id');
516
-                $param['receivablesIdArray'] = !empty($receivablesIdArray) ? $receivablesIdArray : -1;
517
-                break;
518
-            case '2' :
519
-                # 全部
520
-                $param['flow_user_id'] = ['like',',%'.$userInfo['id'].'%,'];
521
-                break;
522
-        }
382
+        $messageLogic=new MessageLogic();
523
         $param['user_id'] = $userInfo['id'];
383
         $param['user_id'] = $userInfo['id'];
524
-        $data = $receivablesModel->getDataList($param);
384
+        $data = $messageLogic->checkReceivables($param);
525
         if ($types == 'list') {
385
         if ($types == 'list') {
526
             return resultArray(['data' => $data]);
386
             return resultArray(['data' => $data]);
527
         }
387
         }
528
         return $data;
388
         return $data;
529
     }
389
     }
530
-
390
+    
531
     /**
391
     /**
532
      * 待审核发票
392
      * 待审核发票
533
      *
393
      *
540
         $param  = $this->param;
400
         $param  = $this->param;
541
         $userId = $this->userInfo['id'];
401
         $userId = $this->userInfo['id'];
542
         $types  = $param['types'];
402
         $types  = $param['types'];
543
-        $type   = !empty($param['type'])  ? $param['type']  : 1;
544
-        $isSub  = !empty($param['isSub']) ? $param['isSub'] : 0;
545
         if ($getCount == true) $param['getCount'] = 1;
403
         if ($getCount == true) $param['getCount'] = 1;
546
-
547
         # 清除与模型无关的数据
404
         # 清除与模型无关的数据
548
         unset($param['types']);
405
         unset($param['types']);
549
-        unset($param['type']);
550
-        unset($param['isSub']);
551
-
552
-        switch ($type) {
553
-            case '1' :
554
-                # 待审核、审核中
555
-                $param['check_status']  = ['lt', 2];
556
-                $param['check_user_id'] = ['like', ',%'. $userId .'%,'];
557
-                # 要提醒的发票ID
558
-                $invoiceIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'user_id' => ['eq', $userId]])->column('types_id');
559
-                $param['invoiceIdArray'] = !empty($invoiceIdArray) ? $invoiceIdArray : -1;
560
-                $param['dealt'] = 1;
561
-                break;
562
-            case '2' :
563
-                # 全部
564
-                $param['flow_user_id'] = ['like', ',%'. $userId .'%,'];
565
-                $param['dealt'] = 1;
566
-                break;
567
-        }
568
-
569
-        $data = (new InvoiceLogic())->index($param);
570
-
406
+        $param['user_id'] = $userId;
407
+        $messageLogic=new MessageLogic();
408
+        $data = $messageLogic->checkInvoice($param);
409
+        
571
         if ($types == 'list') return resultArray(['data' => $data]);
410
         if ($types == 'list') return resultArray(['data' => $data]);
572
-
411
+        
573
         return $data;
412
         return $data;
574
     }
413
     }
575
-
414
+    
576
     /**
415
     /**
577
      * 待回款提醒
416
      * 待回款提醒
578
      * @author Michael_xu
417
      * @author Michael_xu
579
-     * @return 
418
+     * @return
580
      */
419
      */
581
     public function remindReceivablesPlan($getCount = false)
420
     public function remindReceivablesPlan($getCount = false)
582
     {
421
     {
586
         $type     = $param['type']  ? : 1;
425
         $type     = $param['type']  ? : 1;
587
         $isSub    = $param['isSub'] ? : '';
426
         $isSub    = $param['isSub'] ? : '';
588
         unset($param['types']);
427
         unset($param['types']);
589
-        unset($param['type']);  
590
-        unset($param['isSub']);        
428
+        unset($param['type']);
429
+        unset($param['isSub']);
591
         $receivablesPlanModel = model('ReceivablesPlan');
430
         $receivablesPlanModel = model('ReceivablesPlan');
592
-
431
+        
593
         if ($getCount == true) $param['getCount'] = 1;
432
         if ($getCount == true) $param['getCount'] = 1;
594
-
433
+        
595
         $param['owner_user_id'] = $userInfo['id'];
434
         $param['owner_user_id'] = $userInfo['id'];
596
         if ($isSub) {
435
         if ($isSub) {
597
-            $param['owner_user_id'] = array('in',getSubUserId(false));
598
-        }       
436
+            $param['owner_user_id'] = ['in', getSubUserId(false)];
437
+        }
599
         switch ($type) {
438
         switch ($type) {
600
             case '1' :
439
             case '1' :
601
                 $param['receivables_id'] = 0;
440
                 $param['receivables_id'] = 0;
602
-                $param['check_status'] = array('lt',2);
603
-                $param['remind_date'] = array('elt',date('Y-m-d',time()));
604
-                $param['return_date'] = array('egt',date('Y-m-d',time()));
441
+                $param['check_status'] = ['lt', 2];
442
+                $param['remind_date'] = ['elt', date('Y-m-d', time())];
443
+                $param['return_date'] = ['egt', date('Y-m-d', time())];
605
                 $param['types'] = 1;
444
                 $param['types'] = 1;
606
                 $param['is_dealt'] = 0;
445
                 $param['is_dealt'] = 0;
607
                 break;
446
                 break;
612
                 break;
451
                 break;
613
             case '3' :
452
             case '3' :
614
                 $param['receivables_id'] = 0;
453
                 $param['receivables_id'] = 0;
615
-                $param['remind_date'] = array('lt',date('Y-m-d',time()));
454
+                $param['return_date'] = ['lt', date('Y-m-d', time())];
616
                 break;
455
                 break;
617
         }
456
         }
618
         $data = $receivablesPlanModel->getDataList($param);
457
         $data = $receivablesPlanModel->getDataList($param);
621
         }
460
         }
622
         return $data;
461
         return $data;
623
     }
462
     }
624
-
463
+    
625
     /**
464
     /**
626
      * 即将到期合同
465
      * 即将到期合同
627
      * @author Michael_xu
466
      * @author Michael_xu
628
-     * @return 
467
+     * @return
629
      */
468
      */
630
     public function endContract($getCount = false)
469
     public function endContract($getCount = false)
631
     {
470
     {
636
         $isSub = $param['isSub'] ? : '';
475
         $isSub = $param['isSub'] ? : '';
637
         if ($getCount == true) $param['getCount'] = 1;
476
         if ($getCount == true) $param['getCount'] = 1;
638
         unset($param['types']);
477
         unset($param['types']);
639
-        unset($param['type']);  
640
-        unset($param['isSub']);       
478
+        unset($param['type']);
479
+        unset($param['isSub']);
641
         $contractModel = model('Contract');
480
         $contractModel = model('Contract');
642
         $configModel = new \app\crm\model\ConfigData();
481
         $configModel = new \app\crm\model\ConfigData();
643
         $configInfo = $configModel->getData();
482
         $configInfo = $configModel->getData();
644
         $expireDay = $configInfo['contract_day'] ? : '7';
483
         $expireDay = $configInfo['contract_day'] ? : '7';
645
-
484
+        // 合同到期不提醒
485
+        if (empty($configInfo['contract_config'])) return resultArray(['data' => []]);
646
         $param['owner_user_id'] = $userInfo['id'];
486
         $param['owner_user_id'] = $userInfo['id'];
647
         if ($isSub) {
487
         if ($isSub) {
648
             $param['owner_user_id'] = array('in',getSubUserId(false));
488
             $param['owner_user_id'] = array('in',getSubUserId(false));
649
-        }         
489
+        }
650
         switch ($type) {
490
         switch ($type) {
651
             case '1' :
491
             case '1' :
652
                 $param['end_time'] = array('between',array(date('Y-m-d',time()),date('Y-m-d',time()+86400*$expireDay)));
492
                 $param['end_time'] = array('between',array(date('Y-m-d',time()),date('Y-m-d',time()+86400*$expireDay)));
659
             return resultArray(['data' => $data]);
499
             return resultArray(['data' => $data]);
660
         }
500
         }
661
         return $data;
501
         return $data;
662
-    }  
663
-
502
+    }
503
+    
664
     /**
504
     /**
665
      * 待进入客户池
505
      * 待进入客户池
666
      * @author Michael_xu
506
      * @author Michael_xu
667
-     * @return 
507
+     * @return
668
      */
508
      */
669
     public function remindCustomer($getCount = false)
509
     public function remindCustomer($getCount = false)
670
     {
510
     {
671
         $customerModel = model('Customer');
511
         $customerModel = model('Customer');
672
-
512
+        
673
         $param = $this->param;
513
         $param = $this->param;
674
         $userInfo = $this->userInfo;
514
         $userInfo = $this->userInfo;
675
         $types = $param['types'];
515
         $types = $param['types'];
680
         unset($param['isSub']);
520
         unset($param['isSub']);
681
         unset($param['deal_status']);
521
         unset($param['deal_status']);
682
         unset($param['owner_user_id']);
522
         unset($param['owner_user_id']);
683
-
523
+        
684
         # 负责人
524
         # 负责人
685
         $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userInfo['id'])] : $userInfo['id'];
525
         $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userInfo['id'])] : $userInfo['id'];
686
-
526
+        
687
         # 是否提醒
527
         # 是否提醒
688
         $data = [];
528
         $data = [];
689
         $remind = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
529
         $remind = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
703
         }
543
         }
704
         return $data;
544
         return $data;
705
     }
545
     }
706
-
546
+    
707
     /**
547
     /**
708
      * 待回访合同
548
      * 待回访合同
709
      *
549
      *
722
         if ($getCount == true) $param['getCount'] = 1;
562
         if ($getCount == true) $param['getCount'] = 1;
723
         unset($param['isSub']);
563
         unset($param['isSub']);
724
         unset($param['types']);
564
         unset($param['types']);
725
-
565
+        
726
         $param['is_visit']     = 0; # 未回访
566
         $param['is_visit']     = 0; # 未回访
727
         $param['check_status'] = 2; # 审核通过
567
         $param['check_status'] = 2; # 审核通过
728
-
568
+        
729
         $contractModel = new \app\crm\model\Contract();
569
         $contractModel = new \app\crm\model\Contract();
730
-
570
+        
731
         # 负责人
571
         # 负责人
732
         $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId;
572
         $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId;
733
-
573
+        
734
         $param['user_id'] = $userId;
574
         $param['user_id'] = $userId;
735
         $data = $contractModel->getDataList($param);
575
         $data = $contractModel->getDataList($param);
736
-
576
+        
737
         if ($types == 'list') return resultArray(['data' => $data]);
577
         if ($types == 'list') return resultArray(['data' => $data]);
738
-
578
+        
739
         return $data;
579
         return $data;
740
     }
580
     }
741
-
581
+    
742
     /**
582
     /**
743
      * 全部标记已处理
583
      * 全部标记已处理
744
      *
584
      *
752
         $typeId = !empty($this->param['type_id']) ? $this->param['type_id'] : '';
592
         $typeId = !empty($this->param['type_id']) ? $this->param['type_id'] : '';
753
         $isSub  = !empty($this->param['isSub'])   ? $this->param['isSub']   : 0;
593
         $isSub  = !empty($this->param['isSub'])   ? $this->param['isSub']   : 0;
754
         $userId = $this->userInfo['id'];
594
         $userId = $this->userInfo['id'];
755
-
595
+        
756
         if (empty($type)) return resultArray(['error' => '缺少模块类型参数']);
596
         if (empty($type)) return resultArray(['error' => '缺少模块类型参数']);
757
-
597
+        
758
         # 获得今日开始和结束时间戳
598
         # 获得今日开始和结束时间戳
759
         $todayTime = getTimeByType('today');
599
         $todayTime = getTimeByType('today');
760
-
600
+        
761
         # 处理今日需联系线索、客户、商机
601
         # 处理今日需联系线索、客户、商机
762
         if (in_array($type, ['todayLeads', 'todayCustomer', 'todayBusiness'])) {
602
         if (in_array($type, ['todayLeads', 'todayCustomer', 'todayBusiness'])) {
763
             # 负责人
603
             # 负责人
766
             $where['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
606
             $where['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
767
             # 是否已处理(联系)
607
             # 是否已处理(联系)
768
             $where['is_dealt'] = 0;
608
             $where['is_dealt'] = 0;
769
-
609
+            
770
             # 线索
610
             # 线索
771
             if ($type == 'todayLeads') {
611
             if ($type == 'todayLeads') {
772
                 $leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id');
612
                 $leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id');
794
                 ]);
634
                 ]);
795
             }
635
             }
796
         }
636
         }
797
-
637
+        
798
         # 处理分配给我的线索、客户
638
         # 处理分配给我的线索、客户
799
         if (in_array($type, ['followLeads', 'followCustomer'])) {
639
         if (in_array($type, ['followLeads', 'followCustomer'])) {
800
             $where['owner_user_id'] = $userId;
640
             $where['owner_user_id'] = $userId;
801
             $where['follow']        = [['neq','已跟进'], null, 'or'];
641
             $where['follow']        = [['neq','已跟进'], null, 'or'];
802
             $where['is_allocation'] = 1;
642
             $where['is_allocation'] = 1;
803
-
643
+            
804
             # 线索
644
             # 线索
805
             if ($type == 'followLeads') {
645
             if ($type == 'followLeads') {
806
                 $leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id');
646
                 $leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id');
812
                 Db::name('crm_customer')->whereIn('customer_id', $customerId)->update(['follow' => '已跟进']);
652
                 Db::name('crm_customer')->whereIn('customer_id', $customerId)->update(['follow' => '已跟进']);
813
             }
653
             }
814
         }
654
         }
815
-
655
+        
816
         # 处理待审核合同、回款、发票
656
         # 处理待审核合同、回款、发票
817
         if (in_array($type, ['checkContract', 'checkReceivables', 'checkInvoice'])) {
657
         if (in_array($type, ['checkContract', 'checkReceivables', 'checkInvoice'])) {
818
             $where['check_status']  = ['lt','2'];
658
             $where['check_status']  = ['lt','2'];
819
             $where['check_user_id'] = ['like',',%' . $userId . '%,'];
659
             $where['check_user_id'] = ['like',',%' . $userId . '%,'];
820
-
660
+            
821
             # 合同
661
             # 合同
822
             if ($type == 'checkContract') {
662
             if ($type == 'checkContract') {
823
                 $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
663
                 $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
833
                 $invoiceId = !empty($typeId) ? $typeId : Db::name('crm_invoice')->where($where)->column('invoice_id');
673
                 $invoiceId = !empty($typeId) ? $typeId : Db::name('crm_invoice')->where($where)->column('invoice_id');
834
                 db('crm_dealt_relation')->where('user_id', $userId)->where('types', 'crm_invoice')->whereIn('types_id', $invoiceId)->delete();
674
                 db('crm_dealt_relation')->where('user_id', $userId)->where('types', 'crm_invoice')->whereIn('types_id', $invoiceId)->delete();
835
             }
675
             }
836
-
676
+            
837
         }
677
         }
838
-
678
+        
839
         # 处理到期合同
679
         # 处理到期合同
840
         if ($type == 'endContract') {
680
         if ($type == 'endContract') {
841
             $configModel = new \app\crm\model\ConfigData();
681
             $configModel = new \app\crm\model\ConfigData();
842
             $configInfo  = $configModel->getData();
682
             $configInfo  = $configModel->getData();
843
             $expireDay   = $configInfo['contract_day'] ? : '7';
683
             $expireDay   = $configInfo['contract_day'] ? : '7';
844
-
684
+            
845
             $where['owner_user_id'] = $userId;
685
             $where['owner_user_id'] = $userId;
846
             $where['end_time']      = ['between', [date('Y-m-d',time()), date('Y-m-d',time()+86400*$expireDay)]];
686
             $where['end_time']      = ['between', [date('Y-m-d',time()), date('Y-m-d',time()+86400*$expireDay)]];
847
             $where['expire_remind'] = 1;
687
             $where['expire_remind'] = 1;
848
-
688
+            
849
             $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
689
             $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
850
             Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['expire_remind' => 0]);
690
             Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['expire_remind' => 0]);
851
         }
691
         }
852
-
692
+        
853
         # 处理待回访合同
693
         # 处理待回访合同
854
         if ($type == 'returnVisitRemind') {
694
         if ($type == 'returnVisitRemind') {
855
             $where['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId; # 负责人
695
             $where['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId; # 负责人
856
             $where['is_visit']      = 0; # 未回访
696
             $where['is_visit']      = 0; # 未回访
857
             $where['check_status']  = 2; # 审核通过
697
             $where['check_status']  = 2; # 审核通过
858
-
698
+            
859
             $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
699
             $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
860
             Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['is_visit' => 1]);
700
             Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['is_visit' => 1]);
861
         }
701
         }
862
-
702
+        
863
         # 处理待进入公海
703
         # 处理待进入公海
864
         if ($type == 'putInPoolRemind') {
704
         if ($type == 'putInPoolRemind') {
865
             if (!empty($typeId)) {
705
             if (!empty($typeId)) {
883
                 }
723
                 }
884
             }
724
             }
885
         }
725
         }
886
-
726
+        
887
         # 带回款提醒
727
         # 带回款提醒
888
         if ($type == 'remindReceivablesPlan') {
728
         if ($type == 'remindReceivablesPlan') {
889
             $planId = [];
729
             $planId = [];
906
             }
746
             }
907
             if (!empty($planId)) db('crm_receivables_plan')->whereIn('plan_id', $planId)->update(['is_dealt' => 1]);
747
             if (!empty($planId)) db('crm_receivables_plan')->whereIn('plan_id', $planId)->update(['is_dealt' => 1]);
908
         }
748
         }
909
-
910
-
749
+        
750
+            cache::rm('todayLeadsCount'.$userId);
751
+            cache::rm('todayCustomerCount'.$userId);
752
+            cache::rm('todayBusinessCount'.$userId);
753
+            cache::rm('followLeadsCount'.$userId);
754
+            cache::rm('followCustomerCount'.$userId);
755
+            cache::rm('checkContractCount'.$userId);
756
+            cache::rm('checkReceivablesCount'.$userId);
757
+            cache::rm('checkInvoiceCount'.$userId);
758
+            cache::rm('remindReceivablesPlanCount'.$userId);
759
+            cache::rm('visitContractCount'.$userId);
760
+            cache::rm('endContractCount'.$userId);
761
+            cache::rm('remindCustomerCount'.$userId);
762
+
763
+            cache::rm('todayLeadsTime'.$userId);
764
+            cache::rm('todayCustomerTime'.$userId);
765
+            cache::rm('todayBusinessTime'.$userId);
766
+            cache::rm('followLeadsTime'.$userId);
767
+            cache::rm('followCustomerTime'.$userId);
768
+            cache::rm('checkContractTime'.$userId);
769
+            cache::rm('checkReceivablesTime'.$userId);
770
+            cache::rm('checkInvoiceTime'.$userId);
771
+            cache::rm('remindReceivablesPlanTime'.$userId);
772
+            cache::rm('visitContractTime'.$userId);
773
+            cache::rm('endContractTime'.$userId);
774
+            cache::rm('remindCustomerTime'.$userId);
911
         return resultArray(['data' => '操作成功!']);
775
         return resultArray(['data' => '操作成功!']);
912
     }
776
     }
913
 }
777
 }

+ 19
- 29
application/crm/controller/Product.php Bestand weergeven

187
      */ 
187
      */ 
188
     public function excelDownload($save_path = '') 
188
     public function excelDownload($save_path = '') 
189
     {
189
     {
190
+        # 下次升级
190
         $param = $this->param;
191
         $param = $this->param;
191
         $userInfo = $this->userInfo;
192
         $userInfo = $this->userInfo;
192
         $excelModel = new \app\admin\model\Excel();
193
         $excelModel = new \app\admin\model\Excel();
193
-    
194
+
194
         // 导出的字段列表
195
         // 导出的字段列表
195
         $fieldModel = new \app\admin\model\Field();
196
         $fieldModel = new \app\admin\model\Field();
196
         $fieldParam['types'] = 'crm_product';
197
         $fieldParam['types'] = 'crm_product';
197
         $fieldParam['action'] = 'excel';
198
         $fieldParam['action'] = 'excel';
198
         $field_list = $fieldModel->field($fieldParam);
199
         $field_list = $fieldModel->field($fieldParam);
200
+        $field=[1=>[
201
+            'field'=>'owner_user_id',
202
+            'types'=>'crm_product',
203
+            'name'=>'负责人',
204
+            'form_type'=>'user',
205
+            'default_value'=>'',
206
+            'is_null' => 1,
207
+            'input_tips' =>'',
208
+            'setting' => Array(),
209
+            'is_hidden'=>0,
210
+            'writeStatus' => 1,
211
+            'value' => '']
212
+        ];
213
+        $first_array = array_splice($field_list, 2,0, $field);
199
         $excelModel->excelImportDownload($field_list, 'crm_product', $save_path);
214
         $excelModel->excelImportDownload($field_list, 'crm_product', $save_path);
200
-        # 下次升级
201
-//        $param = $this->param;
202
-//        $userInfo = $this->userInfo;
203
-//        $excelModel = new \app\admin\model\Excel();
204
-//
205
-//        // 导出的字段列表
206
-//        $fieldModel = new \app\admin\model\Field();
207
-//        $fieldParam['types'] = 'crm_product';
208
-//        $fieldParam['action'] = 'excel';
209
-//        $field_list = $fieldModel->field($fieldParam);
210
-//        $field=[1=>[
211
-//            'field'=>'owner_user_id',
212
-//            'types'=>'crm_product',
213
-//            'name'=>'负责人',
214
-//            'form_type'=>'user',
215
-//            'default_value'=>'',
216
-//            'is_unique' => 1,
217
-//            'is_null' => 1,
218
-//            'input_tips' =>'',
219
-//            'setting' => Array(),
220
-//            'is_hidden'=>0,
221
-//            'writeStatus' => 1,
222
-//            'value' => '']
223
-//        ];
224
-//        $first_array = array_splice($field_list, 0, 2);
225
-//        $array = array_merge($first_array, $field, $field_list);
226
-//        $excelModel->excelImportDownload($array, 'crm_product', $save_path);
227
     }  
215
     }  
228
 
216
 
229
     /**
217
     /**
246
         $excelModel = new \app\admin\model\Excel();
234
         $excelModel = new \app\admin\model\Excel();
247
         // 导出的字段列表
235
         // 导出的字段列表
248
         $fieldModel = new \app\admin\model\Field();
236
         $fieldModel = new \app\admin\model\Field();
249
-        $field_list = $fieldModel->getIndexFieldConfig('crm_product', $userInfo['id']);
237
+        $field_list = $fieldModel->getIndexFieldConfig('crm_product', $userInfo['id'],'','excel');
250
         // 文件名
238
         // 文件名
251
         $file_name = '5kcrm_product_'.date('Ymd');
239
         $file_name = '5kcrm_product_'.date('Ymd');
252
         
240
         
337
             if ($res == count($delIds)) {
325
             if ($res == count($delIds)) {
338
                 // 事务提交
326
                 // 事务提交
339
                 ProductModel::commit();
327
                 ProductModel::commit();
328
+                // 删除客户扩展数据
329
+                db('crm_product_data')->whereIn('product_id', $delIds)->delete();
340
                 // 删除关联附件
330
                 // 删除关联附件
341
                 (new FileModel)->delRFileByModule('crm_product', $delIds);
331
                 (new FileModel)->delRFileByModule('crm_product', $delIds);
342
                 // 操作记录
332
                 // 操作记录

+ 4
- 2
application/crm/controller/ProductCategory.php Bestand weergeven

86
         $categoryModel = model('ProductCategory');
86
         $categoryModel = model('ProductCategory');
87
         $param = $this->param;
87
         $param = $this->param;
88
         $userInfo = $this->userInfo;
88
         $userInfo = $this->userInfo;
89
-
89
+        $param['user_id']=$userInfo['id'];
90
         $res = $categoryModel->updateDataById($param, $param['id']); 
90
         $res = $categoryModel->updateDataById($param, $param['id']); 
91
         if ($res) {
91
         if ($res) {
92
             return resultArray(['data' => '编辑成功']);
92
             return resultArray(['data' => '编辑成功']);
105
     {
105
     {
106
         $categoryModel = model('ProductCategory');
106
         $categoryModel = model('ProductCategory');
107
         $param = $this->param;
107
         $param = $this->param;
108
-        $data = $categoryModel->delDataById($param['id'], true);       
108
+        $userInfo=$this->userInfo;
109
+        $param['user_id']=$userInfo['id'];
110
+        $data = $categoryModel->delDataById($param, true);
109
         if (!$data) {
111
         if (!$data) {
110
             return resultArray(['error' => $categoryModel->getError()]);
112
             return resultArray(['error' => $categoryModel->getError()]);
111
         } 
113
         } 

+ 12
- 2
application/crm/controller/Receivables.php Bestand weergeven

348
             if (!$data) {
348
             if (!$data) {
349
                 return resultArray(['error' => $receivablesModel->getError()]);
349
                 return resultArray(['error' => $receivablesModel->getError()]);
350
             }
350
             }
351
+            // 删除回款扩展数据
352
+            db('crm_receivables_data')->whereIn('receivables_id', $delIds)->delete();
351
             //删除跟进记录
353
             //删除跟进记录
352
             $recordModel->delDataByTypes(7,$delIds);
354
             $recordModel->delDataByTypes(7,$delIds);
353
             # 删除附件
355
             # 删除附件
642
     public function count()
644
     public function count()
643
     {
645
     {
644
         if (empty($this->param['receivables_id'])) return resultArray(['error' => '参数错误!']);
646
         if (empty($this->param['receivables_id'])) return resultArray(['error' => '参数错误!']);
645
-        
647
+
648
+        $receivablesId = $this->param['receivables_id'];
649
+
650
+        # 团队成员
651
+        $receivables = Db::name('crm_receivables')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('receivables_id', $receivablesId)->find();
652
+        $receivables['ro_user_id'] = stringToArray($receivables['ro_user_id']);
653
+        $receivables['rw_user_id'] = stringToArray($receivables['rw_user_id']);
654
+        $receivables['owner_user_id'] = [$receivables['owner_user_id']];
655
+        $teamCount = array_filter(array_unique(array_merge($receivables['ro_user_id'], $receivables['rw_user_id'], $receivables['owner_user_id'])));
646
         # 附件
656
         # 附件
647
         $fileCount = Db::name('crm_receivables_file')->alias('receivables')->join('__ADMIN_FILE__ file', 'file.file_id = receivables.file_id', 'LEFT')->where('receivables_id', $this->param['receivables_id'])->count();
657
         $fileCount = Db::name('crm_receivables_file')->alias('receivables')->join('__ADMIN_FILE__ file', 'file.file_id = receivables.file_id', 'LEFT')->where('receivables_id', $this->param['receivables_id'])->count();
648
         
658
         
649
-        return resultArray(['data' => ['fileCount' => $fileCount]]);
659
+        return resultArray(['data' => ['fileCount' => $fileCount,'memberCount'      => count($teamCount)]]);
650
     }
660
     }
651
 }
661
 }

+ 4
- 0
application/crm/controller/ReceivablesPlan.php Bestand weergeven

61
         $userInfo = $this->userInfo;
61
         $userInfo = $this->userInfo;
62
         $param['create_user_id'] = $userInfo['id'];
62
         $param['create_user_id'] = $userInfo['id'];
63
         $param['owner_user_id'] = $userInfo['id'];
63
         $param['owner_user_id'] = $userInfo['id'];
64
+        $param['user_id'] = $userInfo['id'];
64
 
65
 
65
         $res = $receivablesPlanModel->createData($param);
66
         $res = $receivablesPlanModel->createData($param);
66
         if ($res) {
67
         if ($res) {
111
             header('Content-Type:application/json; charset=utf-8');
112
             header('Content-Type:application/json; charset=utf-8');
112
             exit(json_encode(['code'=>102,'error'=>'无权操作']));
113
             exit(json_encode(['code'=>102,'error'=>'无权操作']));
113
         }
114
         }
115
+        $param['user_id'] = $userInfo['id'];
114
         $res = $receivablesPlanModel->updateDataById($param, $param['id']);
116
         $res = $receivablesPlanModel->updateDataById($param, $param['id']);
115
         if ($res) {
117
         if ($res) {
116
             return resultArray(['data' => '编辑成功']);
118
             return resultArray(['data' => '编辑成功']);
153
             if (!$res) {
155
             if (!$res) {
154
                 return resultArray(['error' => model('ReceivablesPlan')->getError()]);
156
                 return resultArray(['error' => model('ReceivablesPlan')->getError()]);
155
             }
157
             }
158
+            // 删除回款计划扩展数据
159
+            db('crm_receivables_plan_data')->where('plan_id', $plan_id)->delete();
156
             return resultArray(['data' => '删除成功']);
160
             return resultArray(['data' => '删除成功']);
157
         } else {
161
         } else {
158
             return resultArray(['error'=>'参数错误']);
162
             return resultArray(['error'=>'参数错误']);

+ 150
- 54
application/crm/controller/Setting.php Bestand weergeven

38
             parent::_initialize();
38
             parent::_initialize();
39
         }
39
         }
40
     }
40
     }
41
-
41
+    
42
     /**
42
     /**
43
      * 客户相关配置
43
      * 客户相关配置
44
      *
44
      *
63
             return resultArray(['error' => $configModel->getError()]);
63
             return resultArray(['error' => $configModel->getError()]);
64
         }
64
         }
65
     }
65
     }
66
-
66
+    
67
     /**
67
     /**
68
      * 客户相关配置(详情)
68
      * 客户相关配置(详情)
69
      *
69
      *
75
         $data = $configModel->getData();
75
         $data = $configModel->getData();
76
         return resultArray(['data' => $data]);
76
         return resultArray(['data' => $data]);
77
     }
77
     }
78
-
78
+    
79
     /**
79
     /**
80
      * 相关团队列表
80
      * 相关团队列表
81
      *
81
      *
107
             case 'crm_contract' :
107
             case 'crm_contract' :
108
                 $dataModel = new \app\crm\model\Contract();
108
                 $dataModel = new \app\crm\model\Contract();
109
                 break;
109
                 break;
110
+            case 'crm_receivables' :
111
+                $dataModel = new \app\crm\model\Receivables();
112
+                break;
110
         }
113
         }
111
         $resData = $dataModel->getDataById($param['types_id']);
114
         $resData = $dataModel->getDataById($param['types_id']);
112
         $ro_user_ids = $resData['ro_user_id'] ? array_filter(explode(',', $resData['ro_user_id'])) : []; //只读权限
115
         $ro_user_ids = $resData['ro_user_id'] ? array_filter(explode(',', $resData['ro_user_id'])) : []; //只读权限
113
         $rw_user_ids = $resData['rw_user_id'] ? array_filter(explode(',', $resData['rw_user_id'])) : []; //读写权限
116
         $rw_user_ids = $resData['rw_user_id'] ? array_filter(explode(',', $resData['rw_user_id'])) : []; //读写权限
114
-
117
+        
115
         $ro_user_arr = [];
118
         $ro_user_arr = [];
116
         $rw_user_arr = [];
119
         $rw_user_arr = [];
117
         $owner_user_arr = ['1' => ['user_id' => $resData['owner_user_id'], 'type' => 0, 'group_name' => '负责人', 'authority' => '负责人权限']]; //负责人
120
         $owner_user_arr = ['1' => ['user_id' => $resData['owner_user_id'], 'type' => 0, 'group_name' => '负责人', 'authority' => '负责人权限']]; //负责人
118
-
121
+        
119
         //转换为二维数组
122
         //转换为二维数组
120
         foreach ($ro_user_ids as $k => $v) {
123
         foreach ($ro_user_ids as $k => $v) {
121
             $ro_user_arr[$k]['user_id'] = $v;
124
             $ro_user_arr[$k]['user_id'] = $v;
123
             $ro_user_arr[$k]['group_name'] = '普通成员';
126
             $ro_user_arr[$k]['group_name'] = '普通成员';
124
             $ro_user_arr[$k]['authority'] = '只读';
127
             $ro_user_arr[$k]['authority'] = '只读';
125
         }
128
         }
126
-
129
+        
127
         foreach ($rw_user_ids as $k => $v) {
130
         foreach ($rw_user_ids as $k => $v) {
128
             $rw_user_arr[$k]['user_id'] = $v;
131
             $rw_user_arr[$k]['user_id'] = $v;
129
             $rw_user_arr[$k]['type'] = 2;
132
             $rw_user_arr[$k]['type'] = 2;
130
             $rw_user_arr[$k]['group_name'] = '普通成员';
133
             $rw_user_arr[$k]['group_name'] = '普通成员';
131
             $rw_user_arr[$k]['authority'] = '读写';
134
             $rw_user_arr[$k]['authority'] = '读写';
132
         }
135
         }
133
-
136
+        
134
         $user_list = array_merge($owner_user_arr, $rw_user_arr, $ro_user_arr);
137
         $user_list = array_merge($owner_user_arr, $rw_user_arr, $ro_user_arr);
135
         $new_user_list = [];
138
         $new_user_list = [];
139
+        $types_data = ['crm_leads' => 6, 'crm_customer' => 1, 'crm_contacts' => 2, 'crm_business' => 3, 'crm_contract' => 4, 'crm_receivables' => 5];
136
         foreach ($user_list as $k => $v) {
140
         foreach ($user_list as $k => $v) {
137
             if ($v['user_id']) {
141
             if ($v['user_id']) {
138
                 $userInfo = [];
142
                 $userInfo = [];
140
                 $userInfo['group_name'] = $v['group_name'];
144
                 $userInfo['group_name'] = $v['group_name'];
141
                 $userInfo['authority'] = $v['authority'];
145
                 $userInfo['authority'] = $v['authority'];
142
                 $userInfo['type'] = $v['type'];
146
                 $userInfo['type'] = $v['type'];
147
+                $userInfo['target_time'] = db('crm_team')->where(['team_user_id' => ['in', $v], 'target_id' => $param['types_id'], 'types' => $types_data[$param['types']]])->value('target_time') ? date('Y-m-d', db('crm_team')->where(['team_user_id' => ['in', $v], 'target_id' => $param['types_id'], 'types' => $types_data[$param['types']]])->value('target_time')) : '无限';
143
                 $new_user_list[] = $userInfo;
148
                 $new_user_list[] = $userInfo;
144
             }
149
             }
145
         }
150
         }
146
         return resultArray(['data' => $new_user_list]);
151
         return resultArray(['data' => $new_user_list]);
147
     }
152
     }
148
-
153
+    
149
     /**
154
     /**
150
      * 退出团队
155
      * 退出团队
151
      *
156
      *
162
         if (!in_array($this->param['types'], ['crm_customer', 'crm_contacts', 'crm_business', 'crm_contract'])) {
167
         if (!in_array($this->param['types'], ['crm_customer', 'crm_contacts', 'crm_business', 'crm_contract'])) {
163
             return resultArray(['error' => '参数错误']);
168
             return resultArray(['error' => '参数错误']);
164
         }
169
         }
165
-
170
+        
166
         $userId = $this->userInfo['id'];
171
         $userId = $this->userInfo['id'];
167
-
172
+        
168
         $primaryKey = ['crm_customer' => 'customer_id', 'crm_contacts' => 'contacts_id', 'crm_business' => 'business_id', 'crm_contract' => 'contract_id'];
173
         $primaryKey = ['crm_customer' => 'customer_id', 'crm_contacts' => 'contacts_id', 'crm_business' => 'business_id', 'crm_contract' => 'contract_id'];
169
-
174
+        
170
         $data = Db::name($this->param['types'])->field([$primaryKey[$this->param['types']], 'ro_user_id', 'rw_user_id', 'owner_user_id,name'])
175
         $data = Db::name($this->param['types'])->field([$primaryKey[$this->param['types']], 'ro_user_id', 'rw_user_id', 'owner_user_id,name'])
171
             ->where($primaryKey[$this->param['types']], $this->param['types_id'])->find();
176
             ->where($primaryKey[$this->param['types']], $this->param['types_id'])->find();
172
-
177
+        
173
         if ($data['owner_user_id'] == $userId) return resultArray(['error' => '负责人不能退出团队!']);
178
         if ($data['owner_user_id'] == $userId) return resultArray(['error' => '负责人不能退出团队!']);
174
-
175
-
179
+        
180
+        
176
         $data[$primaryKey[$this->param['types']]] = $this->param['types_id'];
181
         $data[$primaryKey[$this->param['types']]] = $this->param['types_id'];
177
         $data['ro_user_id'] = str_replace(',' . $userId, '', $data['ro_user_id']);
182
         $data['ro_user_id'] = str_replace(',' . $userId, '', $data['ro_user_id']);
178
         $data['rw_user_id'] = str_replace(',' . $userId, '', $data['rw_user_id']);
183
         $data['rw_user_id'] = str_replace(',' . $userId, '', $data['rw_user_id']);
179
-
184
+        
180
         if (!Db::name($this->param['types'])->update($data)) {
185
         if (!Db::name($this->param['types'])->update($data)) {
181
             return resultArray(['error' => '操作失败!']);
186
             return resultArray(['error' => '操作失败!']);
182
         }
187
         }
191
             case 'crm_contract':
196
             case 'crm_contract':
192
                 $type = Message::CONTRACT_END;
197
                 $type = Message::CONTRACT_END;
193
                 break;
198
                 break;
194
-
199
+            
195
         }
200
         }
196
         //站内信
201
         //站内信
197
         $send_user_id = stringToArray($userId);
202
         $send_user_id = stringToArray($userId);
207
         }
212
         }
208
         return resultArray(['data' => '操作成功!']);
213
         return resultArray(['data' => '操作成功!']);
209
     }
214
     }
210
-
215
+    
211
     /**
216
     /**
212
      * 相关团队创建
217
      * 相关团队创建
213
      *
218
      *
286
                     }
291
                     }
287
                     $message_type = Message::TEAM_CONTRACT;
292
                     $message_type = Message::TEAM_CONTRACT;
288
                     continue;
293
                     continue;
294
+                case 'crm_leads' :
295
+                    $typesName = '线索';
296
+                    $leadsModel = new \app\crm\model\Leads();
297
+                    $dataInfo = db('crm_leads')->where(['leads_id' => $v])->find();
298
+                    //判断权限
299
+                    $auth_user_ids = $userModel->getUserByPer('crm', 'leads', 'teamSave');
300
+                    if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
301
+                        $error = true;
302
+                        $errorMessage = "线索'" . $dataInfo['name'] . "'操作失败,错误原因:无权操作";
303
+                    }
304
+                    if (in_array($dataInfo['owner_user_id'], $param['user_id'])) {
305
+                        $error = true;
306
+                        $errorMessage = "线索'" . $dataInfo['name'] . "'操作失败,错误原因:不能对负责人进行添加或移出操作!";
307
+                    }
308
+                    $message_type = Message::TEAM_CONTRACT;
309
+                    continue;
310
+                case 'crm_receivables' :
311
+                    $typesName = '回款';
312
+                    $receivablesModel = new \app\crm\model\Receivables();
313
+                    $dataInfo = db('crm_receivables')->where(['receivables_id' => $v])->find();
314
+                    //判断权限
315
+                    $auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'teamSave');
316
+                    if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
317
+                        $error = true;
318
+                        $errorMessage = "回款'" . $dataInfo['name'] . "'操作失败,错误原因:无权操作";
319
+                    }
320
+                    if (in_array($dataInfo['owner_user_id'], $param['user_id'])) {
321
+                        $error = true;
322
+                        $errorMessage = "回款'" . $dataInfo['name'] . "'操作失败,错误原因:不能对负责人进行添加或移出操作!";
323
+                    }
324
+                    $message_type = Message::TEAM_CONTRACT;
325
+                    continue;
326
+                case 'crm_contacts' :
327
+                    $typesName = '联系人';
328
+                    $leadsModel = new \app\crm\model\Leads();
329
+                    $dataInfo = db('crm_contacts')->where(['contacts_id' => $v])->find();
330
+                    //判断权限
331
+                    $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'teamSave');
332
+                    if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
333
+                        $error = true;
334
+                        $errorMessage = "联系人'" . $dataInfo['name'] . "'操作失败,错误原因:无权操作";
335
+                    }
336
+                    if (in_array($dataInfo['owner_user_id'], $param['user_id'])) {
337
+                        $error = true;
338
+                        $errorMessage = "联系人'" . $dataInfo['name'] . "'操作失败,错误原因:不能对负责人进行添加或移出操作!";
339
+                    }
340
+                    $message_type = Message::TEAM_CONTRACT;
341
+                    continue;
289
             }
342
             }
290
             if ($error !== true) {
343
             if ($error !== true) {
291
                 $param['type_id'] = $v;
344
                 $param['type_id'] = $v;
292
                 $param['type'] = $param['type'] ?: 1;
345
                 $param['type'] = $param['type'] ?: 1;
293
                 $param['is_del'] = $param['is_del'] ?: 3;
346
                 $param['is_del'] = $param['is_del'] ?: 3;
294
                 $param['owner_user_id'] = $userInfo['id'];
347
                 $param['owner_user_id'] = $userInfo['id'];
295
-                if (empty($param['is_del'])) {
348
+                $param['target_time'] = strtotime($param['target_time']);
349
+                if ($param['is_del'] == 3) {
296
                     $res = $settingModel->createTeamData($param);
350
                     $res = $settingModel->createTeamData($param);
297
                     if (!$res) {
351
                     if (!$res) {
298
                         $errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
352
                         $errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
305
                             ],
359
                             ],
306
                             $param['user_id']
360
                             $param['user_id']
307
                         );
361
                         );
308
-                        $username=db('admin_user')->where('id',['in',$param['user_id']])->column('realname');
309
-                        RecordActionLog($userInfo['id'], 'crm_customer', 'teamSave',$dataInfo['name'], '','','给' . $typesName. $dataInfo['name'].'添加了团队成员 :'.implode(',',$username));
362
+                        $username = db('admin_user')->where('id', ['in', $param['user_id']])->column('realname');
363
+                        RecordActionLog($userInfo['id'], $param['types'], 'teamSave', $dataInfo['name'], '', '', '给' . $typesName . $dataInfo['name'] . '添加了团队成员 :' . implode(',', $username));
364
+                        updateActionLog($userInfo['id'], $param['types'], $v, '', '', $typesName . $dataInfo['name'] . '添加了团队成员' . implode(',', $username));
310
                     }
365
                     }
311
                 } else {
366
                 } else {
312
                     $res = $settingModel->createTeamData($param);
367
                     $res = $settingModel->createTeamData($param);
313
                     if (!$res) {
368
                     if (!$res) {
314
                         $errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
369
                         $errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
315
-                    }else{
370
+                    } else {
316
                         (new Message())->send(
371
                         (new Message())->send(
317
                             Message::TEAM_END,
372
                             Message::TEAM_END,
318
                             [
373
                             [
322
                             $param['user_id']
377
                             $param['user_id']
323
                         );
378
                         );
324
                     }
379
                     }
325
-                    $username=db('admin_user')->where('id',['in',$param['user_id']])->column('realname');
326
-                    RecordActionLog($userInfo['id'], 'crm_customer', 'teamSave',$dataInfo['name'], '','','移除了' . $typesName. $dataInfo['name'].'团队成员 :'.implode(',',$username));
380
+                    $username = db('admin_user')->where('id', ['in', $param['user_id']])->column('realname');
381
+                    RecordActionLog($userInfo['id'], $param['types'], 'teamSave', $dataInfo['name'], '', '', '移除了' . $typesName . $dataInfo['name'] . '团队成员 :' . implode(',', $username));
382
+                    updateActionLog($userInfo['id'], $param['types'], $v, '', '', $typesName . $dataInfo['name'] . '移除了团队成员' . implode(',', $username));
327
                 }
383
                 }
328
-
329
             }
384
             }
330
         }
385
         }
331
         if ($errorMessage) {
386
         if ($errorMessage) {
334
             return resultArray(['data' => '保存成功']);
389
             return resultArray(['data' => '保存成功']);
335
         }
390
         }
336
     }
391
     }
337
-
392
+    
338
     /**
393
     /**
339
      * 合同到期提醒天数
394
      * 合同到期提醒天数
340
      *
395
      *
350
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
405
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
351
         }
406
         }
352
         $param = $this->param;
407
         $param = $this->param;
353
-        $userInfo=$this->userInfo;
408
+        $userInfo = $this->userInfo;
354
         $data = [];
409
         $data = [];
355
         $contract_day = $param['contract_day'] ? intval($param['contract_day']) : 0;
410
         $contract_day = $param['contract_day'] ? intval($param['contract_day']) : 0;
356
         $contract_config = $param['contract_config'] ? intval($param['contract_config']) : 0;
411
         $contract_config = $param['contract_config'] ? intval($param['contract_config']) : 0;
357
         $res = db('crm_config')->where(['name' => 'contract_config'])->update(['value' => $contract_config]);
412
         $res = db('crm_config')->where(['name' => 'contract_config'])->update(['value' => $contract_config]);
358
         if ($contract_day && $contract_config == 1) $res = db('crm_config')->where(['name' => 'contract_day'])->update(['value' => $contract_day]);
413
         if ($contract_day && $contract_config == 1) $res = db('crm_config')->where(['name' => 'contract_day'])->update(['value' => $contract_day]);
359
         # 系统操作日志
414
         # 系统操作日志
360
-        SystemActionLog($userInfo['id'], 'crm_config','customer', 1, 'update','' , '', '','编辑了合同到期提醒设置');
415
+        SystemActionLog($userInfo['id'], 'crm_config', 'customer', 1, 'update', '', '', '', '编辑了合同到期提醒设置');
361
         return resultArray(['data' => '设置成功']);
416
         return resultArray(['data' => '设置成功']);
362
     }
417
     }
363
-
418
+    
364
     /**
419
     /**
365
      * 记录类型编辑
420
      * 记录类型编辑
366
      *
421
      *
374
     public function recordEdit()
429
     public function recordEdit()
375
     {
430
     {
376
         $param = $this->param;
431
         $param = $this->param;
377
-        $userInfo=$this->userInfo;
432
+        $userInfo = $this->userInfo;
378
         //权限判断
433
         //权限判断
379
         if (!checkPerByAction('admin', 'crm', 'setting')) {
434
         if (!checkPerByAction('admin', 'crm', 'setting')) {
380
             header('Content-Type:application/json; charset=utf-8');
435
             header('Content-Type:application/json; charset=utf-8');
385
             $record_type = db('crm_config')->where(['name' => 'record_type'])->find();
440
             $record_type = db('crm_config')->where(['name' => 'record_type'])->find();
386
             if ($record_type) {
441
             if ($record_type) {
387
                 $res = db('crm_config')->where(['name' => 'record_type'])->update(['value' => $array]);
442
                 $res = db('crm_config')->where(['name' => 'record_type'])->update(['value' => $array]);
388
-                $id=$record_type['id'];
443
+                $id = $record_type['id'];
389
             } else {
444
             } else {
390
                 $data = array();
445
                 $data = array();
391
                 $data['name'] = 'record_type';
446
                 $data['name'] = 'record_type';
392
                 $data['value'] = $array;
447
                 $data['value'] = $array;
393
                 $data['description'] = '跟进记录类型';
448
                 $data['description'] = '跟进记录类型';
394
                 $res = db('crm_config')->insertGetId($data);
449
                 $res = db('crm_config')->insertGetId($data);
395
-                $id=$res;
396
-                $record_type['description']='跟进记录类型';
450
+                $id = $res;
451
+                $record_type['description'] = '跟进记录类型';
397
             }
452
             }
398
             if ($res) {
453
             if ($res) {
399
-                SystemActionLog($userInfo['id'], 'crm_config','customer', $id,  'update',$record_type['description'] , '', '','编辑了跟进记录类型:'.$record_type['description']);
454
+                SystemActionLog($userInfo['id'], 'crm_config', 'customer', $id, 'update', $record_type['description'], '', '', '编辑了跟进记录类型:' . $record_type['description']);
400
                 return resultArray(['data' => '设置成功']);
455
                 return resultArray(['data' => '设置成功']);
401
             } else {
456
             } else {
402
                 return resultArray(['error' => '设置失败,请重试!']);
457
                 return resultArray(['error' => '设置失败,请重试!']);
407
             return resultArray(['data' => $record_type]);
462
             return resultArray(['data' => $record_type]);
408
         }
463
         }
409
     }
464
     }
410
-
465
+    
411
     /**
466
     /**
412
      * 跟进记录 记录方式展示
467
      * 跟进记录 记录方式展示
413
      *
468
      *
426
             return resultArray(['data' => array()]);
481
             return resultArray(['data' => array()]);
427
         }
482
         }
428
     }
483
     }
429
-
484
+    
430
     /**
485
     /**
431
      * 拥有、锁定客户数限制列表
486
      * 拥有、锁定客户数限制列表
432
      *
487
      *
444
         $data = $customerConfigModel->getDataList($param);
499
         $data = $customerConfigModel->getDataList($param);
445
         return resultArray(['data' => $data]);
500
         return resultArray(['data' => $data]);
446
     }
501
     }
447
-
502
+    
448
     /**
503
     /**
449
      * 拥有、锁定客户数限制 创建/编辑 todo 创建和编辑走一个接口,前端非要这么搞
504
      * 拥有、锁定客户数限制 创建/编辑 todo 创建和编辑走一个接口,前端非要这么搞
450
      *
505
      *
460
             header('Content-Type:application/json; charset=utf-8');
515
             header('Content-Type:application/json; charset=utf-8');
461
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
516
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
462
         }
517
         }
463
-
518
+        $userInfo = $this->userInfo;
519
+        $this->param['user_id'] = $userInfo['id'];
464
         $customerConfigModel = new \app\crm\model\CustomerConfig();
520
         $customerConfigModel = new \app\crm\model\CustomerConfig();
465
         if (!$customerConfigModel->createData($this->param)) {
521
         if (!$customerConfigModel->createData($this->param)) {
466
             return resultArray(['error' => $customerConfigModel->getError()]);
522
             return resultArray(['error' => $customerConfigModel->getError()]);
467
         }
523
         }
468
-
524
+        
469
         return resultArray(['data' => empty($param['id']) ? '创建成功!' : '编辑成功!']);
525
         return resultArray(['data' => empty($param['id']) ? '创建成功!' : '编辑成功!']);
470
     }
526
     }
471
-
527
+    
472
     /**
528
     /**
473
      * 拥有、锁定客户数限制 编辑 todo 编辑不走这个接口,前端非要走创建接口
529
      * 拥有、锁定客户数限制 编辑 todo 编辑不走这个接口,前端非要走创建接口
474
      *
530
      *
481
             header('Content-Type:application/json; charset=utf-8');
537
             header('Content-Type:application/json; charset=utf-8');
482
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
538
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
483
         }
539
         }
484
-
540
+        
485
         $param = $this->param;
541
         $param = $this->param;
486
         $customerConfigModel = new \app\crm\model\CustomerConfig();
542
         $customerConfigModel = new \app\crm\model\CustomerConfig();
487
         $res = $customerConfigModel->updateDataById($param, $param['id']);
543
         $res = $customerConfigModel->updateDataById($param, $param['id']);
490
         }
546
         }
491
         return resultArray(['data' => '编辑成功']);
547
         return resultArray(['data' => '编辑成功']);
492
     }
548
     }
493
-
549
+    
494
     /**
550
     /**
495
      * 拥有、锁定客户数限制 删除
551
      * 拥有、锁定客户数限制 删除
496
      *
552
      *
511
         }
567
         }
512
         return resultArray(['data' => '删除成功']);
568
         return resultArray(['data' => '删除成功']);
513
     }
569
     }
514
-
570
+    
515
     /**
571
     /**
516
      * 编号列表
572
      * 编号列表
517
      *
573
      *
527
         $data = $numberSequenceModel->getDataList($param);
583
         $data = $numberSequenceModel->getDataList($param);
528
         return resultArray(['data' => $data]);
584
         return resultArray(['data' => $data]);
529
     }
585
     }
530
-
586
+    
531
     /**
587
     /**
532
      * 编号修改
588
      * 编号修改
533
      *
589
      *
548
         }
604
         }
549
         return resultArray(['data' => '编辑成功']);
605
         return resultArray(['data' => '编辑成功']);
550
     }
606
     }
551
-
607
+    
552
     /**
608
     /**
553
      * 编号删除
609
      * 编号删除
554
      *
610
      *
569
         }
625
         }
570
         return resultArray(['data' => '删除成功']);
626
         return resultArray(['data' => '删除成功']);
571
     }
627
     }
572
-
628
+    
573
     /**
629
     /**
574
      * 设置回访提醒
630
      * 设置回访提醒
575
      *
631
      *
580
     public function setVisitDay()
636
     public function setVisitDay()
581
     {
637
     {
582
         $status = !empty($this->param['status']) ? $this->param['status'] : 0;
638
         $status = !empty($this->param['status']) ? $this->param['status'] : 0;
583
-        $day    = !empty($this->param['day'])    ? $this->param['day']    : 0;
584
-
639
+        $day = !empty($this->param['day']) ? $this->param['day'] : 0;
640
+        $userInfo = $this->userInfo;
585
         $settingModel = new \app\crm\model\Setting();
641
         $settingModel = new \app\crm\model\Setting();
586
-
587
-        if (!$settingModel->setVisitDay($status, $day)) return resultArray(['error' => '操作失败!']);
588
-
642
+        
643
+        if (!$settingModel->setVisitDay($status, $day, $userInfo['id'])) return resultArray(['error' => '操作失败!']);
644
+        
589
         return resultArray(['data' => '操作成功!']);
645
         return resultArray(['data' => '操作成功!']);
590
     }
646
     }
591
     
647
     
602
         
658
         
603
         return resultArray(['data' => $data]);
659
         return resultArray(['data' => $data]);
604
     }
660
     }
661
+    
605
     /**
662
     /**
606
      * 设置自动编号
663
      * 设置自动编号
607
      *
664
      *
610
     public function setNumber()
667
     public function setNumber()
611
     {
668
     {
612
         if (empty($this->param) || !is_array($this->param)) return resultArray(['error' => '参数错误!']);
669
         if (empty($this->param) || !is_array($this->param)) return resultArray(['error' => '参数错误!']);
613
-
670
+        $userInfo = $this->userInfo;
614
         $settingModel = new \app\crm\model\Setting();
671
         $settingModel = new \app\crm\model\Setting();
615
-
616
-        if ($settingModel->setNumber($this->param) === false) return resultArray(['error' => '操作失败!']);
617
-
672
+        if ($settingModel->setNumber($this->param, $userInfo['id']) === false) return resultArray(['error' => '操作失败!']);
673
+        
618
         return resultArray(['data' => '操作成功!']);
674
         return resultArray(['data' => '操作成功!']);
619
     }
675
     }
676
+    
677
+    /**
678
+     * 手机端导航栏显示
679
+     *
680
+     * @author      alvin guogaobo
681
+     * @version     1.0 版本号
682
+     * @since       2021/6/22 0022 11:27
683
+     */
684
+    public function appMenuConfig(){
685
+        $param=$this->userInfo['id'];
686
+        $settingModel = new \app\crm\model\Setting();
687
+        $data=$settingModel->appMenuConfig($param);
688
+        return resultArray(['data' => $data]);
689
+    }
690
+    
691
+    /**
692
+     * 手机端办公数量
693
+     *
694
+     * @author      alvin guogaobo
695
+     * @version     1.0 版本号
696
+     * @since       2021/6/22 0022 13:44
697
+     */
698
+   public function oaNumber(){
699
+       $userInfo=$this->userInfo;
700
+      
701
+       # 日志
702
+       $logNum=db('oa_log')->where('create_user_id',$userInfo['id'])->count();
703
+       #审批
704
+       $examineNum=db('oa_examine')->where('create_user_id',$userInfo['id'])->count();
705
+       #任务
706
+       $taskNum=db('task')->where('create_user_id',$userInfo['id'])->count();
707
+       #跟进
708
+       $activityNum=db('crm_activity')->where(['create_user_id'=>$userInfo['id'],'type'=>1])->count();
709
+       $data=[];
710
+       $data['logNum']=$logNum;
711
+       $data['examineNum']=$examineNum;
712
+       $data['taskNum']=$taskNum;
713
+       $data['activityNu']=$activityNum;
714
+       return $data;
715
+   }
620
 }
716
 }

+ 7
- 5
application/crm/logic/ActivityLogic.php Bestand weergeven

444
         $param['business_ids']   = !empty($param['business_ids']) ? arrayToString($param['business_ids']) : '';
444
         $param['business_ids']   = !empty($param['business_ids']) ? arrayToString($param['business_ids']) : '';
445
         $param['create_time']    = time();
445
         $param['create_time']    = time();
446
         $param['update_time']    = time();
446
         $param['update_time']    = time();
447
-        if (!empty($param['contacts_ids'])) $param['contacts_ids'] = ',' . $param['contacts_ids'] . ',';
447
+        if(empty($param['excel'])){
448
+            if (!empty($param['contacts_ids'])) $param['contacts_ids'] = ',' . $param['contacts_ids'] . ',';
449
+        }else{
450
+            unset($param['excel']);
451
+        }
448
         $activityJson = Activity::create($param);
452
         $activityJson = Activity::create($param);
449
         if (empty($activityJson)) return false;
453
         if (empty($activityJson)) return false;
450
 
454
 
549
      * @param $activityId
553
      * @param $activityId
550
      * @return Activity
554
      * @return Activity
551
      */
555
      */
552
-    public function delete($activityId)
556
+    public function delete($activityId,$userId)
553
     {
557
     {
554
         $activityInfo = Db::name('crm_activity')->where(['activity_id' => $activityId])->find();
558
         $activityInfo = Db::name('crm_activity')->where(['activity_id' => $activityId])->find();
555
         if (Activity::update(['activity_id' => $activityId, 'status' => 0])) {
559
         if (Activity::update(['activity_id' => $activityId, 'status' => 0])) {
563
             if ($activityInfo['activity_type'] == 3) db('crm_contacts_file')->whereIn('file_id', $fileIds)->delete();
567
             if ($activityInfo['activity_type'] == 3) db('crm_contacts_file')->whereIn('file_id', $fileIds)->delete();
564
             if ($activityInfo['activity_type'] == 5) db('crm_business_file')->whereIn('file_id', $fileIds)->delete();
568
             if ($activityInfo['activity_type'] == 5) db('crm_business_file')->whereIn('file_id', $fileIds)->delete();
565
             if ($activityInfo['activity_type'] == 6) db('crm_contract_file')->whereIn('file_id', $fileIds)->delete();
569
             if ($activityInfo['activity_type'] == 6) db('crm_contract_file')->whereIn('file_id', $fileIds)->delete();
566
-            $user=new ApiCommon();
567
-            $userInfo=$user->userInfo;
568
-            RecordActionLog($userInfo['id'],'crm_activity','delete','删除跟进记录','','','删除了'.$recordModules[$types].$name);
570
+            RecordActionLog($userId,'crm_activity','delete','删除跟进记录','','','删除了'.$recordModules[$types].$name);
569
             return true;
571
             return true;
570
         } else {
572
         } else {
571
             return false;
573
             return false;

+ 106
- 47
application/crm/logic/CommonLogic.php Bestand weergeven

10
 
10
 
11
 use app\admin\controller\ApiCommon;
11
 use app\admin\controller\ApiCommon;
12
 use app\admin\model\User;
12
 use app\admin\model\User;
13
+use app\admin\traits\FieldVerificationTrait;
13
 use app\crm\model\Customer;
14
 use app\crm\model\Customer;
14
 use think\Db;
15
 use think\Db;
15
 use think\Validate;
16
 use think\Validate;
16
 
17
 
17
 class CommonLogic
18
 class CommonLogic
18
 {
19
 {
20
+    use FieldVerificationTrait;
21
+
19
     public $error = '操作失败!';
22
     public $error = '操作失败!';
20
     
23
     
21
     /**
24
     /**
22
-     * 快捷编辑【线索、客户、联系人、商机、合同、回款、回访、产品】
25
+     * 快捷编辑【线索、客户、联系人、商机、合同、回款、发票、回访、产品】
23
      *
26
      *
24
      * @param $param
27
      * @param $param
25
      * @return false|int|string
28
      * @return false|int|string
48
         $model = db($types);
51
         $model = db($types);
49
         
52
         
50
         # 主键
53
         # 主键
51
-        $primaryKey = '';
52
-       // author      guogaobo $item模块
54
+        $primaryKey = getPrimaryKeyName($types);
55
+
53
         $info='';
56
         $info='';
54
         switch ($types) {
57
         switch ($types) {
55
             case 'crm_leads' :
58
             case 'crm_leads' :
56
-                $primaryKey = 'leads_id';
57
                 $dataModel=new \app\crm\model\Leads();
59
                 $dataModel=new \app\crm\model\Leads();
58
                 $info=$dataModel->getDataById($actionId);
60
                 $info=$dataModel->getDataById($actionId);
59
                 break;
61
                 break;
60
             case 'crm_customer' :
62
             case 'crm_customer' :
61
-                $primaryKey = 'customer_id';
62
                 $info=db('crm_customer')->where('customer_id',$actionId)->find();
63
                 $info=db('crm_customer')->where('customer_id',$actionId)->find();
63
                 break;
64
                 break;
64
             case 'crm_contacts' :
65
             case 'crm_contacts' :
65
-                $primaryKey = 'contacts_id';
66
                 $dataModel=new \app\crm\model\Contacts();
66
                 $dataModel=new \app\crm\model\Contacts();
67
                 $info=$dataModel->getDataById($actionId);
67
                 $info=$dataModel->getDataById($actionId);
68
                 break;
68
                 break;
69
             case 'crm_business' :
69
             case 'crm_business' :
70
-                $primaryKey = 'business_id';
71
                 $dataModel=new \app\crm\model\Business();
70
                 $dataModel=new \app\crm\model\Business();
72
                 $info=$dataModel->getDataById($actionId);
71
                 $info=$dataModel->getDataById($actionId);
73
                 break;
72
                 break;
74
             case 'crm_contract' :
73
             case 'crm_contract' :
75
-                $primaryKey = 'contract_id';
76
                 $info=db('crm_contract')->where('customer_id',$actionId)->find();
74
                 $info=db('crm_contract')->where('customer_id',$actionId)->find();
77
                 break;
75
                 break;
78
             case 'crm_receivables' :
76
             case 'crm_receivables' :
79
-                $primaryKey = 'receivables_id';
80
                 $info=db('crm_receivables')->where('customer_id',$actionId)->find();
77
                 $info=db('crm_receivables')->where('customer_id',$actionId)->find();
81
                 break;
78
                 break;
79
+            case 'crm_invoice' :
80
+                $info = $model->where($primaryKey, $actionId)->find();
81
+                break;
82
             case 'crm_visit' :
82
             case 'crm_visit' :
83
-                $primaryKey = 'visit_id';
84
                 $dataModel=new \app\crm\logic\VisitLogic();
83
                 $dataModel=new \app\crm\logic\VisitLogic();
85
                 $info=$dataModel->getDataById($actionId);
84
                 $info=$dataModel->getDataById($actionId);
86
                 break;
85
                 break;
87
             case 'crm_product' :
86
             case 'crm_product' :
88
-                $primaryKey = 'product_id';
89
                 $dataModel=new \app\crm\model\Product();
87
                 $dataModel=new \app\crm\model\Product();
90
                 $info=$dataModel->getDataById($actionId);
88
                 $info=$dataModel->getDataById($actionId);
91
                 break;
89
                 break;
92
         }
90
         }
93
         $apiCommon = new ApiCommon();
91
         $apiCommon = new ApiCommon();
94
         $userModel = new User();
92
         $userModel = new User();
95
-
93
+        $userInfo = $apiCommon->userInfo;
96
 
94
 
97
         if (in_array($types, ['crm_contract', 'crm_receivables'])) {
95
         if (in_array($types, ['crm_contract', 'crm_receivables'])) {
98
             $checkStatus = $model->where($primaryKey, $actionId)->value('check_status');
96
             $checkStatus = $model->where($primaryKey, $actionId)->value('check_status');
101
                 return false;
99
                 return false;
102
             }
100
             }
103
         }
101
         }
102
+
103
+        // 数据验证
104
+        $validateData = [];
105
+        if (!empty($param['list'])) {
106
+            foreach ($param['list'] AS $key => $value) {
107
+                foreach ($value AS $k => $v) {
108
+                    $validateData[$k] = $v;
109
+                }
110
+            }
111
+        }
112
+        $validateResult = $this->fieldDataValidate($validateData, $types, $userInfo['id'], $actionId);
113
+        if (!empty($validateResult)) {
114
+            $this->error = $validateResult;
115
+            return false;
116
+        }
117
+
104
         # 产品修改验证
118
         # 产品修改验证
105
         if($types == 'crm_product'){
119
         if($types == 'crm_product'){
106
             foreach ($param['list'] as $val){
120
             foreach ($param['list'] as $val){
164
         $userField = $fieldModel->getFieldByFormType($types, 'user');
178
         $userField = $fieldModel->getFieldByFormType($types, 'user');
165
         # 部门类型
179
         # 部门类型
166
         $structureField = $fieldModel->getFieldByFormType($types, 'structure');
180
         $structureField = $fieldModel->getFieldByFormType($types, 'structure');
181
+        # 地址
182
+        $positionField = $fieldModel->getFieldByFormType($types, 'position');
183
+        # 定位
184
+        $locationField = $fieldModel->getFieldByFormType($types, 'location');
185
+        # 日期区间
186
+        $dateIntervalField = $fieldModel->getFieldByFormType($types, 'date_interval');
187
+        # 手写签名
188
+        $handwritingField = $fieldModel->getFieldByFormType($types, 'handwriting_sign');
189
+        # 明细表格
190
+        $detailTableField = $fieldModel->getFieldByFormType($types, 'detail_table');
167
 
191
 
168
-        foreach ($param['list'] as $key => $value) {
169
-            foreach ($value as $k => $v) {
170
-                # 查询自定义字段信息
171
-                $fieldInfo = Db::name('admin_field')->field(['max_length', 'is_unique', 'is_null', 'name'])
172
-                    ->where('types', $types)->where('field', $k)->find();
173
-
174
-                # 字符长度
175
-                if (!empty($fieldInfo['max_length']) && strlen($v) > $fieldInfo['max_length']) {
176
-                    $this->error = $fieldInfo['name'] . ' 字符长度不能超过 ' . $fieldInfo['max_length'] . ' 个字符!';
177
-                    return false;
178
-                }
179
-
180
-                # 必填
181
-                if (!empty($fieldInfo['is_null']) && empty($v)) {
182
-                    $this->error = $fieldInfo['name'] . ' 是必填信息,不能为空!';
183
-                    return false;
184
-                }
185
-
186
-                # 唯一
187
-                if (!empty($fieldInfo['is_unique']) && $model->where([$primaryKey => ['neq', $actionId]])->where($k, $v)->value($primaryKey)) {
188
-                    $this->error = $fieldInfo['name'] . ' 内容重复!';
189
-                    return false;
190
-                }
191
-            }
192
-        }
193
-        
194
-        # 编辑参数
192
+        # 处理数据 data 常规数据 extraData 扩展数据(地址、定位、日期区间、详细表格)
195
         $data = [];
193
         $data = [];
194
+        $extraData = [];
195
+        $deleteExtraWhere = [];
196
         if (!empty($param['list'])) {
196
         if (!empty($param['list'])) {
197
             foreach ($param['list'] as $key => $value) {
197
             foreach ($param['list'] as $key => $value) {
198
                 foreach ($value as $k => $v) {
198
                 foreach ($value as $k => $v) {
199
                     if ($k == 'next_time' || in_array($k, $datetimeField)) {
199
                     if ($k == 'next_time' || in_array($k, $datetimeField)) {
200
                         # 处理下次联系时间格式、datetime类型数据
200
                         # 处理下次联系时间格式、datetime类型数据
201
-                        $data[$k] = !empty($v) ? strtotime($v) : '';
201
+                        $data[$k] = !empty($v) && $v == strtotime($v) ? strtotime($v) : $v;
202
                     } elseif ($types == 'crm_product' && $k == 'category_id') {
202
                     } elseif ($types == 'crm_product' && $k == 'category_id') {
203
                         # 处理产品类别
203
                         # 处理产品类别
204
                         $categorys = explode(',', $v);
204
                         $categorys = explode(',', $v);
209
                     } elseif ($types == 'crm_visit' && $k == 'contract_id') {
209
                     } elseif ($types == 'crm_visit' && $k == 'contract_id') {
210
                         # 处理回访提交过来的合同编号
210
                         # 处理回访提交过来的合同编号
211
                         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'];
212
+                    } elseif (in_array($k, $handwritingField)) {
213
+                        // 手写签名
214
+                        $data[$k] = !empty($v['file_id']) ? $v['file_id'] : 0;
215
+                    } elseif (in_array($k, $positionField)) {
216
+                        // 地址
217
+                        if (!empty($v)) {
218
+                            $extraData[] = [
219
+                                $primaryKey => $actionId,
220
+                                'field' => $k,
221
+                                'content' => json_encode($v),
222
+                                'create_time' => time()
223
+                            ];
224
+                            $positionNames = array_column($v, 'name');
225
+                            $data[$k] = implode(',', $positionNames);
226
+                        } else {
227
+                            $data[$k] = '';
228
+                        }
229
+                        $deleteExtraWhere[] = $k;
230
+                    } elseif (in_array($k, $locationField)) {
231
+                        // 定位
232
+                        if (!empty($v)) {
233
+                            $extraData[] = [
234
+                                $primaryKey => $actionId,
235
+                                'field' => $k,
236
+                                'content' => json_encode($v),
237
+                                'create_time' => time()
238
+                            ];
239
+                            $data[$k] = $v['address'];
240
+                        } else {
241
+                            $data[$k] = '';
242
+                        }
243
+                        $deleteExtraWhere[] = $k;
244
+                    } elseif (in_array($k, $dateIntervalField)) {
245
+                        // 日期区间
246
+                        if (!empty($v)) {
247
+                            $extraData[] = [
248
+                                $primaryKey => $actionId,
249
+                                'field' => $k,
250
+                                'content' => json_encode($v),
251
+                                'create_time' => time()
252
+                            ];
253
+                            $data[$k] = implode('_', $v);
254
+                        } else {
255
+                            $data[$k] = '';
256
+                        }
257
+                        $deleteExtraWhere[] = $k;
258
+                    } elseif (in_array($k, $detailTableField)) {
259
+                        // 明细表格
260
+                        if (!empty($v)) {
261
+                            $extraData[] = [
262
+                                $primaryKey => $actionId,
263
+                                'field' => $k,
264
+                                'content' => json_encode($v),
265
+                                'create_time' => time()
266
+                            ];
267
+                        }
268
+                        $deleteExtraWhere[] = $k;
212
                     } else {
269
                     } else {
213
                         $data[$k] = $v;
270
                         $data[$k] = $v;
214
                     }
271
                     }
215
-                    $item[$k]=$v;
216
                 }
272
                 }
217
             }
273
             }
218
             $data[$primaryKey]   = $actionId;
274
             $data[$primaryKey]   = $actionId;
219
             $data['update_time'] = time();
275
             $data['update_time'] = time();
220
         }
276
         }
277
+
221
         $res = $model->update($data);
278
         $res = $model->update($data);
222
         unset($data[$primaryKey]);
279
         unset($data[$primaryKey]);
223
         unset($data['update_time']);
280
         unset($data['update_time']);
224
-        //详细信息修改新增操作记录
281
+        // 详细信息修改新增操作记录、处理扩展数据
225
         if ($res) {
282
         if ($res) {
226
-            //修改记录
227
-            $user_id = $apiCommon->userInfo;
228
-            updateActionLog($user_id['id'], $types, $actionId, $info, $data);
229
-            RecordActionLog($user_id['id'], $types, 'update',$info['name'], $info, $data);
230
-    
283
+            // 删除扩展数据
284
+            if (!empty($deleteExtraWhere)) db($types . '_data')->where([$primaryKey => $actionId, 'field' => ['in', $deleteExtraWhere]])->delete();
285
+            // 添加扩展数据
286
+            if (!empty($extraData)) db($types . '_data')->insertAll($extraData);
287
+            // 修改记录
288
+            updateActionLog($userInfo['id'], $types, $actionId, $info, $data);
289
+            RecordActionLog($userInfo['id'], $types, 'update',$info['name'], $info, $data);
231
         }
290
         }
232
         return $res;
291
         return $res;
233
     }
292
     }

+ 99
- 53
application/crm/logic/CustomerPoolLogic.php Bestand weergeven

38
         $poolId = $param['pool_id'];
38
         $poolId = $param['pool_id'];
39
         $orderField = $param['order_field'];
39
         $orderField = $param['order_field'];
40
         $orderType = $param['order_type'];
40
         $orderType = $param['order_type'];
41
-      
42
-        # 基础条件
41
+
42
+        // 基础条件
43
         $where['relation.pool_id'] = $poolId;
43
         $where['relation.pool_id'] = $poolId;
44
 
44
 
45
-        # 普通搜索
45
+        // 普通搜索
46
         $searchMap = [];
46
         $searchMap = [];
47
         if ($param['search'] == '0' || !empty($param['search'])) {
47
         if ($param['search'] == '0' || !empty($param['search'])) {
48
             $search = $param['search'];
48
             $search = $param['search'];
52
                     ->whereOr('customer.telephone',array('like','%'.$search.'%'));
52
                     ->whereOr('customer.telephone',array('like','%'.$search.'%'));
53
             };
53
             };
54
         }
54
         }
55
-      
56
-        # 处理排序参数
55
+
56
+        // 处理排序参数
57
         if (!empty($orderField)) {
57
         if (!empty($orderField)) {
58
             if ($orderField == 'create_user_id_name') $orderField = 'create_user_id';
58
             if ($orderField == 'create_user_id_name') $orderField = 'create_user_id';
59
             if ($orderField == 'before_owner_user_name') $orderField = 'before_owner_user_id';
59
             if ($orderField == 'before_owner_user_name') $orderField = 'before_owner_user_id';
60
         }
60
         }
61
-        # 公海条件
61
+        // 公海条件
62
         if ($param['is_excel'] == 1 && !empty($param['customer_id'])) {
62
         if ($param['is_excel'] == 1 && !empty($param['customer_id'])) {
63
             $authMap['customer.customer_id'] = ['in', trim(arrayToString($param['customer_id']),',')];
63
             $authMap['customer.customer_id'] = ['in', trim(arrayToString($param['customer_id']),',')];
64
         }
64
         }
65
-        # 排序
65
+        // 排序
66
         if (!empty($orderField) && !empty($orderType)) {
66
         if (!empty($orderField) && !empty($orderType)) {
67
             $order = $fieldModel->getOrderByFormtype('crm_customer','customer', $orderField, $orderType);
67
             $order = $fieldModel->getOrderByFormtype('crm_customer','customer', $orderField, $orderType);
68
         } else {
68
         } else {
69
             $order = 'customer.update_time desc';
69
             $order = 'customer.update_time desc';
70
         }
70
         }
71
-        # 删除参数
71
+        // 删除参数
72
         unset($param['pool_id']);
72
         unset($param['pool_id']);
73
         unset($param['search']);
73
         unset($param['search']);
74
         unset($param['order_field']);
74
         unset($param['order_field']);
75
         unset($param['order_type']);
75
         unset($param['order_type']);
76
         unset($param['is_excel']);
76
         unset($param['is_excel']);
77
         unset($param['customer_id']);
77
         unset($param['customer_id']);
78
-        # 格式化参数
78
+        // 格式化参数
79
         $request = $this->fmtRequest( $param );
79
         $request = $this->fmtRequest( $param );
80
         $requestMap = !empty($request['map']) ? $request['map'] : [];
80
         $requestMap = !empty($request['map']) ? $request['map'] : [];
81
-        
82
-        # 高级搜索
83
-        $map = where_arr($requestMap, 'crm', 'customer', 'index');
84
-        # 公海字段
81
+
82
+        // 高级搜索
83
+        $map = advancedQuery($requestMap, 'crm', 'customer', 'index');
84
+
85
+        // 公海字段
85
         $customerFieldString = $this->getPoolQueryField($poolId);
86
         $customerFieldString = $this->getPoolQueryField($poolId);
86
-        # 公海数据
87
+        // 公海数据
87
         $customerPoolCount = db('crm_customer_pool_relation')->alias('relation')
88
         $customerPoolCount = db('crm_customer_pool_relation')->alias('relation')
88
             ->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT')
89
             ->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT')
89
             ->where($where)->where($searchMap)->where($map)->where($authMap)->count();
90
             ->where($where)->where($searchMap)->where($map)->where($authMap)->count();
93
             ->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT')
94
             ->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT')
94
             ->limit($request['offset'], $request['length'])->where($where)->where($searchMap)->where($map)->where($authMap)->orderRaw($order)->select();
95
             ->limit($request['offset'], $request['length'])->where($where)->where($searchMap)->where($map)->where($authMap)->orderRaw($order)->select();
95
 
96
 
96
-        # 员工列表
97
+        // 员工列表
97
         $userData = $this->getUserList();
98
         $userData = $this->getUserList();
98
 
99
 
99
-        # 部门列表
100
+        // 部门列表
100
         $structureData = $this->getStructureList();
101
         $structureData = $this->getStructureList();
101
 
102
 
102
-        # 特殊字段
103
+        // 特殊字段
103
         $userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); # 人员类型
104
         $userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); # 人员类型
104
         $structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); # 部门类型
105
         $structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); # 部门类型
105
         $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); # 日期时间类型
106
         $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); # 日期时间类型
107
+        $booleanField = $fieldModel->getFieldByFormType('crm_customer', 'boolean_value'); // 布尔值类型字段
108
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_customer', 'date_interval'); // 日期区间类型字段
109
+        $positionField = $fieldModel->getFieldByFormType('crm_customer', 'position'); // 地址类型字段
110
+        $handwritingField = $fieldModel->getFieldByFormType('crm_customer', 'handwriting_sign'); // 手写签名类型字段
111
+        $locationField = $fieldModel->getFieldByFormType('crm_customer', 'location'); // 定位类型字段
112
+
113
+        // 扩展数据
114
+        $extraData = [];
115
+        $customerIds = array_column($customerPoolList, 'customer_id');
116
+        $extraList = db('crm_customer_data')->whereIn('customer_id', $customerIds)->select();
117
+        foreach ($extraList AS $key => $value) {
118
+            $extraData[$value['customer_id']][$value['field']] = $value['content'];
119
+        }
106
 
120
 
107
-        # 整理公海数据
121
+        // 整理公海数据
108
         foreach ($customerPoolList AS $key => $value) {
122
         foreach ($customerPoolList AS $key => $value) {
109
             $customerPoolList[$key]['create_user_name'] = !empty($userData[$value['create_user_id']]) ? $userData[$value['create_user_id']] : '';
123
             $customerPoolList[$key]['create_user_name'] = !empty($userData[$value['create_user_id']]) ? $userData[$value['create_user_id']] : '';
110
             $customerPoolList[$key]['before_owner_user_name'] = !empty($userData[$value['before_owner_user_id']]) ? $userData[$value['before_owner_user_id']] : '';
124
             $customerPoolList[$key]['before_owner_user_name'] = !empty($userData[$value['before_owner_user_id']]) ? $userData[$value['before_owner_user_id']] : '';
115
             $customerPoolList[$key]['last_time'] = !empty($value['last_time']) ? date('Y-m-d H:i:s', $value['last_time']) : null;
129
             $customerPoolList[$key]['last_time'] = !empty($value['last_time']) ? date('Y-m-d H:i:s', $value['last_time']) : null;
116
             $customerPoolList[$key]['into_pool_time'] = !empty($value['into_pool_time']) ? date('Y-m-d H:i:s', $value['into_pool_time']) : null;
130
             $customerPoolList[$key]['into_pool_time'] = !empty($value['into_pool_time']) ? date('Y-m-d H:i:s', $value['into_pool_time']) : null;
117
 
131
 
118
-            # 处理日期时间类型的自定义字段
132
+            // 处理日期时间类型的自定义字段
119
             foreach ($datetimeField AS $k => $v) {
133
             foreach ($datetimeField AS $k => $v) {
120
-                if (isset($datetimeField[$key][$v])) {
121
-                    $datetimeField[$key][$v] = !empty($value[$v]) ? date('Y-m-d H:i:s', $value[$v]) : null;
122
-                }
134
+                if (!empty($value[$v])) $customerPoolList[$key][$v] = date('Y-m-d H:i:s', $value[$v]);
123
             }
135
             }
124
-            # 处理人员类型的自定义字段
136
+            // 处理人员类型的自定义字段
125
             foreach ($userField AS $k => $v) {
137
             foreach ($userField AS $k => $v) {
126
-                if (isset($datetimeField[$key][$v]) && !empty($value[$v])) {
127
-                    $datetimeField[$key][$v] = $this->fieldTransformToText($value[$v], $userData);
138
+                if (!empty($value[$v])) {
139
+                    $customerPoolList[$key][$v] = $this->fieldTransformToText($value[$v], $userData);
128
                 }
140
                 }
129
             }
141
             }
130
-            # 处理部门类型的自定义字段
142
+            // 处理部门类型的自定义字段
131
             foreach ($structureField AS $k => $v) {
143
             foreach ($structureField AS $k => $v) {
132
-                if (isset($datetimeField[$key][$v]) && !empty($value[$v])) {
133
-                    $datetimeField[$key][$v] = $this->fieldTransformToText($value[$v], $structureData);
134
-                }
144
+                if (!empty($value[$v])) $customerPoolList[$key][$v] = $this->fieldTransformToText($value[$v], $structureData);
145
+            }
146
+            // 布尔值类型字段
147
+            foreach ($booleanField AS $k => $v) {
148
+                $customerPoolList[$key][$v] = !empty($value[$v]) ? (string)$value[$v] : '0';
149
+            }
150
+            // 处理日期区间类型字段的格式
151
+            foreach ($dateIntervalField AS $k => $v) {
152
+                $customerPoolList[$key][$v] = !empty($extraData[$value['customer_id']][$v]) ? json_decode($extraData[$value['customer_id']][$v], true) : null;
153
+            }
154
+            // 处理地址类型字段的格式
155
+            foreach ($positionField AS $k => $v) {
156
+                $customerPoolList[$key][$v] = !empty($extraData[$value['customer_id']][$v]) ? json_decode($extraData[$value['customer_id']][$v], true) : null;
157
+            }
158
+            // 手写签名类型字段
159
+            foreach ($handwritingField AS $k => $v) {
160
+                $handwritingData = !empty($value[$v]) ? db('admin_file')->where('file_id', $value[$v])->value('file_path') : null;
161
+                $customerPoolList[$key][$v] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
162
+            }
163
+            // 定位类型字段
164
+            foreach ($locationField AS $k => $v) {
165
+                $customerPoolList[$key][$v] = !empty($extraData[$value['customer_id']][$v]) ? json_decode($extraData[$value['customer_id']][$v], true) : null;
135
             }
166
             }
136
         }
167
         }
137
 
168
 
307
      */
338
      */
308
     public function getPondList($param)
339
     public function getPondList($param)
309
     {
340
     {
341
+        $adminTypes = adminGroupTypes($param['user_id']);
342
+
310
         return db('crm_customer_pool')->field(['pool_id', 'pool_name'])
343
         return db('crm_customer_pool')->field(['pool_id', 'pool_name'])
311
             ->where('status', 1)
344
             ->where('status', 1)
312
-            ->where(function ($query) use ($param) {
313
-                $query->where('admin_user_ids', 'like', '%,' . $param['user_id'] . ',%');
314
-                $query->whereOr('user_ids', 'like', '%,' . $param['user_id'] . ',%');
315
-                $query->whereOr('department_ids', '%,' . $param['structure_id'] . ',%');
345
+            ->where(function ($query) use ($param, $adminTypes) {
346
+                if (!in_array(1, $adminTypes)) $query->where('admin_user_ids', 'like', '%,' . $param['user_id'] . ',%');
347
+                if (!in_array(1, $adminTypes)) $query->whereOr('user_ids', 'like', '%,' . $param['user_id'] . ',%');
348
+                if (!in_array(1, $adminTypes))  $query->whereOr('department_ids', '%,' . $param['structure_id'] . ',%');
316
             })->select();
349
             })->select();
317
     }
350
     }
318
 
351
 
329
         $data = [];
362
         $data = [];
330
 
363
 
331
         # 自定义字段
364
         # 自定义字段
332
-        $list = db('crm_customer_pool_field_setting')->where('pool_id', $param['pool_id'])->where('is_hidden', 0)->select();
365
+        $where = [
366
+            'pool_id'   => $param['pool_id'],
367
+            'is_hidden' => 0,
368
+            'form_type' => ['notin', ['file', 'desc_text', 'detail_table']]
369
+        ];
370
+        $list = db('crm_customer_pool_field_setting')->where($where)->select();
333
 
371
 
334
         # 处理公海字段
372
         # 处理公海字段
335
         foreach ($list AS $key => $value) {
373
         foreach ($list AS $key => $value) {
346
                 default :
384
                 default :
347
                     $list[$key]['fieldName'] = $value['field_name'];
385
                     $list[$key]['fieldName'] = $value['field_name'];
348
             }
386
             }
349
-            if (in_array($value['form_type'], ['user', 'structure']) && !in_array($value['field_name'], ['create_user_id', 'owner_user_id', 'before_owner_user_id'])) {
350
-                $list[$key]['fieldName'] = $value['field_name'] . '_name';
351
-            }
352
 
387
 
353
             if (in_array($value['field_name'], ['last_record', 'create_user_id', 'create_time', 'update_time', 'last_time', 'deal_status'])) {
388
             if (in_array($value['field_name'], ['last_record', 'create_user_id', 'create_time', 'update_time', 'last_time', 'deal_status'])) {
354
                 $list[$key]['system'] = 1;
389
                 $list[$key]['system'] = 1;
395
             ['field' => 'into_pool_time', 'name' => '进入公海时间', 'form_type' => 'datetime', 'setting' => ''],
430
             ['field' => 'into_pool_time', 'name' => '进入公海时间', 'form_type' => 'datetime', 'setting' => ''],
396
         ];
431
         ];
397
         # 自定义字段
432
         # 自定义字段
398
-        $list = db('admin_field')->field(['field', 'name', 'form_type', 'setting'])->where('types', 'crm_customer')->select();
433
+        $list = db('admin_field')->field(['field', 'name', 'form_type', 'setting'])->where('types', 'crm_customer')->whereNotIn('form_type', ['file', 'handwriting_sign', 'desc_text', 'detail_table', 'date_interval'])->select();
399
         $list = array_merge($list, $base);
434
         $list = array_merge($list, $base);
400
 
435
 
401
         # 整理数据
436
         # 整理数据
416
      */
451
      */
417
     public function receiveCustomers($param)
452
     public function receiveCustomers($param)
418
     {
453
     {
454
+        
419
         if (empty($param['user_id'])) return ['缺少员工ID'];
455
         if (empty($param['user_id'])) return ['缺少员工ID'];
420
 
456
 
421
         # 查询参数
457
         # 查询参数
453
                 $message[] = '客户《' . $customerData[$value]['name'] . '》领取失败,失败原因:持有客户数达到上限!';
489
                 $message[] = '客户《' . $customerData[$value]['name'] . '》领取失败,失败原因:持有客户数达到上限!';
454
             }
490
             }
455
         }
491
         }
456
-
457
         # 可以领取的客户ID,取差集
492
         # 可以领取的客户ID,取差集
458
         $addCustomerId = count($customerId) == 1 ? $customerId : array_diff($customerId, $failCustomer);
493
         $addCustomerId = count($customerId) == 1 ? $customerId : array_diff($customerId, $failCustomer);
459
-
494
+      
460
         # 检查是否还有要领取的客户
495
         # 检查是否还有要领取的客户
461
         if (empty($addCustomerId)) return $message;
496
         if (empty($addCustomerId)) return $message;
462
-
497
+        # 查询领取客户的公海id
498
+        $poolId=db('crm_customer_pool_relation')->whereIn('customer_id',$customerId)->value('pool_id');
463
         # 公海配置
499
         # 公海配置
464
-        $poolConfig = db('crm_customer_pool')->field(['before_owner_conf', 'before_owner_day', 'receive_conf', 'receive_count'])->where('pool_id', $param['pool_id'])->find();
500
+        $poolConfig = db('crm_customer_pool')->field(['before_owner_conf', 'before_owner_day', 'receive_conf', 'receive_count'])->where('pool_id', $poolId)->find();
465
 
501
 
466
         # 前负责人N天内不能领取客户
502
         # 前负责人N天内不能领取客户
467
         if (!empty($poolConfig['before_owner_conf'])) {
503
         if (!empty($poolConfig['before_owner_conf'])) {
483
 
519
 
484
         # 检查每天领取的个数限制
520
         # 检查每天领取的个数限制
485
         $countWhere['type'] = 1;
521
         $countWhere['type'] = 1;
486
-        $countWhere['pool_id'] = $param['pool_id'];
522
+        $countWhere['pool_id'] = $poolId;
487
         $countWhere['user_id'] = $userId;
523
         $countWhere['user_id'] = $userId;
488
         $countWhere['create_time'] = ['between', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))]];
524
         $countWhere['create_time'] = ['between', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))]];
489
         $receiveCount = db('crm_customer_pool_record')->where($countWhere)->count();
525
         $receiveCount = db('crm_customer_pool_record')->where($countWhere)->count();
527
             $addReceiveData[] = [
563
             $addReceiveData[] = [
528
                 'customer_id' => $value,
564
                 'customer_id' => $value,
529
                 'user_id'     => $userId,
565
                 'user_id'     => $userId,
530
-                'pool_id'     => $param['pool_id'],
566
+                'pool_id'     => $poolId,
531
                 'type'        => 1,
567
                 'type'        => 1,
532
                 'create_time' => time()
568
                 'create_time' => time()
533
             ];
569
             ];
537
         try {
573
         try {
538
             # 领取客户
574
             # 领取客户
539
             Db::name('crm_customer')->whereIn('customer_id', $addCustomerId)->update($addCustomerData);
575
             Db::name('crm_customer')->whereIn('customer_id', $addCustomerId)->update($addCustomerData);
540
-
576
+            
541
             # 设置客户的联系人数据
577
             # 设置客户的联系人数据
542
             Db::name('crm_contacts')->whereIn('customer_id', $addCustomerId)->update(['owner_user_id' => $userId]);
578
             Db::name('crm_contacts')->whereIn('customer_id', $addCustomerId)->update(['owner_user_id' => $userId]);
543
-
579
+           
544
             # 删除公海与客户关联数据
580
             # 删除公海与客户关联数据
545
             Db::name('crm_customer_pool_relation')->whereIn('customer_id', $addCustomerId)->delete();
581
             Db::name('crm_customer_pool_relation')->whereIn('customer_id', $addCustomerId)->delete();
546
-
582
+            
547
             # 字段操作日志
583
             # 字段操作日志
548
             Db::name('admin_action_record')->insertAll($addActionRecordData);
584
             Db::name('admin_action_record')->insertAll($addActionRecordData);
549
-
585
+           
550
             # 数据操作日志
586
             # 数据操作日志
551
             Db::name('admin_operation_log')->insertAll($addOperationLogData);
587
             Db::name('admin_operation_log')->insertAll($addOperationLogData);
552
-
588
+            
553
             # 记录领取的客户
589
             # 记录领取的客户
554
             Db::name('crm_customer_pool_record')->insertAll($addReceiveData);
590
             Db::name('crm_customer_pool_record')->insertAll($addReceiveData);
555
-
591
+           
556
             Db::commit();
592
             Db::commit();
557
         } catch (\Exception $e) {
593
         } catch (\Exception $e) {
558
             Db::rollback();
594
             Db::rollback();
615
 
651
 
616
         # 检查是否还有要领取的客户
652
         # 检查是否还有要领取的客户
617
         if (empty($addCustomerId)) return $message;
653
         if (empty($addCustomerId)) return $message;
618
-
654
+        # 查询分配客户的公海id
655
+        $poolId=db('crm_customer_pool_relation')->whereIn('customer_id',$customerId)->value('pool_id');
619
         # 整理客户更新数据
656
         # 整理客户更新数据
620
         $addCustomerData = [
657
         $addCustomerData = [
621
             'owner_user_id'        => $userId,
658
             'owner_user_id'        => $userId,
653
             $addReceiveData[] = [
690
             $addReceiveData[] = [
654
                 'customer_id' => $value,
691
                 'customer_id' => $value,
655
                 'user_id'     => $userId,
692
                 'user_id'     => $userId,
656
-                'pool_id'     => $param['pool_id'],
693
+                'pool_id'     => $poolId,
657
                 'type'        => 3,
694
                 'type'        => 3,
658
                 'create_time' => time()
695
                 'create_time' => time()
659
             ];
696
             ];
755
         $data = !empty($data) ? json_decode($data, true) :[];
792
         $data = !empty($data) ? json_decode($data, true) :[];
756
 
793
 
757
         if (!empty($data)) {
794
         if (!empty($data)) {
795
+            $exceptFields = db('admin_field')->where(['types' => 'crm_customer', 'form_type' => ['in', ['file', 'handwriting_sign', 'desc_text', 'detail_table']]])->column('field');
796
+
758
             foreach ($data AS $key => $value) {
797
             foreach ($data AS $key => $value) {
798
+                if (in_array($value['field'], $exceptFields)) continue;
799
+
759
                 if (!empty($value['is_hidden'])) {
800
                 if (!empty($value['is_hidden'])) {
760
                     $hideList[] = $value;
801
                     $hideList[] = $value;
761
                 } else {
802
                 } else {
764
             }
805
             }
765
         } else {
806
         } else {
766
             # 公海字段-后台配置数据
807
             # 公海字段-后台配置数据
767
-            $poolField = db('crm_customer_pool_field_setting')->where('pool_id', $param['pool_id'])->select();
808
+            $where = [
809
+                'pool_id'   => $param['pool_id'],
810
+                'is_hidden' => 0,
811
+                'form_type' => ['notin', ['file', 'handwriting_sign', 'desc_text', 'detail_table']]
812
+            ];
813
+            $poolField = db('crm_customer_pool_field_setting')->where($where)->select();
768
             foreach ($poolField AS $key => $value) {
814
             foreach ($poolField AS $key => $value) {
769
                 if (empty($value['is_hidden'])) {
815
                 if (empty($value['is_hidden'])) {
770
                     $showList[] = [
816
                     $showList[] = [

+ 89
- 100
application/crm/logic/IndexLogic.php Bestand weergeven

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
+        $last_between_time = ByDateTime($param['type']);
40
         if($param['start_time'] && $param['end_time']){
41
         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';
42
+            $param['start_time']=$param['start_time'].' 00:00:00';
43
+            $param['end_time']=$param['end_time'].' 23:59:59';
43
         }
44
         }
44
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
45
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
45
-        $lastArr = $adminModel->getWhere($param, 1, '', true); //统计条件
46
+//        $lastArr = $adminModel->getWhere($param, 1, '', true); //统计条件
46
         $userIds = $whereArr['userIds'];
47
         $userIds = $whereArr['userIds'];
47
         $between_time = $whereArr['between_time'];
48
         $between_time = $whereArr['between_time'];
48
-        $last_between_time = $lastArr['between_time'];
49
-        
50
-        
49
+   
51
         $customerNum = 0; //新增客户
50
         $customerNum = 0; //新增客户
52
         $customerLastNum = 0; //上期对比
51
         $customerLastNum = 0; //上期对比
53
         $contactsNum = 0; //新增联系人
52
         $contactsNum = 0; //新增联系人
89
                 'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? :[-1],
88
                 'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? :[-1],
90
             ])
89
             ])
91
         );
90
         );
92
-        
93
         $resLastCount = queryCache(
91
         $resLastCount = queryCache(
94
             $this->getCountSql([
92
             $this->getCountSql([
95
-                'start_time' => $last_between_time[0],
96
-                'end_time' => $last_between_time[1],
93
+                'start_time' => $last_between_time['last_time'][0],
94
+                'end_time' => $last_between_time['last_time'][1],
97
                 'customer_auth_user_ids' => array_intersect($userIds, $customer_auth_user_ids) ? : [-1],
95
                 'customer_auth_user_ids' => array_intersect($userIds, $customer_auth_user_ids) ? : [-1],
98
                 'contacts_auth_user_ids' => array_intersect($userIds, $contacts_auth_user_ids) ? : [-1],
96
                 'contacts_auth_user_ids' => array_intersect($userIds, $contacts_auth_user_ids) ? : [-1],
99
                 'business_auth_user_ids' => array_intersect($userIds, $business_auth_user_ids) ? : [-1],
97
                 'business_auth_user_ids' => array_intersect($userIds, $business_auth_user_ids) ? : [-1],
120
         $contractLastMoneyNum = $resLastCount[3]['count2'] ?: 0;
118
         $contractLastMoneyNum = $resLastCount[3]['count2'] ?: 0;
121
         $receivablesLastMoneyNum = $resLastCount[4]['count'] ?: 0;
119
         $receivablesLastMoneyNum = $resLastCount[4]['count'] ?: 0;
122
         $recordLastNum = (int)$resLastCount[5]['count'] ?: 0;
120
         $recordLastNum = (int)$resLastCount[5]['count'] ?: 0;
123
-        
124
         $data = [];
121
         $data = [];
125
         $data['data']['customerNum'] = $customerNum;
122
         $data['data']['customerNum'] = $customerNum;
126
         $data['prev']['customerNum'] = $this->getProportion($customerNum, $customerLastNum);
123
         $data['prev']['customerNum'] = $this->getProportion($customerNum, $customerLastNum);
145
         
142
         
146
         $data['data']['receivablesMoneyNum'] = $receivablesMoneyNum;
143
         $data['data']['receivablesMoneyNum'] = $receivablesMoneyNum;
147
         $data['prev']['receivablesMoneyNum'] = $this->getProportion($receivablesMoneyNum, $receivablesLastMoneyNum);
144
         $data['prev']['receivablesMoneyNum'] = $this->getProportion($receivablesMoneyNum, $receivablesLastMoneyNum);
145
+        
148
         return $data;
146
         return $data;
149
     }
147
     }
150
     
148
     
151
     public function getCountSql($param)
149
     public function getCountSql($param)
152
     {
150
     {
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'] = '未成交';
161
         $countSql = "SELECT
151
         $countSql = "SELECT
162
         count(1) count1,
152
         count(1) count1,
163
         0 count2
153
         0 count2
210
     ///计算涨幅
200
     ///计算涨幅
211
     public function getProportion($now, $last)
201
     public function getProportion($now, $last)
212
     {
202
     {
213
-        $res = 0;
214
         if ($last && $last != 0.00) {
203
         if ($last && $last != 0.00) {
215
-            if ($now && $now != 0.00) {
216
-                $res = round(($now / $last), 2);
217
-            }
204
+                if($now-$last>0){
205
+                    $res = round(($now-$last) / $last,2);
206
+                }else{
207
+                    $res  =round(($now-$last) / $last,2);
208
+                }
218
         } else {
209
         } else {
219
-            if ($now && $now != 0.00) {
220
-                $res = 1;
221
-            }
210
+                $res = 0;
222
         }
211
         }
223
         return $res;
212
         return $res;
224
     }
213
     }
363
                     ->field([
352
                     ->field([
364
                         'SUM(CASE WHEN check_status = 2 THEN money ELSE 0 END) as money',
353
                         'SUM(CASE WHEN check_status = 2 THEN money ELSE 0 END) as money',
365
                         'contract.owner_user_id as owner_user_id',
354
                         'contract.owner_user_id as owner_user_id',
366
-                        'user.realname as realname',
367
-                        'user.id',
368
-                        'user.thumb_img',
369
-                        'structure.name'
370
                     ])
355
                     ])
371
                     ->where([
356
                     ->where([
372
                         'contract.owner_user_id' => ['in', $auth_user_ids],
357
                         'contract.owner_user_id' => ['in', $auth_user_ids],
388
                     ->field([
373
                     ->field([
389
                         'SUM(CASE WHEN receivables.check_status = 2 THEN receivables.money ELSE 0 END) as money',
374
                         'SUM(CASE WHEN receivables.check_status = 2 THEN receivables.money ELSE 0 END) as money',
390
                         'receivables.owner_user_id as owner_user_id',
375
                         'receivables.owner_user_id as owner_user_id',
391
-                        'user.realname as realname',
392
-                        'user.id',
393
-                        'user.thumb_img',
394
-                        'structure.name'
395
                     ])
376
                     ])
396
                     ->where([
377
                     ->where([
397
                         'receivables.owner_user_id' => ['in', $auth_user_ids],
378
                         'receivables.owner_user_id' => ['in', $auth_user_ids],
414
                     ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
395
                     ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
415
                     ->field([
396
                     ->field([
416
                         'count(contract.contract_id) as count',
397
                         'count(contract.contract_id) as count',
417
-                        'user.realname as realname',
418
-                        'user.id',
419
-                        'user.thumb_img',
420
-                        'structure.name',
421
                         'contract.owner_user_id as owner_user_id'])
398
                         'contract.owner_user_id as owner_user_id'])
422
                     ->where([
399
                     ->where([
423
                         'contract.owner_user_id' => ['in', $auth_user_ids],
400
                         'contract.owner_user_id' => ['in', $auth_user_ids],
440
                     ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
417
                     ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
441
                     ->field([
418
                     ->field([
442
                         'count(customer.customer_id) as count',
419
                         'count(customer.customer_id) as count',
443
-                        'user.realname as realname',
444
-                        'user.id',
445
-                        'user.thumb_img',
446
-                        'structure.name',
447
                         'customer.owner_user_id as owner_user_id'])
420
                         'customer.owner_user_id as owner_user_id'])
448
                     ->where(
421
                     ->where(
449
                         'customer.owner_user_id' ,['in', $auth_user_ids]
422
                         'customer.owner_user_id' ,['in', $auth_user_ids]
462
                     ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
435
                     ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
463
                     ->field([
436
                     ->field([
464
                         'count(contacts.contacts_id) as count',
437
                         'count(contacts.contacts_id) as count',
465
-                        'user.realname as realname',
466
-                        'user.id',
467
-                        'user.thumb_img',
468
-                        'structure.name',
469
                         'contacts.contacts_id',
438
                         'contacts.contacts_id',
470
                         'contacts.owner_user_id as owner_user_id'])
439
                         'contacts.owner_user_id as owner_user_id'])
471
                     ->where([
440
                     ->where([
484
                     ->join('__ADMIN_USER__ user', 'activity.create_user_id=user.id')
453
                     ->join('__ADMIN_USER__ user', 'activity.create_user_id=user.id')
485
                     ->field([
454
                     ->field([
486
                         'count(activity.activity_id) as count',
455
                         'count(activity.activity_id) as count',
487
-                        'user.realname as realname',
488
-                        'user.id',
489
-                        'user.thumb_img',
490
                         'activity.create_user_id as create_user_id'])
456
                         'activity.create_user_id as create_user_id'])
491
                     ->where([
457
                     ->where([
492
                         'activity.create_user_id' => ['in', $auth_user_ids],
458
                         'activity.create_user_id' => ['in', $auth_user_ids],
500
                     ->select();
466
                     ->select();
501
                 break;
467
                 break;
502
         }
468
         }
503
-        
469
+        foreach ($list as $k=>$v){
470
+            $userInfo=$userModel->getUserById($v['owner_user_id']);
471
+           if(!empty($v['create_user_id'])){
472
+               $userInfo=$userModel->getUserById($v['create_user_id']);
473
+           }
474
+            $list[$k]['realname']= $userInfo['realname'];
475
+            $list[$k]['id']= $userInfo['id'];
476
+            $list[$k]['thumb_img']=$userInfo['thumb_img'] ? getFullPath($v['thumb_img']) : '';
477
+        }
504
         //业绩目标
478
         //业绩目标
505
         $between_time = getTimeByType($param['type']);
479
         $between_time = getTimeByType($param['type']);
506
         $start_time = $between_time[0];
480
         $start_time = $between_time[0];
587
         $business_auth_user_ids = $userModel->getUserByPer('crm', 'business', 'index');
561
         $business_auth_user_ids = $userModel->getUserByPer('crm', 'business', 'index');
588
         $contract_auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'index');
562
         $contract_auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'index');
589
         $receivables_auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index');
563
         $receivables_auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index');
564
+        $receivablesPlan_auth_user_ids = $userModel->getUserByPer('crm', 'receivables_plan', 'index');
590
         $record_auth_user_ids = $userModel->getUserByPer('crm', 'activity', 'index');
565
         $record_auth_user_ids = $userModel->getUserByPer('crm', 'activity', 'index');
591
-        
592
         $resDataArr = [];
566
         $resDataArr = [];
593
-        for ($i = 1; $i <= 5; $i++) {
567
+        for ($i = 1; $i <= 6; $i++) {
594
             $resData = queryCache(
568
             $resData = queryCache(
595
                 $this->getQueryDataSql([
569
                 $this->getQueryDataSql([
596
                     'type' => $i,
570
                     'type' => $i,
602
                     'contract_auth_user_ids' => array_intersect($userIds, $contract_auth_user_ids) ? : [-1],
576
                     'contract_auth_user_ids' => array_intersect($userIds, $contract_auth_user_ids) ? : [-1],
603
                     'receivables_auth_user_ids' => array_intersect($userIds, $receivables_auth_user_ids) ? : [-1],
577
                     'receivables_auth_user_ids' => array_intersect($userIds, $receivables_auth_user_ids) ? : [-1],
604
                     'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? : [-1],
578
                     'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? : [-1],
579
+                    '$receivablesPlan_auth_user_ids' => array_intersect($userIds, $receivablesPlan_auth_user_ids) ? : [-1],
605
                 ])
580
                 ])
606
             );
581
             );
607
             $resDataArr = array_merge($resDataArr, $resData[0]);
582
             $resDataArr = array_merge($resDataArr, $resData[0]);
661
                 SUM( CASE WHEN check_status = 2 THEN money ELSE 0 END) AS contractMoney
636
                 SUM( CASE WHEN check_status = 2 THEN money ELSE 0 END) AS contractMoney
662
                 FROM 5kcrm_crm_contract
637
                 FROM 5kcrm_crm_contract
663
                 WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
638
                 WHERE create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
664
-                AND owner_user_id IN (" . implode(',', $param['business_auth_user_ids']) . ")";
639
+                AND owner_user_id IN (" . implode(',', $param['contract_auth_user_ids']) . ")";
665
                 break;
640
                 break;
666
             case 5 :
641
             case 5 :
642
+                $start_time=date('Y-m-d',$param['start_time']);
643
+                $end_time=date('Y-m-d',$param['end_time']);
667
                 $countSql = "SELECT
644
                 $countSql = "SELECT
668
-                SUM( CASE WHEN r.check_status = 2 THEN r.money ELSE 0 END) AS receivablesMoney,
669
-                SUM(CASE WHEN p.money > 0 THEN p.money ELSE 0 END) AS planMoney
645
+                SUM( CASE WHEN r.check_status = 2 THEN r.money ELSE 0 END) AS receivablesMoney
670
                 FROM 5kcrm_crm_receivables as r
646
                 FROM 5kcrm_crm_receivables as r
671
-                LEFT JOIN 5kcrm_crm_receivables_plan AS p ON p.receivables_id = r.receivables_id
672
-                WHERE r.create_time BETWEEN " . $param['start_time'] . " AND " . $param['end_time'] . "
673
-                AND r.owner_user_id IN (" . implode(',', $param['business_auth_user_ids']) . ")";
647
+                WHERE r.create_time BETWEEN " .  "'".$start_time."'" . " AND " ."'".$end_time."'" . "
648
+                AND r.owner_user_id IN (" . implode(',', $param['receivables_auth_user_ids']) . ")";
649
+                break;
650
+            case 6 :
651
+                $start_time=date('Y-m-d',$param['start_time']);
652
+                $end_time=date('Y-m-d',$param['end_time']);
653
+                $countSql = "SELECT
654
+                SUM(r.money) AS planMoney
655
+                FROM 5kcrm_crm_receivables_plan as r
656
+                WHERE r.return_date BETWEEN " . "'".$start_time."'" . " AND " ."'". $end_time."'"  . " AND r.receivables_id = 0
657
+                AND r.owner_user_id IN (" . implode(',', $param['receivables_auth_user_ids']) . ")";
674
                 break;
658
                 break;
675
         }
659
         }
676
-        
677
         return $countSql;
660
         return $countSql;
678
     }
661
     }
679
     
662
     
680
     /**
663
     /**
681
-     * 赢单输单查看
664
+     * 销售漏斗查看
682
      */
665
      */
683
     public function businessList($param)
666
     public function businessList($param)
684
     {
667
     {
685
-        $userModel = new \app\admin\model\User();
686
         $adminModel = new \app\admin\model\Admin();
668
         $adminModel = new \app\admin\model\Admin();
687
         if($param['start_time'] && $param['end_time']){
669
         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';
670
+            $between_time[0]=$param['start_time'].'00:00:00';
671
+            $between_time[1]=$param['end_time'].'23:59:59';
690
         }
672
         }
691
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
673
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
692
-        $user_id = $param['user_id'] ?: [-1];
693
         $userIds = $whereArr['userIds'];
674
         $userIds = $whereArr['userIds'];
694
         $between_time = $whereArr['between_time'];
675
         $between_time = $whereArr['between_time'];
695
-        //权限控制
696
-        $where_customer['create_time'] = array('between', $between_time);
697
-        $auth_customer_user_ids = $userModel->getUserByPer('bi', 'ranking', 'read');
698
-        $auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集
699
-        $where_customer['owner_user_id'] = array('in', $auth_customer_user_ids);
700
-        $businessList = db('crm_business')
701
-            ->where([
702
-                'owner_user_id' => $where_customer['owner_user_id'],
703
-                'create_time' => $where_customer['create_time'],
704
-                'status_id' => $param['status_id']
705
-            ])
706
-            ->select();
707
-        $data = [];
708
-        $data['businesslist'] = $businessList;
676
+        $start_time = $between_time[0];
677
+        $end_time = $between_time[1];
678
+        //场景默认全部
679
+        $scene_id = db('admin_scene')->where(['types' => 'crm_business', 'bydata' => 'all'])->value('scene_id');
680
+        $param['scene_id'] = $scene_id ?: '';
681
+        $param['create_time']['start'] = $start_time;
682
+        $param['create_time']['end'] = $end_time;
683
+        
684
+        $param['owner_user_id']['value'] =  $userIds;
685
+        unset($param['type']);
686
+        unset($param['dataType']);
687
+        unset($param['label']);
688
+        unset($param['log_type']);
689
+        unset($param['types']);
690
+        $businessModel = new \app\crm\model\Business();
691
+        $data=$businessModel->getDataList($param);
709
         return $data;
692
         return $data;
710
     }
693
     }
711
     
694
     
792
         $auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集
775
         $auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集
793
         $where_activity['t.create_user_id'] = array('in', $auth_customer_user_ids);
776
         $where_activity['t.create_user_id'] = array('in', $auth_customer_user_ids);
794
         # 跟进记录类型
777
         # 跟进记录类型
795
-        $where_activity['t.activity_type'] = $param['activity_type'];
778
+        $where_activity['t.activity_type'] = $param['activity_type']?:['elt',7];
796
         $where_activity['t.type'] = 1;
779
         $where_activity['t.type'] = 1;
797
         $where_activity['t.status'] = 1;
780
         $where_activity['t.status'] = 1;
798
-        if ($param['label'] == 2) {
781
+        if ($param['label'] != 1) {
799
             if ($param['search']) {
782
             if ($param['search']) {
800
                 $type['t.content'] = array('like', '%' . $param['search'] . '%');
783
                 $type['t.content'] = array('like', '%' . $param['search'] . '%');
801
             }
784
             }
822
                 $type['t.type'] = $param['queryType'];
805
                 $type['t.type'] = $param['queryType'];
823
             }
806
             }
824
             if ($param['user_id'] == '') {
807
             if ($param['user_id'] == '') {
825
-                if ($param['subUser'] == '0') {
808
+               
809
+                if ($param['subUser'] === "0" || $param['subUser']===0) {
826
                     $type['t.create_user_id'] = $param['id'];
810
                     $type['t.create_user_id'] = $param['id'];
827
                     //下属创建
811
                     //下属创建
828
                 } elseif ($param['subUser'] == '1') {
812
                 } elseif ($param['subUser'] == '1') {
829
                     $subList = getSubUserId(false, 0, $param['id']);
813
                     $subList = getSubUserId(false, 0, $param['id']);
830
                     $subStr = $subList ? implode(',', $subList) : '-1';
814
                     $subStr = $subList ? implode(',', $subList) : '-1';
831
                     $type['t.create_user_id'] = array('in', $subStr);
815
                     $type['t.create_user_id'] = array('in', $subStr);
832
-                } elseif ($param['subUser'] == '') {
816
+                } else {
833
                     $userIds = getSubUserId(true, 0, $param['id']);
817
                     $userIds = getSubUserId(true, 0, $param['id']);
834
                     $subStr = $userIds ? implode(',', $userIds) : '-1';
818
                     $subStr = $userIds ? implode(',', $userIds) : '-1';
835
                     $type['t.create_user_id'] = array('in', $subStr);
819
                     $type['t.create_user_id'] = array('in', $subStr);
846
                 ->page($param['page'], $param['limit'])
830
                 ->page($param['page'], $param['limit'])
847
                 ->order('t.create_time desc')
831
                 ->order('t.create_time desc')
848
                 ->select();
832
                 ->select();
833
+            if($param['is_excel']){
834
+                $list = db('crm_activity')
835
+                    ->alias('t')
836
+                    ->join('__ADMIN_USER__ user', 'user.id = t.create_user_id', 'LEFT')
837
+                    ->field('t.content,t.next_time,t.category,t.activity_type,t.type,t.activity_id,t.activity_type_id,t.update_time,t.create_time,user.realname as create_user_name,user.thumb_img')
838
+                    ->where($type)
839
+                    ->order('t.create_time desc')
840
+                    ->select();
841
+            }
849
             $dataCount = db('crm_activity')
842
             $dataCount = db('crm_activity')
850
                 ->alias('t')
843
                 ->alias('t')
851
                 ->join('__ADMIN_USER__ user', 'user.id = t.create_user_id', 'LEFT')
844
                 ->join('__ADMIN_USER__ user', 'user.id = t.create_user_id', 'LEFT')
864
                     $activity_contacts = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->select();
857
                     $activity_contacts = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->select();
865
                     $list[$k]['business_list'] = $activity_business ?: [];
858
                     $list[$k]['business_list'] = $activity_business ?: [];
866
                     $list[$k]['contacts_list'] = $activity_contacts ?: [];
859
                     $list[$k]['contacts_list'] = $activity_contacts ?: [];
867
-                }
860
+                  
861
+                   }
868
                 
862
                 
869
                 if ($v['activity_type'] == 3) {
863
                 if ($v['activity_type'] == 3) {
870
                     $activity_name = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->find();
864
                     $activity_name = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->find();
901
                             $imgList[] = $val;
895
                             $imgList[] = $val;
902
                         }
896
                         }
903
                     }
897
                     }
904
-                }
898
+                };
905
                 $list[$k]['fileList'] = $fileList ?: [];
899
                 $list[$k]['fileList'] = $fileList ?: [];
906
                 $list[$k]['imgList'] = $imgList ?: [];
900
                 $list[$k]['imgList'] = $imgList ?: [];
907
-                $dataInfo['customerList'] = $relation_list['customer_list'] ?: [];
908
-                $dataInfo['contactsList'] = $relation_list['contacts_list'] ?: [];
909
-                $dataInfo['businessList'] = $relation_list['business_list'] ?: [];
910
-                $dataInfo['contractList'] = $relation_list['contract_list'] ?: [];
901
+               
902
+                $dataInfo['customerList'] = $relation_list['customerList'] ?: [];
903
+                $dataInfo['contactsList'] = $relation_list['contactsList'] ?: [];
904
+                $dataInfo['businessList'] = $relation_list['businessList'] ?: [];
905
+                $dataInfo['contractList'] = $relation_list['contractList'] ?: [];
906
+                $list[$k]['business_ids'] = implode(',',array_column($relation_list['businessList'],'name'));
907
+                $list[$k]['contacts_ids'] = implode(',',array_column($relation_list['contactsList'],'name'));
911
                 $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
908
                 $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
912
                 $list[$k]['dataInfo'] = $dataInfo ?: [];
909
                 $list[$k]['dataInfo'] = $dataInfo ?: [];
913
-                
914
-                $list[$k]['relation'] = arrayToString(array_column($relationArr['businessList'], 'name')) . ' ' .
915
-                    arrayToString(array_column($relationArr['contactsList'], 'name')) . ' ' .
916
-                    arrayToString(array_column($relationArr['contractList'], 'name')) . ' ' .
917
-                    arrayToString(array_column($relationArr['customerList'], 'name'));
918
-                
919
             }
910
             }
920
         } else {
911
         } else {
921
             $list = db('crm_activity')
912
             $list = db('crm_activity')
981
                 }
972
                 }
982
                 $list[$k]['fileList'] = $fileList ?: [];
973
                 $list[$k]['fileList'] = $fileList ?: [];
983
                 $list[$k]['imgList'] = $imgList ?: [];
974
                 $list[$k]['imgList'] = $imgList ?: [];
984
-                $dataInfo['customerList'] = $relation_list['customer_list'] ?: [];
985
-                $dataInfo['contactsList'] = $relation_list['contacts_list'] ?: [];
986
-                $dataInfo['businessList'] = $relation_list['business_list'] ?: [];
987
-                $dataInfo['contractList'] = $relation_list['contract_list'] ?: [];
975
+                $dataInfo['customerList'] = $relation_list['customerList'] ?: [];
976
+                $dataInfo['contactsList'] = $relation_list['contactsList'] ?: [];
977
+                $dataInfo['businessList'] = $relation_list['businessList'] ?: [];
978
+                $dataInfo['contractList'] = $relation_list['contractList'] ?: [];
988
                 $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
979
                 $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
989
                 $list[$k]['dataInfo'] = $dataInfo ?: [];
980
                 $list[$k]['dataInfo'] = $dataInfo ?: [];
990
-                $list[$k]['contacts_ids'] = arrayToString(array_column($relationArr['contactsList'], 'name'));
991
-                $list[$k]['business_ids'] = arrayToString(array_column($relationArr['businessList'], 'name'));
992
             }
981
             }
993
         }
982
         }
994
         
983
         
1002
         } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
991
         } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
1003
             $data['firstPage'] = false;
992
             $data['firstPage'] = false;
1004
             $data['lastPage'] = false;
993
             $data['lastPage'] = false;
1005
-        } else if ($param['page'] == 1) {
994
+        } else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
1006
             $data['firstPage'] = true;
995
             $data['firstPage'] = true;
1007
             $data['lastPage'] = false;
996
             $data['lastPage'] = false;
1008
         }
997
         }

+ 244
- 137
application/crm/logic/InvoiceLogic.php Bestand weergeven

16
 class InvoiceLogic
16
 class InvoiceLogic
17
 {
17
 {
18
     private $invoiceType = ['增值税专用发票', '增值税普通发票', '国税通用机打发票', '地税通用机打发票', '收据'];
18
     private $invoiceType = ['增值税专用发票', '增值税普通发票', '国税通用机打发票', '地税通用机打发票', '收据'];
19
-
19
+    private $check_status = ['待审核', '审核中', '审核通过', '审核未通过', '撤回'];
20
+    
20
     /**
21
     /**
21
      * 列表
22
      * 列表
22
      *
23
      *
25
      * @return array
26
      * @return array
26
      * @throws \think\exception\DbException
27
      * @throws \think\exception\DbException
27
      */
28
      */
28
-    public function index($param, $search = false)
29
+    public function index($param)
29
     {
30
     {
30
-        $field = [
31
-            'invoice_id',
32
-            'invoice_apple_number',
33
-            'invoice_money',
34
-            'invoice_date',
35
-            'real_invoice_date',
36
-            'invoice_type',
37
-            'invoice_number',
38
-            'logistics_number',
39
-            'check_status',
40
-            'invoice_status',
41
-            'customer_id',
42
-            'contract_id',
43
-            'owner_user_id',
44
-            'flow_id'
45
-        ];
46
-
47
-        $limit = $param['limit'];
31
+        $fieldModel = new \app\admin\model\Field();
32
+        //列表展示字段
33
+        $field = $fieldModel->getIndexField('crm_invoice', $param['user_id'], 1) ?: array('name');
34
+        if (!empty($param['is_excel']) && !empty($param['invoice_id'])) {
35
+            $param['invoice_id'] = ['in', arrayToString($param['invoice_id'])];
36
+        }
48
         $getCount = $param['getCount'];
37
         $getCount = $param['getCount'];
49
-        $userId   = $param['user_id'];
38
+        $userId = $param['user_id'];
50
         $invoiceIdArray = $param['invoiceIdArray']; // 待办事项提醒参数
39
         $invoiceIdArray = $param['invoiceIdArray']; // 待办事项提醒参数
51
         $dealt = $param['dealt'];
40
         $dealt = $param['dealt'];
52
-
41
+        $order_field = $param['order_field'];
42
+        $order_type = $param['order_type'];
43
+        $is_excel = $param['is_excel'];
44
+        $search = $param['search'];
45
+        $scene_id = $param['scene_id'];
46
+        $isMessage = !empty($param['isMessage']);
47
+        $common = new Common();
48
+        
53
         unset($param['getCount']);
49
         unset($param['getCount']);
54
-        unset($param['limit']);
55
-        unset($param['page']);
50
+//        unset($param['limit']); 导出使用 暂未发现为何去掉分页参数
51
+//        unset($param['page']);
56
         unset($param['user_id']);
52
         unset($param['user_id']);
57
         unset($param['invoiceIdArray']);
53
         unset($param['invoiceIdArray']);
58
         unset($param['dealt']);
54
         unset($param['dealt']);
59
-
55
+        unset($param['search']);
56
+        unset($param['order_field']);
57
+        unset($param['order_type']);
58
+        unset($param['is_excel']);
59
+        unset($param['scene_id']);
60
+        unset($param['isMessage']);
61
+        $request = $common->fmtRequest($param);
60
         $where = [];
62
         $where = [];
63
+       
64
+        # 高级搜索
65
+        $requestMap = !empty($request['map']) ? $request['map'] : [];
66
+        unset($requestMap['search']);
67
+        
68
+        # 场景
69
+        $sceneMap = [];
70
+        $sceneModel = new \app\admin\model\Scene();
71
+        if ($scene_id) {
72
+            //自定义场景
73
+            $sceneMap = $sceneModel->getDataById($scene_id, $userId, 'invoice') ?: [];
74
+        } else {
75
+            //默认场景
76
+            $sceneMap = $sceneModel->getDefaultData('crm_invoice', $userId) ?: [];
77
+        }
78
+        //普通筛选
61
         if ($search) {
79
         if ($search) {
62
             # 处理基本参数
80
             # 处理基本参数
63
-
64
-            $scene_id = $param['scene_id'];
65
-            unset($param['scene_id']);
66
-
67
-            $common = new Common();
68
-
69
-            # 高级搜索
70
-            $request    = $common->fmtRequest($param);
71
-            $requestMap = !empty($request['map']) ? $request['map'] : [];
72
-            unset($requestMap['search']);
73
-
74
-            # 场景
75
-            $sceneMap = [];
76
-            if (!empty($scene_id) && $scene_id == 1) {
77
-                # 我负责的
78
-                $sceneMap['owner_user_id'] = $userId;
79
-            }
80
-            if (!empty($scene_id) && $scene_id == 2) {
81
-                # 我下属负责的
82
-                $subordinate = getSubUserId(false, 0, $userId);
83
-                $sceneMap['owner_user_id'] = !empty($subordinate) ? ['in', $subordinate] : 0;
84
-            }
85
-
86
-            # 合并高级搜索和场景的查询条件
87
-            $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
88
-            $map = where_arr($map, 'crm', 'invoice', 'index');
89
-
90
-            # 替换掉字段前缀,不修改公共函数
91
-            foreach ($map AS $key => $value) {
92
-                $k = str_replace('invoice.', '', $key);
93
-
94
-                $where[$k] = $value;
95
-            }
96
-
97
-            # 重置查询条件
98
-            if ($where) $param = $where;
81
+            $searchWhere = function ($query) use ($search) {
82
+                $query->where(function ($query) use ($search) {
83
+                    $query->whereLike('customer.name', '%' . $search . '%');
84
+                })->whereOr(function ($query) use ($search) {
85
+                    $query->whereLike('contract.num', '%' . $search . '%');
86
+                })->whereOr(function ($query) use ($search) {
87
+                    $query->whereLike('invoice.invoice_apple_number', '%' . $search . '%');
88
+                });
89
+            };
90
+        }
91
+        # 合并高级搜索和场景的查询条件
92
+        $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
93
+        $map = where_arr($map, 'crm', 'invoice', 'index');
94
+        # 替换掉字段前缀,不修改公共函数
95
+        foreach ($map as $key => $value) {
96
+            $k = str_replace('invoice.', '', $key);
97
+            
98
+            $where[$k] = $value;
99
         }
99
         }
100
-
101
         # 待办事项查询参数
100
         # 待办事项查询参数
102
         $dealtWhere = [];
101
         $dealtWhere = [];
103
-        if (!empty($invoiceIdArray)) $dealtWhere['invoice_id'] = ['in', $invoiceIdArray];
104
-
102
+        if (!empty($invoiceIdArray)) $dealtWhere['invoice.invoice_id'] = ['in', $invoiceIdArray];
103
+        
105
         # 权限,不是待办事项,则加上列表权限
104
         # 权限,不是待办事项,则加上列表权限
106
         $auth = [];
105
         $auth = [];
106
+        $userModel = new \app\admin\model\User();
107
+        $a = 'index';
108
+        if ($is_excel) $a = 'excelExport';
109
+        $auth_user_ids = $userModel->getUserByPer('crm', 'invoice', $a);
107
         if (empty($dealt)) {
110
         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
+            if (isset($map['invoice.owner_user_id']) && $map['invoice.owner_user_id'][0] != 'like') {
113
+                if (!is_array($map['invoice.owner_user_id'][1])) {
114
+                    $map['invoice.owner_user_id'][1] = [$map['invoice.owner_user_id'][1]];
115
+                }
116
+                if (in_array($map['invoice.owner_user_id'][0], ['neq', 'notin'])) {
117
+                    $auth_user_ids = array_diff($auth_user_ids, $map['invoice.owner_user_id'][1]) ?: [];    //取差集
118
+                } else {
119
+                    $auth_user_ids = array_intersect($map['invoice.owner_user_id'][1], $auth_user_ids) ?: [];    //取交集
120
+                }
121
+                unset($map['invoice.owner_user_id']);
122
+            }
111
         }
123
         }
112
-
124
+        $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
125
+        // 待办事项的待审核发票不一定是自己创建的
126
+        if (!$isMessage) {
127
+            $auth['invoice.owner_user_id'] = ['in', $auth_user_ids];
128
+        }
129
+        if ($order_type && $order_field) {
130
+            $order = $fieldModel->getOrderByFormtype('crm_invoice', 'invoice', $order_field, $order_type);
131
+        } else {
132
+            $order = 'invoice.update_time desc';
133
+        }
134
+        $join = [
135
+            ['__CRM_CUSTOMER__ customer', 'customer.customer_id=invoice.customer_id', 'LEFT'],
136
+            ['__CRM_CONTRACT__ contract', 'contract.contract_id=invoice.contract_id', 'LEFT'],
137
+            ['__ADMIN_USER__ user', 'user.id=invoice.owner_user_id', 'LEFT'],
138
+            ['__ADMIN_USER__ u', 'u.id=invoice.create_user_id', 'LEFT'],
139
+        ];
113
         # 查询数据
140
         # 查询数据
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();
141
+        $list = db('crm_invoice')
142
+            ->alias('invoice')
143
+            ->join($join)
144
+            ->field(array_merge($field, [
145
+                'customer.name' => 'customer_name',
146
+                'user.realname' => 'owner_user_name',
147
+                'contract.num' => 'contract_num',
148
+                'contract.money' => 'contract_money',
149
+                'u.realname' => 'create_user_name',
150
+            ]))->where($auth)
151
+            ->where($map)
152
+            ->where($dealtWhere)
153
+            ->where($searchWhere)
154
+            ->limit($request['offset'], $request['length'])
155
+            ->orderRaw($order)
156
+            ->select();
157
+        
158
+        $dataCount = db('crm_invoice')
159
+            ->alias('invoice')
160
+            ->join($join)
161
+            ->field(array_merge($field, [
162
+                'customer.name' => 'customer_name',
163
+                'user.realname' => 'owner_user_name',
164
+                'contract.num' => 'contract_num',
165
+                'contract.money' => 'contract_money',
166
+                'u.realname' => 'create_user_name',
167
+            ]))->where($auth)
168
+            ->where($map)
169
+            ->where($dealtWhere)->where($searchWhere)->count();
170
+
171
+        $userField = $fieldModel->getFieldByFormType('crm_invoice', 'user'); //人员类型
172
+        $structureField = $fieldModel->getFieldByFormType('crm_invoice', 'structure');  //部门类型
173
+        $datetimeField = $fieldModel->getFieldByFormType('crm_invoice', 'datetime'); //日期时间类型
174
+        $booleanField = $fieldModel->getFieldByFormType('crm_invoice', 'boolean_value'); //布尔值
175
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_invoice', 'date_interval'); // 日期区间类型字段
176
+        $positionField = $fieldModel->getFieldByFormType('crm_invoice', 'position'); // 地址类型字段
177
+        $handwritingField = $fieldModel->getFieldByFormType('crm_invoice', 'handwriting_sign'); // 手写签名类型字段
178
+        $locationField = $fieldModel->getFieldByFormType('crm_invoice', 'location'); // 定位类型字段
179
+
180
+        # 扩展数据
181
+        $extraData = [];
182
+        $invoice_id_list = !empty($list) ? array_column($list, 'invoice_id') : [];
183
+        $extraList = db('crm_invoice_data')->whereIn('invoice_id', $invoice_id_list)->select();
184
+        foreach ($extraList AS $key => $value) {
185
+            $extraData[$value['invoice_id']][$value['field']] = $value['content'];
186
+        }
116
 
187
 
117
         # 处理发票类型
188
         # 处理发票类型
118
-//        foreach ($list['data'] AS $key => $value) {
119
-//            $list['data'][$key]['invoice_type'] = $this->invoiceType[$value['invoice_type']];
120
-//        }
121
-
122
-        return ['list' => $list['data'], 'dataCount' => $list['total']];
189
+        foreach ($list as $key => $value) {
190
+            $list[$key]['check_status_info'] = $this->check_status[$value['check_status']];
191
+            $list[$key]['invoice_status'] = !empty($value['invoice_status']) ? '已开票' : '未开票';
192
+            $list[$key]['create_time'] = !empty($value['create_time']) ? date('Y-m-d H:i:s',$value['create_time']) : null;
193
+            $list[$key]['update_time'] = !empty($value['update_time']) ? date('Y-m-d H:i:s',$value['update_time']) : null;
194
+            foreach ($userField as $k => $val) {
195
+                $usernameField = !empty($value[$val]) ? db('admin_user')->whereIn('id', stringToArray($value[$val]))->column('realname') : [];
196
+                $list[$key][$val] = implode($usernameField, ',');
197
+            }
198
+            foreach ($structureField as $k => $val) {
199
+                $structureNameField = !empty($value[$val]) ? db('admin_structure')->whereIn('id', stringToArray($value[$val]))->column('name') : [];
200
+                $list[$key][$val] = implode($structureNameField, ',');
201
+            }
202
+            foreach ($datetimeField as $k => $val) {
203
+                $list[$key][$val] = !empty($value[$val]) ? date('Y-m-d H:i:s', $value[$val]) : null;
204
+            }
205
+            foreach ($booleanField as $k => $val) {
206
+                $list[$key][$val] = !empty($value[$val]) ? (string)$value[$val] : '0';
207
+            }
208
+            // 处理日期区间类型字段的格式
209
+            foreach ($dateIntervalField as $k => $val) {
210
+                $list[$key][$val] = !empty($extraData[$value['invoice_id']][$val]) ? json_decode($extraData[$value['invoice_id']][$val], true) : null;
211
+            }
212
+            // 处理地址类型字段的格式
213
+            foreach ($positionField as $k => $val) {
214
+                $list[$key][$val] = !empty($extraData[$value['invoice_id']][$val]) ? json_decode($extraData[$value['invoice_id']][$val], true) : null;
215
+            }
216
+            // 手写签名类型字段
217
+            foreach ($handwritingField AS $k => $val) {
218
+                $handwritingData = !empty($value[$val]) ? db('admin_file')->where('file_id', $value[$val])->value('file_path') : null;
219
+                $list[$key][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
220
+            }
221
+            // 定位类型字段
222
+            foreach ($locationField as $k => $val) {
223
+                $list[$key][$val] = !empty($extraData[$value['invoice_id']][$val]) ? json_decode($extraData[$value['invoice_id']][$val], true) : null;
224
+            }
225
+        }
226
+        $data = [];
227
+        $data['list'] = $list ?: [];
228
+        $data['dataCount'] = $dataCount ?: 0;
229
+        return $data;
123
     }
230
     }
124
-
231
+    
125
     /**
232
     /**
126
      * 创建
233
      * 创建
127
      *
234
      *
132
     {
239
     {
133
         return db('crm_invoice')->insert($param, false, true);
240
         return db('crm_invoice')->insert($param, false, true);
134
     }
241
     }
135
-
242
+    
136
     /**
243
     /**
137
      * 详情
244
      * 详情
138
      *
245
      *
146
     public function read($invoiceId, $isUpdate)
253
     public function read($invoiceId, $isUpdate)
147
     {
254
     {
148
         $apiCommon = new ApiCommon();
255
         $apiCommon = new ApiCommon();
149
-
150
-        $userId     = $apiCommon->userInfo['id'];
151
-        $result     = [];
256
+        
257
+        $userId = $apiCommon->userInfo['id'];
258
+        $result = [];
152
         $dataObject = Invoice::with(['toCustomer', 'toContract'])->where('invoice_id', $invoiceId)->find();
259
         $dataObject = Invoice::with(['toCustomer', 'toContract'])->where('invoice_id', $invoiceId)->find();
153
-
260
+        
154
         if (empty($dataObject)) return $result;
261
         if (empty($dataObject)) return $result;
155
-
262
+        
156
         $dataArray = $dataObject->toArray();
263
         $dataArray = $dataObject->toArray();
157
-
264
+        
158
         if (!empty($isUpdate)) return $dataArray;
265
         if (!empty($isUpdate)) return $dataArray;
159
-
266
+        
160
         # 主键ID
267
         # 主键ID
161
         $result['invoice_id'] = $dataArray['invoice_id'];
268
         $result['invoice_id'] = $dataArray['invoice_id'];
162
-
269
+        
163
         # 是否显示撤回按钮
270
         # 是否显示撤回按钮
164
         $result['isShowRecall'] = 0;
271
         $result['isShowRecall'] = 0;
165
         if ($userId == $dataArray['owner_user_id'] && $dataArray['check_status'] == 0) $result['isShowRecall'] = 1;
272
         if ($userId == $dataArray['owner_user_id'] && $dataArray['check_status'] == 0) $result['isShowRecall'] = 1;
166
-
167
-        $result['customer_name']     = $dataArray['customer_name'];     # 客户名称
168
-        $result['invoice_money']     = $dataArray['invoice_money'];     # 开票金额
169
-        $result['invoice_number']    = $dataArray['invoice_number'];    # 发票号码
273
+        
274
+        $result['customer_name'] = $dataArray['customer_name'];     # 客户名称
275
+        $result['invoice_money'] = $dataArray['invoice_money'];     # 开票金额
276
+        $result['invoice_number'] = $dataArray['invoice_number'];    # 发票号码
170
         $result['real_invoice_date'] = $dataArray['real_invoice_date']; # 开票日期
277
         $result['real_invoice_date'] = $dataArray['real_invoice_date']; # 开票日期
171
-        $result['flow_id']           = $dataArray['flow_id'];           # 审核ID
172
-        $check=['0'=>'待审核','1'=>'审核中','2'=>'审核通过','3'=>'审核未通过','4'=>'撤销','5'=>'草稿(未提交)','6'=>'作废'];
278
+        $result['flow_id'] = $dataArray['flow_id'];           # 审核ID
279
+        $check = ['0' => '待审核', '1' => '审核中', '2' => '审核通过', '3' => '审核未通过', '4' => '撤销', '5' => '草稿(未提交)', '6' => '作废'];
173
         # 基本信息
280
         # 基本信息
174
         $result['essential'] = [
281
         $result['essential'] = [
175
             'invoice_apple_number' => $dataArray['invoice_apple_number'],
282
             'invoice_apple_number' => $dataArray['invoice_apple_number'],
176
-            'customer_name'        => $dataArray['customer_name'],
177
-            'contract_number'      => $dataArray['contract_number'],
178
-            'contract_money'       => $dataArray['contract_money'],
179
-            'invoice_money'        => $dataArray['invoice_money'],
180
-            'invoice_date'         => $dataArray['invoice_date'],
181
-            'invoice_type'         => $dataArray['invoice_type'],
182
-            'remark'               => $dataArray['remark'],
183
-            'create_user_name'     => db('admin_user')->where('id', $dataArray['create_user_id'])->value('realname'),
184
-            'owner_user_name'      => db('admin_user')->where('id', $dataArray['owner_user_id'])->value('realname'),
185
-            'create_time'          => $dataArray['create_time'],
186
-            'update_time'          => $dataArray['update_time'],
187
-            'invoice_number'       => $dataArray['invoice_number'],
188
-            'real_invoice_date'    => $dataArray['real_invoice_date'],
189
-            'customer_id'          => $dataArray['customer_id'],
190
-            'check_status'          => $check[$dataArray['check_status']]
283
+            'customer_name' => $dataArray['customer_name'],
284
+            'contract_num' => $dataArray['contract_number'],
285
+            'contract_money' => $dataArray['contract_money'],
286
+            'invoice_money' => $dataArray['invoice_money'],
287
+            'invoice_date' => $dataArray['invoice_date'],
288
+            'invoice_type' => $dataArray['invoice_type'],
289
+            'remark' => $dataArray['remark'],
290
+            'create_user_name' => db('admin_user')->where('id', $dataArray['create_user_id'])->value('realname'),
291
+            'owner_user_name' => db('admin_user')->where('id', $dataArray['owner_user_id'])->value('realname'),
292
+            'create_time' => $dataArray['create_time'],
293
+            'update_time' => $dataArray['update_time'],
294
+            'invoice_number' => $dataArray['invoice_number'],
295
+            'real_invoice_date' => $dataArray['real_invoice_date'],
296
+            'customer_id' => $dataArray['customer_id'],
297
+            'check_status' => $check[$dataArray['check_status']]
191
         ];
298
         ];
192
-
299
+        
193
         # 发票信息
300
         # 发票信息
194
         $result['invoice'] = [
301
         $result['invoice'] = [
195
-            'title_type'      => $dataArray['title_type'],
196
-            'deposit_bank'    => $dataArray['deposit_bank'],
197
-            'invoice_title'   => $dataArray['invoice_title'],
198
-            'tax_number'      => $dataArray['tax_number'],
302
+            'title_type' => $dataArray['title_type'],
303
+            'deposit_bank' => $dataArray['deposit_bank'],
304
+            'invoice_title' => $dataArray['invoice_title'],
305
+            'tax_number' => $dataArray['tax_number'],
199
             'deposit_account' => $dataArray['deposit_account'],
306
             'deposit_account' => $dataArray['deposit_account'],
200
             'deposit_address' => $dataArray['deposit_address'],
307
             'deposit_address' => $dataArray['deposit_address'],
201
-            'phone'           => $dataArray['phone']
308
+            'phone' => $dataArray['phone']
202
         ];
309
         ];
203
-
310
+        
204
         # 邮寄信息
311
         # 邮寄信息
205
-        $result['posting']   = [
206
-            'contacts_name'    => $dataArray['contacts_name'],
207
-            'contacts_mobile'  => $dataArray['contacts_mobile'],
312
+        $result['posting'] = [
313
+            'contacts_name' => $dataArray['contacts_name'],
314
+            'contacts_mobile' => $dataArray['contacts_mobile'],
208
             'contacts_address' => $dataArray['contacts_address']
315
             'contacts_address' => $dataArray['contacts_address']
209
         ];
316
         ];
210
-
317
+        
211
         return $result;
318
         return $result;
212
     }
319
     }
213
-
320
+    
214
     /**
321
     /**
215
      * 编辑
322
      * 编辑
216
      *
323
      *
221
     {
328
     {
222
         return Invoice::update($param);
329
         return Invoice::update($param);
223
     }
330
     }
224
-
331
+    
225
     /**
332
     /**
226
      * 删除
333
      * 删除
227
      *
334
      *
232
     {
339
     {
233
         return Invoice::destroy($where);
340
         return Invoice::destroy($where);
234
     }
341
     }
235
-
342
+    
236
     /**
343
     /**
237
      * 获取审批状态
344
      * 获取审批状态
238
      *
345
      *
249
         if ($isDelete) {
356
         if ($isDelete) {
250
             return Invoice::field(['check_status'])->whereIn('invoice_id', $invoiceId)->select();
357
             return Invoice::field(['check_status'])->whereIn('invoice_id', $invoiceId)->select();
251
         }
358
         }
252
-
359
+        
253
         # 编辑
360
         # 编辑
254
         return Invoice::where('invoice_id', $invoiceId)->value('check_status');
361
         return Invoice::where('invoice_id', $invoiceId)->value('check_status');
255
     }
362
     }
256
-
363
+    
257
     /**
364
     /**
258
      * 转移(变更负责人)
365
      * 转移(变更负责人)
259
      *
366
      *
265
     {
372
     {
266
         return Invoice::whereIn('invoice_id', $invoiceIds)->update(['owner_user_id' => $ownerUserId]);
373
         return Invoice::whereIn('invoice_id', $invoiceIds)->update(['owner_user_id' => $ownerUserId]);
267
     }
374
     }
268
-
375
+    
269
     /**
376
     /**
270
      * 设置开票
377
      * 设置开票
271
-     * 
378
+     *
272
      * @param $param
379
      * @param $param
273
      * @return Invoice
380
      * @return Invoice
274
      */
381
      */
276
     {
383
     {
277
         return Invoice::update($param);
384
         return Invoice::update($param);
278
     }
385
     }
279
-
386
+    
280
     /**
387
     /**
281
      * 获取发票审核信息
388
      * 获取发票审核信息
282
      *
389
      *
289
     public function getExamineInfo($invoiceId)
396
     public function getExamineInfo($invoiceId)
290
     {
397
     {
291
         $field = ['check_status', 'flow_id', 'order_id', 'check_user_id', 'flow_user_id', 'invoice_apple_number', 'owner_user_id', 'create_user_id'];
398
         $field = ['check_status', 'flow_id', 'order_id', 'check_user_id', 'flow_user_id', 'invoice_apple_number', 'owner_user_id', 'create_user_id'];
292
-
399
+        
293
         return Invoice::field($field)->where('invoice_id', $invoiceId)->find();
400
         return Invoice::field($field)->where('invoice_id', $invoiceId)->find();
294
     }
401
     }
295
-
402
+    
296
     /**
403
     /**
297
      * 设置审批信息
404
      * 设置审批信息
298
      *
405
      *
303
     {
410
     {
304
         return Invoice::update($data);
411
         return Invoice::update($data);
305
     }
412
     }
306
-
413
+    
307
     /**
414
     /**
308
      * 添加撤销审核记录
415
      * 添加撤销审核记录
309
      *
416
      *
316
     public function createExamineRecord($invoiceId, $examineInfo, $realname, $content, $userId)
423
     public function createExamineRecord($invoiceId, $examineInfo, $realname, $content, $userId)
317
     {
424
     {
318
         $data = [
425
         $data = [
319
-            'types'         => 'crm_invoice',
320
-            'types_id'      => $invoiceId,
321
-            'flow_id'       => $examineInfo['flow_id'],
322
-            'order_id'      => $examineInfo['order_id'],
426
+            'types' => 'crm_invoice',
427
+            'types_id' => $invoiceId,
428
+            'flow_id' => $examineInfo['flow_id'],
429
+            'order_id' => $examineInfo['order_id'],
323
             'check_user_id' => $userId,
430
             'check_user_id' => $userId,
324
-            'check_time'    => time(),
325
-            'status'        => 2,
326
-            'content'       => !empty($content) ? $content : $realname . ' 撤销了审核',
431
+            'check_time' => time(),
432
+            'status' => 2,
433
+            'content' => !empty($content) ? $content : $realname . ' 撤销了审核',
327
         ];
434
         ];
328
-
435
+        
329
         Db::name('admin_examine_record')->insert($data);
436
         Db::name('admin_examine_record')->insert($data);
330
     }
437
     }
331
-
438
+    
332
     /**
439
     /**
333
      * 检查发票编号是否重复
440
      * 检查发票编号是否重复
334
      *
441
      *

+ 272
- 0
application/crm/logic/MessageLogic.php Bestand weergeven

1
+<?php
2
+
3
+namespace app\crm\logic;
4
+
5
+use app\admin\model\Common;
6
+use app\crm\model\Customer;
7
+use think\Db;
8
+use function foo\func;
9
+
10
+class MessageLogic extends Common
11
+{
12
+    /**
13
+     *
14
+     * 今日续联系线索列表
15
+     * @param $param
16
+     *
17
+     * @author      alvin guogaobo
18
+     * @version     1.0 版本号
19
+     * @since       2021/5/24 0024 11:43
20
+     */
21
+    public function todayLeads($param)
22
+    {
23
+        $type = !empty($param['type']) ? $param['type'] : 1;
24
+        $isSub = !empty($param['isSub']) ? $param['isSub'] : 0;
25
+        $todayTime = getTimeByType('today');
26
+        unset($param['type']);
27
+        unset($param['isSub']);
28
+        $request = $this->where($param, $type, $isSub, $todayTime);
29
+        $leadsModel = new \app\crm\model\Leads();
30
+        $data = $leadsModel->getDataList($request);
31
+        return $data;
32
+    }
33
+    
34
+    /**
35
+     * 客户
36
+     * @param $request
37
+     *
38
+     * @author      alvin guogaobo
39
+     * @version     1.0 版本号
40
+     * @since       2021/5/25 0025 09:17
41
+     */
42
+    public function remindCustomer($param)
43
+    {
44
+        
45
+        $type = $param['type'] ?: 1;
46
+        $isSub = $param['isSub'] ?: '';
47
+        $todayTime = getTimeByType('today');
48
+        unset($param['type']);
49
+        unset($param['isSub']);
50
+        $request = $this->where($param, $type, $isSub, $todayTime);
51
+        $customerModel = model('Customer');
52
+        $data = $customerModel->getDataList($request);
53
+        return $data;
54
+    }
55
+    
56
+    /**
57
+     *
58
+     * @param $param
59
+     *
60
+     * @author      alvin guogaobo
61
+     * @version     1.0 版本号
62
+     * @since       2021/5/26 0026 10:13
63
+     */
64
+    public function todayBusiness($param)
65
+    {
66
+        $type = !empty($param['type']) ? $param['type'] : 1;
67
+        $isSub = !empty($param['isSub']) ? $param['isSub'] : 0;
68
+        $todayTime = getTimeByType('today');
69
+        unset($param['type']);
70
+        unset($param['isSub']);
71
+        $request = $this->where($param, $type, $isSub, $todayTime);
72
+        $businessModel = new \app\crm\model\Business();
73
+        $data = $businessModel->getDataList($request);
74
+        return $data;
75
+    }
76
+    
77
+    /**
78
+     * 分配给我的线索
79
+     * @param $param
80
+     *
81
+     * @author      alvin guogaobo
82
+     * @version     1.0 版本号
83
+     * @since       2021/5/26 0026 10:32
84
+     */
85
+    public function followLeads($param)
86
+    {
87
+        $type = $param['type'] ?: 1;
88
+        unset($param['type']);
89
+        $request = $this->where($param, $type, '', '');
90
+        $leadsModel = model('Leads');
91
+        $data = $leadsModel->getDataList($request);
92
+        return $data;
93
+    }
94
+    
95
+    /**
96
+     * 分配给我的客户
97
+     * @param $param
98
+     *
99
+     * @author      alvin guogaobo
100
+     * @version     1.0 版本号
101
+     * @since       2021/5/26 0026 10:36
102
+     */
103
+    public function followCustomer($param)
104
+    {
105
+        $type = $param['type'] ?: 1;
106
+        $isSub = $param['isSub'] ?: '';
107
+        unset($param['type']);
108
+        unset($param['isSub']);
109
+        $request = $this->where($param, $type, $isSub, '');
110
+        unset($param['user_id']);
111
+        $customerModel = model('Customer');
112
+        $data = $customerModel->getDataList($request);
113
+        return $data;
114
+    }
115
+    
116
+    /**
117
+     * @param $param
118
+     *
119
+     * @author      alvin guogaobo
120
+     * @version     1.0 版本号
121
+     * @since       2021/5/26 0026 11:42
122
+     */
123
+    public function checkContract($param)
124
+    {
125
+        $type = $param['type'] ?: 1;
126
+        unset($param['type']);
127
+        $contractModel = model('Contract');
128
+        $request = $this->whereCheck($param, $type);
129
+        $request['isMessage'] = true;
130
+        $data = $contractModel->getDataList($request);
131
+        return $data;
132
+    }
133
+    
134
+    /**
135
+     * 待审核回款
136
+     * @param $param
137
+     *
138
+     * @author      alvin guogaobo
139
+     * @version     1.0 版本号
140
+     * @since       2021/5/26 0026 11:48
141
+     */
142
+    public function checkReceivables($param){
143
+        $type = $param['type'] ? : 1;
144
+        $isSub = 1;
145
+        unset($param['type']);
146
+        $receivablesModel = model('Receivables');
147
+        $request = $this->whereCheck($param, $type,$isSub);
148
+        $request['isMessage'] = true;
149
+        $data = $receivablesModel->getDataList($request);
150
+        return $data;
151
+    }
152
+    
153
+    /**
154
+     *待审核发票
155
+     *
156
+     * @author      alvin guogaobo
157
+     * @version     1.0 版本号
158
+     * @since       2021/5/26 0026 13:35
159
+     */
160
+    public function checkInvoice($param){
161
+        $type   = !empty($param['type'])  ? $param['type']  : 1;
162
+        $isSub  = 2;
163
+        # 清除与模型无关的数据
164
+        unset($param['type']);
165
+        $request = $this->whereCheck($param, $type,$isSub);
166
+        $request['isMessage'] = true;
167
+        $data = (new InvoiceLogic())->index($request);
168
+        return $data;
169
+    }
170
+    /**
171
+     * 审批查询条件
172
+     * @param $param
173
+     * @param $type
174
+     *
175
+     * @author      alvin guogaobo
176
+     * @version     1.0 版本号
177
+     * @since       2021/5/26 0026 11:43
178
+     */
179
+    public function whereCheck($param, $type,$isSub='')
180
+    {
181
+        if(empty($isSub)){
182
+            switch ($type) {
183
+                case '1' :
184
+                    $param['check_status'] = ['lt', '2'];
185
+                    $param['check_user_id'] = ['like', '%,' . $param['user_id'] . ',%'];
186
+                    # 要提醒的合同ID
187
+                    $contractIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_contract'], 'user_id' => ['eq', $param['user_id']]])->column('types_id');
188
+                    $param['contractIdArray'] = !empty($contractIdArray) ? $contractIdArray : -1;
189
+                    break;
190
+                case '2' :
191
+                    $param['flow_user_id'] = ['like', '%,' . $param['user_id'] . ',%'];
192
+                    break;
193
+            }
194
+        }else if($isSub==1){
195
+            switch ($type) {
196
+                case '1' :
197
+                    # 待审核、审核中
198
+                    $param['check_status'] = ['lt','2'];
199
+                    $param['check_user_id'] = ['like','%,'.$param['user_id'].',%'];
200
+                    # 要提醒的回款ID
201
+                    $receivablesIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_receivables'], 'user_id' => ['eq', $param['user_id']]])->column('types_id');
202
+                    $param['receivablesIdArray'] = !empty($receivablesIdArray) ? $receivablesIdArray : -1;
203
+                    break;
204
+                case '2' :
205
+                    # 全部
206
+                    $param['flow_user_id'] = ['like','%,'.$param['user_id'].',%'];
207
+                    break;
208
+            }
209
+        }elseif($isSub==2){
210
+            switch ($type) {
211
+                case '1' :
212
+                    # 待审核、审核中
213
+                    $param['check_status']  = ['lt', 2];
214
+                    $param['check_user_id'] = ['like', '%,'. $param['user_id'] .',%'];
215
+                    # 要提醒的发票ID
216
+                    $invoiceIdArray = db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'user_id' => ['eq', $param['user_id']]])->column('types_id');
217
+                    $param['invoiceIdArray'] = !empty($invoiceIdArray) ? $invoiceIdArray : -1;
218
+                    $param['dealt'] = 1;
219
+                    break;
220
+                case '2' :
221
+                    # 全部
222
+                    $param['flow_user_id'] = ['like', '%,'. $param['user_id'] .',%'];
223
+                    $param['dealt'] = 1;
224
+                    break;
225
+            }
226
+        }
227
+        return $param;
228
+    }
229
+    
230
+    /**
231
+     * 负责人查询条件
232
+     * @param $param
233
+     *
234
+     * @author      alvin guogaobo
235
+     * @version     1.0 版本号
236
+     * @since       2021/5/24 0024 09:46
237
+     */
238
+    public function where($param, $type, $isSub, $todayTime)
239
+    {
240
+        # 负责人
241
+        $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $param['user_id'])] : ['eq', $param['user_id']];
242
+        # 类型:1今日需联系;2已逾期;3已联系
243
+        if (empty($isSub) && empty($todayTime)) {
244
+            switch ($type) {
245
+                case '1' :
246
+                    $param['follow'] = [['neq', '已跟进'], null, 'or'];
247
+                    $param['is_allocation'] = 1;
248
+                    break;
249
+                case '2' :
250
+                    $param['follow'] = ['eq', '已跟进'];
251
+                    $param['is_allocation'] = 1;
252
+                    break;
253
+            }
254
+        } else {
255
+            switch ($type) {
256
+                case '1' :
257
+                    $param['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
258
+                    $param['is_dealt'] = ['neq', 1];
259
+                    break;
260
+                case '2' :
261
+                    $param['next_time'] = ['between', [1, time()]];
262
+                    $param['overdue'] = true;
263
+                    $param['is_dealt'] = ['neq', 1];
264
+                    break;
265
+                case '3' :
266
+                    $param['last_time'] = ['between', [$todayTime[0], $todayTime[1]]];
267
+                    break;
268
+            }
269
+        }
270
+        return $param;
271
+    }
272
+}

+ 5
- 2
application/crm/logic/PrintingLogic.php Bestand weergeven

328
         $contactsData = Db::name('crm_contacts')->where('contacts_id', $contractData['contacts_id'])->find();
328
         $contactsData = Db::name('crm_contacts')->where('contacts_id', $contractData['contacts_id'])->find();
329
         # 查询产品数据
329
         # 查询产品数据
330
         $businessProduct = Db::name('crm_business_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal', 'unit'])->where('business_id', $contractData['business_id'])->select();
330
         $businessProduct = Db::name('crm_business_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal', 'unit'])->where('business_id', $contractData['business_id'])->select();
331
+        if (empty($businessProduct)) {
332
+            $businessProduct = Db::name('crm_contract_product')->field(['product_id', 'price', 'sales_price', 'num', 'discount', 'subtotal', 'unit'])->where('contract_id', $id)->select();
333
+        }
331
         $productIdArray = [];
334
         $productIdArray = [];
332
         foreach ($businessProduct AS $key => $value) {
335
         foreach ($businessProduct AS $key => $value) {
333
             $productIdArray[] = $value['product_id'];
336
             $productIdArray[] = $value['product_id'];
525
         }
528
         }
526
 
529
 
527
         # 替换整单折扣
530
         # 替换整单折扣
528
-        $content = str_replace('{整单折扣}', $businessData['discount_rate'], $content);
529
-        $content = str_replace('{产品总金额}', $businessData['money'], $content);
531
+        $content = str_replace('{整单折扣}', !empty($businessData['discount_rate']) ? $businessData['discount_rate'] : $contractData['discount_rate'], $content);
532
+        $content = str_replace('{产品总金额}', !empty($businessData['money']) ? $businessData['money'] : $contractData['money'], $content);
530
 
533
 
531
         return $content;
534
         return $content;
532
     }
535
     }

+ 208
- 20
application/crm/logic/VisitLogic.php Bestand weergeven

4
 
4
 
5
 use app\admin\controller\ApiCommon;
5
 use app\admin\controller\ApiCommon;
6
 use app\admin\model\Common;
6
 use app\admin\model\Common;
7
+use app\admin\traits\FieldVerificationTrait;
7
 use app\crm\model\Visit;
8
 use app\crm\model\Visit;
8
 use think\Db;
9
 use think\Db;
9
-use think\Validate;
10
 
10
 
11
 class VisitLogic extends Common
11
 class VisitLogic extends Common
12
 {
12
 {
13
+    use FieldVerificationTrait;
14
+
13
     /**
15
     /**
14
      * 获取回访列表
16
      * 获取回访列表
15
      * @param $param
17
      * @param $param
54
         }
56
         }
55
 
57
 
56
         //高级筛选
58
         //高级筛选
57
-        $map = where_arr($map, 'crm', 'visit', 'index');
59
+        $map = advancedQuery($map, 'crm', 'visit', 'index');
58
 
60
 
59
         $authMap = [];
61
         $authMap = [];
60
         if (!$partMap) {
62
         if (!$partMap) {
93
         $userField = $fieldModel->getFieldByFormType('crm_visit', 'user'); //人员类型
95
         $userField = $fieldModel->getFieldByFormType('crm_visit', 'user'); //人员类型
94
         $structureField = $fieldModel->getFieldByFormType('crm_visit', 'structure');  //部门类型
96
         $structureField = $fieldModel->getFieldByFormType('crm_visit', 'structure');  //部门类型
95
         $datetimeField = $fieldModel->getFieldByFormType('crm_visit', 'datetime'); //日期时间类型
97
         $datetimeField = $fieldModel->getFieldByFormType('crm_visit', 'datetime'); //日期时间类型
98
+        $booleanField = $fieldModel->getFieldByFormType('crm_visit', 'boolean_value'); //布尔值
99
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_visit', 'date_interval'); // 日期区间类型字段
100
+        $positionField = $fieldModel->getFieldByFormType('crm_visit', 'position'); // 地址类型字段
101
+        $handwritingField = $fieldModel->getFieldByFormType('crm_visit', 'handwriting_sign'); // 手写签名类型字段
102
+        $locationField = $fieldModel->getFieldByFormType('crm_visit', 'location'); // 定位类型字段
96
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
103
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
97
         $temporaryField = str_replace('_name', '', $order_field);
104
         $temporaryField = str_replace('_name', '', $order_field);
98
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
105
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
133
             ->join('__CRM_CONTRACT__ contract', 'visit.contract_id=contract.contract_id', 'LEFT')
140
             ->join('__CRM_CONTRACT__ contract', 'visit.contract_id=contract.contract_id', 'LEFT')
134
             ->join('__CRM_CONTACTS__ contacts', 'visit.contacts_id=contacts.contacts_id', 'LEFT')
141
             ->join('__CRM_CONTACTS__ contacts', 'visit.contacts_id=contacts.contacts_id', 'LEFT')
135
             ->where($map)->where($partMap)->where($authMap)->group('visit.visit_id')->count('visit.visit_id');
142
             ->where($map)->where($partMap)->where($authMap)->group('visit.visit_id')->count('visit.visit_id');
136
-
143
+        # 扩展数据
144
+        $extraData = [];
145
+        $visit_id_list = !empty($list) ? array_column($list, 'visit_id') : [];
146
+        $extraList = db('crm_visit_data')->whereIn('visit_id', $visit_id_list)->select();
147
+        foreach ($extraList AS $key => $value) {
148
+            $extraData[$value['visit_id']][$value['field']] = $value['content'];
149
+        }
137
         foreach ($list as $k => $v) {
150
         foreach ($list as $k => $v) {
138
             $list[$k]['contract_num'] = $v['contract_number'];
151
             $list[$k]['contract_num'] = $v['contract_number'];
139
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
152
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
151
             foreach ($datetimeField as $key => $val) {
164
             foreach ($datetimeField as $key => $val) {
152
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
165
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
153
             }
166
             }
167
+            foreach ($booleanField as $key => $val) {
168
+                $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
169
+            }
170
+            // 处理日期区间类型字段的格式
171
+            foreach ($dateIntervalField AS $key => $val) {
172
+                $list[$k][$val] = !empty($extraData[$v['visit_id']][$val]) ? json_decode($extraData[$v['visit_id']][$val], true) : null;
173
+            }
174
+            // 处理地址类型字段的格式
175
+            foreach ($positionField AS $key => $val) {
176
+                $list[$k][$val] = !empty($extraData[$v['visit_id']][$val]) ? json_decode($extraData[$v['visit_id']][$val], true) : null;
177
+            }
178
+            // 手写签名类型字段
179
+            foreach ($handwritingField AS $key => $val) {
180
+                $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
181
+                $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
182
+            }
183
+            // 定位类型字段
184
+            foreach ($locationField AS $key => $val) {
185
+                $list[$k][$val] = !empty($extraData[$v['visit_id']][$val]) ? json_decode($extraData[$v['visit_id']][$val], true) : null;
186
+            }
154
             $list[$k]['contract_id_info']['contract_id'] = $v['contract_id'];
187
             $list[$k]['contract_id_info']['contract_id'] = $v['contract_id'];
155
             $list[$k]['contract_id_info']['name'] = $v['contract_name'];
188
             $list[$k]['contract_id_info']['name'] = $v['contract_name'];
156
             $list[$k]['customer_id_info']['customer_id'] = $v['create_user_id'];
189
             $list[$k]['customer_id_info']['customer_id'] = $v['create_user_id'];
232
      */
265
      */
233
     public function createData($param)
266
     public function createData($param)
234
     {
267
     {
268
+        // 回访扩展表数据
269
+        $visitData = [];
270
+
235
         $fieldModel = new \app\admin\model\Field();
271
         $fieldModel = new \app\admin\model\Field();
236
 
272
 
237
-        // 自动验证
238
-        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
239
-        $validate = new Validate($validateArr['rule'], $validateArr['message']);
240
-        $result = $validate->check($param);
241
-        if (!$result) {
242
-            $this->error = $validate->getError();
273
+        // 数据验证
274
+        $validateResult = $this->fieldDataValidate($param, 'crm_visit', $param['create_user_id']);
275
+        if (!empty($validateResult)) {
276
+            $this->error = $validateResult;
243
             return false;
277
             return false;
244
         }
278
         }
279
+
245
         if (!$param['customer_id']) {
280
         if (!$param['customer_id']) {
246
             $this->error = '请选择相关客户';
281
             $this->error = '请选择相关客户';
247
             return false;
282
             return false;
263
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
298
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
264
             }
299
             }
265
         }
300
         }
301
+        // 处理手写签名类型
302
+        $handwritingField = $fieldModel->getFieldByFormType('crm_visit', 'handwriting_sign');
303
+        if (!empty($handwritingField)) {
304
+            foreach ($param AS $key => $value) {
305
+                if (in_array($key, $handwritingField)) {
306
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
307
+                }
308
+            }
309
+        }
310
+        // 处理地址、定位、日期区间、明细表格类型字段
311
+        $positionField     = $fieldModel->getFieldByFormType('crm_visit', 'position');
312
+        $locationField     = $fieldModel->getFieldByFormType('crm_visit', 'location');
313
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_visit', 'date_interval');
314
+        $detailTableField  = $fieldModel->getFieldByFormType('crm_visit', 'detail_table');
315
+        foreach ($param AS $key => $value) {
316
+            // 处理地址类型字段数据
317
+            if (in_array($key, $positionField)) {
318
+                if (!empty($value)) {
319
+                    $visitData[] = [
320
+                        'field'       => $key,
321
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
322
+                        'create_time' => time()
323
+                    ];
324
+                    $positionNames = array_column($value, 'name');
325
+                    $param[$key] = implode(',', $positionNames);
326
+                } else {
327
+                    $param[$key] = '';
328
+                }
329
+            }
330
+            // 处理定位类型字段数据
331
+            if (in_array($key, $locationField)) {
332
+                if (!empty($value)) {
333
+                    $visitData[] = [
334
+                        'field'       => $key,
335
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
336
+                        'create_time' => time()
337
+                    ];
338
+                    $param[$key] = $value['address'];
339
+                } else {
340
+                    $param[$key] = '';
341
+                }
342
+            }
343
+            // 处理日期区间类型字段数据
344
+            if (in_array($key, $dateIntervalField)) {
345
+                if (!empty($value)) {
346
+                    $visitData[] = [
347
+                        'field'       => $key,
348
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
349
+                        'create_time' => time()
350
+                    ];
351
+                    $param[$key] = implode('_', $value);
352
+                } else {
353
+                    $param[$key] = '';
354
+                }
355
+            }
356
+            // 处理明细表格类型字段数据
357
+            if (in_array($key, $detailTableField)) {
358
+                if (!empty($value)) {
359
+                    $visitData[] = [
360
+                        'field'       => $key,
361
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
362
+                        'create_time' => time()
363
+                    ];
364
+                    $param[$key] = $key;
365
+                } else {
366
+                    $param[$key] = '';
367
+                }
368
+            }
369
+        }
266
 
370
 
267
         $visitModel = new Visit();
371
         $visitModel = new Visit();
268
         if ($visitModel->data($param)->allowField(true)->save()) {
372
         if ($visitModel->data($param)->allowField(true)->save()) {
269
             $visit_id = $visitModel->visit_id;
373
             $visit_id = $visitModel->visit_id;
374
+            $data['visit_id'] = $visit_id;
270
             updateActionLog($param['create_user_id'], 'crm_visit', $visitModel->visit_id, '', '', '创建了客户回访');
375
             updateActionLog($param['create_user_id'], 'crm_visit', $visitModel->visit_id, '', '', '创建了客户回访');
271
             RecordActionLog($param['create_user_id'],'crm_visit','save',$param['number'],'','','新增了客户回访'.$param['number']);
376
             RecordActionLog($param['create_user_id'],'crm_visit','save',$param['number'],'','','新增了客户回访'.$param['number']);
272
-            $data = [];
273
-            $data['visit_id'] = $visit_id;
377
+            // 添加回访扩展数据
378
+            array_walk($visitData, function (&$val) use ($data) {
379
+                $val['visit_id'] = $data['visit_id'];
380
+            });
381
+            db('crm_visit_data')->insertAll($visitData);
382
+
274
             return $data;
383
             return $data;
275
         } else {
384
         } else {
276
             $this->error = '添加失败';
385
             $this->error = '添加失败';
283
      */
392
      */
284
     public function updateDataById($param, $visit_id = '')
393
     public function updateDataById($param, $visit_id = '')
285
     {
394
     {
395
+        // 回访扩展表数据
396
+        $visitData = [];
397
+
286
         $Visit = model('Visit');
398
         $Visit = model('Visit');
287
         $productModel = new \app\crm\model\Product();
399
         $productModel = new \app\crm\model\Product();
288
         $dataInfo = $this->getDataById($visit_id);
400
         $dataInfo = $this->getDataById($visit_id);
298
         }
410
         }
299
 
411
 
300
         $fieldModel = new \app\admin\model\Field();
412
         $fieldModel = new \app\admin\model\Field();
301
-        // 自动验证
302
-//        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
303
-        $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
304
-        $validate = new Validate($validateArr['rule'], $validateArr['message']);
305
-        $result = $validate->check($param);
306
-        if (!$result) {
307
-            $this->error = $validate->getError();
413
+
414
+        // 数据验证
415
+        $validateResult = $this->fieldDataValidate($param, 'crm_visit', $param['user_id'], $param['visit_id']);
416
+        if (!empty($validateResult)) {
417
+            $this->error = $validateResult;
308
             return false;
418
             return false;
309
         }
419
         }
420
+
310
         // 处理部门、员工、附件、多选类型字段
421
         // 处理部门、员工、附件、多选类型字段
311
         $arrFieldAtt = $fieldModel->getArrayField('crm_visit');
422
         $arrFieldAtt = $fieldModel->getArrayField('crm_visit');
312
         foreach ($arrFieldAtt as $k => $v) {
423
         foreach ($arrFieldAtt as $k => $v) {
320
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
431
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
321
             }
432
             }
322
         }
433
         }
434
+        // 处理手写签名类型
435
+        $handwritingField = $fieldModel->getFieldByFormType('crm_visit', 'handwriting_sign');
436
+        if (!empty($handwritingField)) {
437
+            foreach ($param AS $key => $value) {
438
+                if (in_array($key, $handwritingField)) {
439
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
440
+                }
441
+            }
442
+        }
443
+        // 处理地址、定位、日期区间、明细表格类型字段
444
+        $positionField     = $fieldModel->getFieldByFormType('crm_visit', 'position');
445
+        $locationField     = $fieldModel->getFieldByFormType('crm_visit', 'location');
446
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_visit', 'date_interval');
447
+        $detailTableField  = $fieldModel->getFieldByFormType('crm_visit', 'detail_table');
448
+        foreach ($param AS $key => $value) {
449
+            // 处理地址类型字段数据
450
+            if (in_array($key, $positionField)) {
451
+                if (!empty($value)) {
452
+                    $visitData[] = [
453
+                        'field'       => $key,
454
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
455
+                        'create_time' => time()
456
+                    ];
457
+                    $positionNames = array_column($value, 'name');
458
+                    $param[$key] = implode(',', $positionNames);
459
+                } else {
460
+                    $param[$key] = '';
461
+                }
462
+            }
463
+            // 处理定位类型字段数据
464
+            if (in_array($key, $locationField)) {
465
+                if (!empty($value)) {
466
+                    $visitData[] = [
467
+                        'field'       => $key,
468
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
469
+                        'create_time' => time()
470
+                    ];
471
+                    $param[$key] = $value['address'];
472
+                } else {
473
+                    $param[$key] = '';
474
+                }
475
+            }
476
+            // 处理日期区间类型字段数据
477
+            if (in_array($key, $dateIntervalField)) {
478
+                if (!empty($value)) {
479
+                    $visitData[] = [
480
+                        'field'       => $key,
481
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
482
+                        'create_time' => time()
483
+                    ];
484
+                    $param[$key] = implode('_', $value);
485
+                } else {
486
+                    $param[$key] = '';
487
+                }
488
+            }
489
+            // 处理明细表格类型字段数据
490
+            if (in_array($key, $detailTableField)) {
491
+                if (!empty($value)) {
492
+                    $visitData[] = [
493
+                        'field'       => $key,
494
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
495
+                        'create_time' => time()
496
+                    ];
497
+                    $param[$key] = $key;
498
+                } else {
499
+                    $param[$key] = '';
500
+                }
501
+            }
502
+        }
323
 
503
 
324
         if ($Visit->update($param, ['visit_id' => $visit_id], true)) {
504
         if ($Visit->update($param, ['visit_id' => $visit_id], true)) {
505
+            $data['visit_id'] = $visit_id;
325
             //修改记录           
506
             //修改记录           
326
             updateActionLog($param['user_id'], 'crm_visit', $visit_id, $dataInfo, $param);
507
             updateActionLog($param['user_id'], 'crm_visit', $visit_id, $dataInfo, $param);
327
             RecordActionLog($param['user_id'], 'crm_visit', 'update',$dataInfo['number'], $dataInfo, $param);
508
             RecordActionLog($param['user_id'], 'crm_visit', 'update',$dataInfo['number'], $dataInfo, $param);
328
-            $data = [];
329
-            $data['visit_id'] = $visit_id;
509
+            // 添加回访扩展数据
510
+            db('crm_visit_data')->where('visit_id', $visit_id)->delete();
511
+            array_walk($visitData, function (&$val) use ($visit_id) {
512
+                $val['visit_id'] = $visit_id;
513
+            });
514
+            db('crm_visit_data')->insertAll($visitData);
515
+
330
             return $data;
516
             return $data;
331
         } else {
517
         } else {
332
             $this->rollback();
518
             $this->rollback();
371
             if (!$data) {
557
             if (!$data) {
372
                 return resultArray(['error' => $this->getError()]);
558
                 return resultArray(['error' => $this->getError()]);
373
             }
559
             }
560
+            // 删除回访扩展数据
561
+            db('crm_visit_data')->whereIn('visit_id', $delIds)->delete();
374
             //删除关联附件
562
             //删除关联附件
375
             $fileModel->delRFileByModule('crm_visit', $delIds);
563
             $fileModel->delRFileByModule('crm_visit', $delIds);
376
             //删除关联操作记录
564
             //删除关联操作记录

+ 219
- 33
application/crm/model/Business.php Bestand weergeven

6
 // +----------------------------------------------------------------------
6
 // +----------------------------------------------------------------------
7
 namespace app\crm\model;
7
 namespace app\crm\model;
8
 
8
 
9
+use app\admin\traits\FieldVerificationTrait;
9
 use think\Db;
10
 use think\Db;
10
 use app\admin\model\Common;
11
 use app\admin\model\Common;
11
-use think\Request;
12
-use think\Validate;
13
 use app\crm\model\Business as CrmBusinessModel;
12
 use app\crm\model\Business as CrmBusinessModel;
14
 
13
 
15
 class Business extends Common
14
 class Business extends Common
16
 {
15
 {
16
+    use FieldVerificationTrait;
17
+
17
     /**
18
     /**
18
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
20
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
47
         $getCount = $request['getCount'];
48
         $getCount = $request['getCount'];
48
         $businessTypeId = $request['typesId']; // 针对mobile
49
         $businessTypeId = $request['typesId']; // 针对mobile
49
         $businessStatusId = $request['statusId']; // 针对mobile
50
         $businessStatusId = $request['statusId']; // 针对mobile
51
+        $overdue = $request['overdue']; // 待办事项下需联系商机(逾期)
50
         unset($request['scene_id']);
52
         unset($request['scene_id']);
51
         unset($request['search']);
53
         unset($request['search']);
52
         unset($request['user_id']);
54
         unset($request['user_id']);
57
         unset($request['getCount']);
59
         unset($request['getCount']);
58
         unset($request['typesId']);
60
         unset($request['typesId']);
59
         unset($request['statusId']);
61
         unset($request['statusId']);
60
-
62
+        unset($request['overdue']);
61
         $request = $this->fmtRequest($request);
63
         $request = $this->fmtRequest($request);
62
         $requestMap = $request['map'] ?: [];
64
         $requestMap = $request['map'] ?: [];
63
         $sceneModel = new \app\admin\model\Scene();
65
         $sceneModel = new \app\admin\model\Scene();
97
         }
99
         }
98
         $partMap = [];
100
         $partMap = [];
99
         //优先级:普通筛选>高级筛选>场景
101
         //优先级:普通筛选>高级筛选>场景
100
-        if ($sceneMap['ro_user_id'] && $sceneMap['rw_user_id']) {
102
+        if ($requestMap['team_id']) {
101
             //相关团队查询
103
             //相关团队查询
102
             $map = $requestMap;
104
             $map = $requestMap;
103
-            $partMap = function ($query) use ($sceneMap) {
104
-                $query->where('business.ro_user_id', array('like', '%,' . $sceneMap['ro_user_id'] . ',%'))
105
-                    ->whereOr('business.rw_user_id', array('like', '%,' . $sceneMap['rw_user_id'] . ',%'));
106
-            };
105
+            $partMap= advancedQueryFormatForTeam($requestMap,'crm_business','business_id');
106
+            unset($map['team_id']);
107
         } else {
107
         } else {
108
             $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
108
             $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
109
         }
109
         }
110
         //高级筛选
110
         //高级筛选
111
-        $map = where_arr($map, 'crm', 'business', 'index');
111
+        $map = advancedQuery($map, 'crm', 'business', 'index');
112
         $authMap = [];
112
         $authMap = [];
113
         if (!$partMap) {
113
         if (!$partMap) {
114
             $a = 'index';
114
             $a = 'index';
156
         $userField = $fieldModel->getFieldByFormType('crm_business', 'user'); //人员类型
156
         $userField = $fieldModel->getFieldByFormType('crm_business', 'user'); //人员类型
157
         $structureField = $fieldModel->getFieldByFormType('crm_business', 'structure');  //部门类型
157
         $structureField = $fieldModel->getFieldByFormType('crm_business', 'structure');  //部门类型
158
         $datetimeField = $fieldModel->getFieldByFormType('crm_business', 'datetime'); //日期时间类型
158
         $datetimeField = $fieldModel->getFieldByFormType('crm_business', 'datetime'); //日期时间类型
159
+        $booleanField = $fieldModel->getFieldByFormType('crm_business', 'boolean_value'); //布尔值
160
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_business', 'date_interval'); // 日期区间类型字段
161
+        $positionField = $fieldModel->getFieldByFormType('crm_business', 'position'); // 地址类型字段
162
+        $handwritingField = $fieldModel->getFieldByFormType('crm_business', 'handwriting_sign'); // 手写签名类型字段
163
+        $locationField = $fieldModel->getFieldByFormType('crm_business', 'location'); // 定位类型字段
159
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
164
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
160
         $temporaryField = str_replace('_name', '', $order_field);
165
         $temporaryField = str_replace('_name', '', $order_field);
161
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
166
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
178
                 $map['is_end']=abs($businessStatusId);
183
                 $map['is_end']=abs($businessStatusId);
179
             }
184
             }
180
         }
185
         }
186
+
187
+        // 待办事项下需联系商机(逾期)
188
+        $overdueWhere = '';
189
+        if (!empty($overdue)) {
190
+            $overdueWhere = "(FROM_UNIXTIME(`business`.`last_time`,'%Y-%m-%d') < FROM_UNIXTIME(`business`.`next_time`,'%Y-%m-%d') OR (ISNULL(`business`.`last_time`) AND `business`.`next_time` < ".time()."))";
191
+        }
192
+
181
         $readAuthIds = $userModel->getUserByPer('crm', 'business', 'read');
193
         $readAuthIds = $userModel->getUserByPer('crm', 'business', 'read');
182
         $updateAuthIds = $userModel->getUserByPer('crm', 'business', 'update');
194
         $updateAuthIds = $userModel->getUserByPer('crm', 'business', 'update');
183
         $deleteAuthIds = $userModel->getUserByPer('crm', 'business', 'delete');
195
         $deleteAuthIds = $userModel->getUserByPer('crm', 'business', 'delete');
184
         $dataCount = db('crm_business')
196
         $dataCount = db('crm_business')
185
             ->alias('business')
197
             ->alias('business')
186
             ->join('__CRM_CUSTOMER__ customer', 'business.customer_id = customer.customer_id', 'LEFT')
198
             ->join('__CRM_CUSTOMER__ customer', 'business.customer_id = customer.customer_id', 'LEFT')
187
-            ->where($map)->where($partMap)->where($authMap)->count('business_id');
199
+            ->where($map)->where($partMap)->where($authMap)->where($overdueWhere)->count('business_id');
188
         if (!empty($getCount) && $getCount == 1) {
200
         if (!empty($getCount) && $getCount == 1) {
189
             $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
201
             $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
190
             # 商机总金额
202
             # 商机总金额
199
             ->where($map)
211
             ->where($map)
200
             ->where($partMap)
212
             ->where($partMap)
201
             ->where($authMap)
213
             ->where($authMap)
214
+            ->where($overdueWhere)
202
             ->limit($request['offset'], $request['length'])
215
             ->limit($request['offset'], $request['length'])
203
             ->field('business.*,customer.name as customer_name')
216
             ->field('business.*,customer.name as customer_name')
204
             ->orderRaw($order)
217
             ->orderRaw($order)
205
             ->select();
218
             ->select();
206
         $endStatus = ['1' => '赢单', '2' => '输单', '3' => '无效'];
219
         $endStatus = ['1' => '赢单', '2' => '输单', '3' => '无效'];
220
+        # 扩展数据
221
+        $extraData = [];
222
+        $business_id_list = !empty($list) ? array_column($list, 'business_id') : [];
223
+        $extraList = db('crm_business_data')->whereIn('business_id', $business_id_list)->select();
224
+        foreach ($extraList AS $key => $value) {
225
+            $extraData[$value['business_id']][$value['field']] = $value['content'];
226
+        }
207
         foreach ($list as $k => $v) {
227
         foreach ($list as $k => $v) {
208
             $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
228
             $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
209
             $list[$k]['customer_id_info']['name'] = $v['customer_name'];
229
             $list[$k]['customer_id_info']['name'] = $v['customer_name'];
213
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
233
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
214
             foreach ($userField as $key => $val) {
234
             foreach ($userField as $key => $val) {
215
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
235
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
216
-                $list[$k][$val.'_name'] = implode($usernameField, ',');
236
+                $list[$k][$val] = implode($usernameField, ',');
217
             }
237
             }
218
             foreach ($structureField as $key => $val) {
238
             foreach ($structureField as $key => $val) {
219
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
239
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
220
-                $list[$k][$val.'_name'] = implode($structureNameField, ',');
240
+                $list[$k][$val] = implode($structureNameField, ',');
221
             }
241
             }
222
             foreach ($datetimeField as $key => $val) {
242
             foreach ($datetimeField as $key => $val) {
223
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
243
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
224
             }
244
             }
245
+            foreach ($booleanField as $key => $val) {
246
+                $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
247
+            }
248
+            // 处理日期区间类型字段的格式
249
+            foreach ($dateIntervalField AS $key => $val) {
250
+                $list[$k][$val] = !empty($extraData[$v['business_id']][$val]) ? json_decode($extraData[$v['business_id']][$val], true) : null;
251
+            }
252
+            // 处理地址类型字段的格式
253
+            foreach ($positionField AS $key => $val) {
254
+                $list[$k][$val] = !empty($extraData[$v['business_id']][$val]) ? json_decode($extraData[$v['business_id']][$val], true) : null;
255
+            }
256
+            // 手写签名类型字段
257
+            foreach ($handwritingField AS $key => $val) {
258
+                $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
259
+                $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
260
+            }
261
+            // 定位类型字段
262
+            foreach ($locationField AS $key => $val) {
263
+                $list[$k][$val] = !empty($extraData[$v['business_id']][$val]) ? json_decode($extraData[$v['business_id']][$val], true) : null;
264
+            }
225
             $statusInfo = [];
265
             $statusInfo = [];
226
             $status_count = 0;
266
             $status_count = 0;
227
             if (!$v['is_end']) {
267
             if (!$v['is_end']) {
281
      */
321
      */
282
     public function createData($param)
322
     public function createData($param)
283
     {
323
     {
324
+        // 商机扩展表数据
325
+        $businessData = [];
326
+
284
         $fieldModel = new \app\admin\model\Field();
327
         $fieldModel = new \app\admin\model\Field();
285
         $productModel = new \app\crm\model\Product();
328
         $productModel = new \app\crm\model\Product();
286
-        // 自动验证
287
-        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
288
-        $validate = new Validate($validateArr['rule'], $validateArr['message']);
289
-        $result = $validate->check($param);
290
-        if (!$result) {
291
-            $this->error = $validate->getError();
329
+        // 数据验证
330
+        $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
331
+        if (!empty($validateResult)) {
332
+            $this->error = $validateResult;
292
             return false;
333
             return false;
293
         }
334
         }
294
         if (!$param['customer_id']) {
335
         if (!$param['customer_id']) {
308
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
349
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
309
             }
350
             }
310
         }
351
         }
352
+        // 处理手写签名类型
353
+        $handwritingField = $fieldModel->getFieldByFormType('crm_business', 'handwriting_sign');
354
+        if (!empty($handwritingField)) {
355
+            foreach ($param AS $key => $value) {
356
+                if (in_array($key, $handwritingField)) {
357
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
358
+                }
359
+            }
360
+        }
361
+        // 处理地址、定位、日期区间、明细表格类型字段
362
+        $positionField     = $fieldModel->getFieldByFormType($this->name, 'position');
363
+        $locationField     = $fieldModel->getFieldByFormType($this->name, 'location');
364
+        $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
365
+        $detailTableField  = $fieldModel->getFieldByFormType($this->name, 'detail_table');
366
+        foreach ($param AS $key => $value) {
367
+            // 处理地址类型字段数据
368
+            if (in_array($key, $positionField)) {
369
+                if (!empty($value)) {
370
+                    $businessData[] = [
371
+                        'field'       => $key,
372
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
373
+                        'create_time' => time()
374
+                    ];
375
+                    $positionNames = array_column($value, 'name');
376
+                    $param[$key] = implode(',', $positionNames);
377
+                } else {
378
+                    $param[$key] = '';
379
+                }
380
+            }
381
+            // 处理定位类型字段数据
382
+            if (in_array($key, $locationField)) {
383
+                if (!empty($value)) {
384
+                    $businessData[] = [
385
+                        'field'       => $key,
386
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
387
+                        'create_time' => time()
388
+                    ];
389
+                    $param[$key] = $value['address'];
390
+                } else {
391
+                    $param[$key] = '';
392
+                }
393
+            }
394
+            // 处理日期区间类型字段数据
395
+            if (in_array($key, $dateIntervalField)) {
396
+                if (!empty($value)) {
397
+                    $businessData[] = [
398
+                        'field'       => $key,
399
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
400
+                        'create_time' => time()
401
+                    ];
402
+                    $param[$key] = implode('_', $value);
403
+                } else {
404
+                    $param[$key] = '';
405
+                }
406
+            }
407
+            // 处理明细表格类型字段数据
408
+            if (in_array($key, $detailTableField)) {
409
+                if (!empty($value)) {
410
+                    $businessData[] = [
411
+                        'field'       => $key,
412
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
413
+                        'create_time' => time()
414
+                    ];
415
+                    $param[$key] = $key;
416
+                } else {
417
+                    $param[$key] = '';
418
+                }
419
+            }
420
+        }
311
 
421
 
312
         # 设置今日需联系商机
422
         # 设置今日需联系商机
313
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
423
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
318
             updateActionLog($param['create_user_id'], 'crm_business', $this->business_id, '', '', '创建了商机');
428
             updateActionLog($param['create_user_id'], 'crm_business', $this->business_id, '', '', '创建了商机');
319
             RecordActionLog($param['create_user_id'],'crm_business','save',$param['name'],'','','新增了商机'.$param['name']);
429
             RecordActionLog($param['create_user_id'],'crm_business','save',$param['name'],'','','新增了商机'.$param['name']);
320
             $business_id = $this->business_id;
430
             $business_id = $this->business_id;
431
+            $data['business_id'] = $business_id;
321
             if ($param['product']) {
432
             if ($param['product']) {
322
                 //产品数据处理
433
                 //产品数据处理
323
                 $resProduct = $productModel->createObject('crm_business', $param, $business_id);
434
                 $resProduct = $productModel->createObject('crm_business', $param, $business_id);
334
             $data_log['owner_user_id'] = $param['owner_user_id'];
445
             $data_log['owner_user_id'] = $param['owner_user_id'];
335
             $data_log['remark'] = '新建商机';
446
             $data_log['remark'] = '新建商机';
336
             Db::name('CrmBusinessLog')->insert($data_log);
447
             Db::name('CrmBusinessLog')->insert($data_log);
337
-
338
-            $data = [];
339
-            $data['business_id'] = $business_id;
340
-
341
-
342
             # 添加活动记录
448
             # 添加活动记录
343
             Db::name('crm_activity')->insert([
449
             Db::name('crm_activity')->insert([
344
                 'type' => 2,
450
                 'type' => 2,
350
                 'create_time' => time(),
456
                 'create_time' => time(),
351
                 'customer_ids' => ',' . $param['customer_id'] . ','
457
                 'customer_ids' => ',' . $param['customer_id'] . ','
352
             ]);
458
             ]);
459
+            // 添加商机扩展数据
460
+            array_walk($businessData, function (&$val) use ($data) {
461
+                $val['business_id'] = $data['business_id'];
462
+            });
463
+            db('crm_business_data')->insertAll($businessData);
353
 
464
 
354
             return $data;
465
             return $data;
355
         } else {
466
         } else {
366
      */
477
      */
367
     public function updateDataById($param, $business_id = '')
478
     public function updateDataById($param, $business_id = '')
368
     {
479
     {
480
+        // 商机扩展表数据
481
+        $businessData = [];
482
+
369
         $productModel = new \app\crm\model\Product();
483
         $productModel = new \app\crm\model\Product();
370
         $dataInfo = $this->getDataById($business_id);
484
         $dataInfo = $this->getDataById($business_id);
371
         if (!$dataInfo) {
485
         if (!$dataInfo) {
380
         }
494
         }
381
 
495
 
382
         $fieldModel = new \app\admin\model\Field();
496
         $fieldModel = new \app\admin\model\Field();
383
-        // 自动验证
384
-//        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
385
-        $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
386
-        $validate = new Validate($validateArr['rule'], $validateArr['message']);
387
-
388
-        $result = $validate->check($param);
389
-        if (!$result) {
390
-            $this->error = $validate->getError();
497
+
498
+        // 数据验证
499
+        $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['business_id']);
500
+        if (!empty($validateResult)) {
501
+            $this->error = $validateResult;
391
             return false;
502
             return false;
392
         }
503
         }
393
 
504
 
408
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
519
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
409
             }
520
             }
410
         }
521
         }
522
+        // 处理手写签名类型
523
+        $handwritingField = $fieldModel->getFieldByFormType('crm_business', 'handwriting_sign');
524
+        if (!empty($handwritingField)) {
525
+            foreach ($param AS $key => $value) {
526
+                if (in_array($key, $handwritingField)) {
527
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
528
+                }
529
+            }
530
+        }
531
+        // 处理地址、定位、日期区间、明细表格类型字段
532
+        $positionField     = $fieldModel->getFieldByFormType($this->name, 'position');
533
+        $locationField     = $fieldModel->getFieldByFormType($this->name, 'location');
534
+        $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
535
+        $detailTableField  = $fieldModel->getFieldByFormType($this->name, 'detail_table');
536
+        foreach ($param AS $key => $value) {
537
+            // 处理地址类型字段数据
538
+            if (in_array($key, $positionField)) {
539
+                if (!empty($value)) {
540
+                    $businessData[] = [
541
+                        'field'       => $key,
542
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
543
+                        'create_time' => time()
544
+                    ];
545
+                    $positionNames = array_column($value, 'name');
546
+                    $param[$key] = implode(',', $positionNames);
547
+                } else {
548
+                    $param[$key] = '';
549
+                }
550
+            }
551
+            // 处理定位类型字段数据
552
+            if (in_array($key, $locationField)) {
553
+                if (!empty($value)) {
554
+                    $businessData[] = [
555
+                        'field'       => $key,
556
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
557
+                        'create_time' => time()
558
+                    ];
559
+                    $param[$key] = $value['address'];
560
+                } else {
561
+                    $param[$key] = '';
562
+                }
563
+            }
564
+            // 处理日期区间类型字段数据
565
+            if (in_array($key, $dateIntervalField)) {
566
+                if (!empty($value)) {
567
+                    $businessData[] = [
568
+                        'field'       => $key,
569
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
570
+                        'create_time' => time()
571
+                    ];
572
+                    $param[$key] = implode('_', $value);
573
+                } else {
574
+                    $param[$key] = '';
575
+                }
576
+            }
577
+            // 处理明细表格类型字段数据
578
+            if (in_array($key, $detailTableField)) {
579
+                if (!empty($value)) {
580
+                    $businessData[] = [
581
+                        'field'       => $key,
582
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
583
+                        'create_time' => time()
584
+                    ];
585
+                    $param[$key] = $key;
586
+                } else {
587
+                    $param[$key] = '';
588
+                }
589
+            }
590
+        }
411
 
591
 
412
         # 设置今日需联系商机
592
         # 设置今日需联系商机
413
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
593
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
422
             $param['is_end'] = $param['status_id'];
602
             $param['is_end'] = $param['status_id'];
423
         }
603
         }
424
         if ($this->update($param, ['business_id' => $business_id], true)) {
604
         if ($this->update($param, ['business_id' => $business_id], true)) {
605
+            $data['business_id'] = $business_id;
425
             //产品数据处理
606
             //产品数据处理
426
             $resProduct = $productModel->createObject('crm_business', $param, $business_id);
607
             $resProduct = $productModel->createObject('crm_business', $param, $business_id);
427
             //修改记录
608
             //修改记录
428
             updateActionLog($param['user_id'], 'crm_business', $business_id, $dataInfo, $param);
609
             updateActionLog($param['user_id'], 'crm_business', $business_id, $dataInfo, $param);
429
             RecordActionLog($param['user_id'], 'crm_business', 'update',$dataInfo['name'], $dataInfo, $param);
610
             RecordActionLog($param['user_id'], 'crm_business', 'update',$dataInfo['name'], $dataInfo, $param);
430
-            $data = [];
431
-            $data['business_id'] = $business_id;
611
+            // 添加商机扩展数据
612
+            db('crm_business_data')->where('business_id', $business_id)->delete();
613
+            array_walk($businessData, function (&$val) use ($business_id) {
614
+                $val['business_id'] = $business_id;
615
+            });
616
+            db('crm_business_data')->insertAll($businessData);
617
+
432
             return $data;
618
             return $data;
433
         } else {
619
         } else {
434
             $this->rollback();
620
             $this->rollback();

+ 7
- 13
application/crm/model/BusinessStatus.php Bestand weergeven

199
 			// 提交事务
199
 			// 提交事务
200
     		Db::commit();
200
     		Db::commit();
201
     		# 系统操作日志
201
     		# 系统操作日志
202
-    		$user=new ApiCommon();
203
-    		$userInfo=$user->userInfo;
204
-            SystemActionLog($userInfo['id'], 'crm_business','customer', $type_id, 'update',$dataInfo['name'] , '', '','编辑了商机组:'.$dataInfo['name']);
202
+            SystemActionLog($param['user_id'], 'crm_business','customer', $type_id, 'update',$dataInfo['name'] , '', '','编辑了商机组:'.$dataInfo['name']);
205
             return true;
203
             return true;
206
 		} catch (\Exception $e) {
204
 		} catch (\Exception $e) {
207
 			$this->error = '编辑失败';
205
 			$this->error = '编辑失败';
230
 
228
 
231
 	/**
229
 	/**
232
 	 * [delDataById 根据id删除数据]
230
 	 * [delDataById 根据id删除数据]
233
-	 * @param     string                   $id     [主键]
231
+	 * @param     string                   $param['id']     [主键]
234
 	 * @param     boolean                  $delSon [是否删除子孙数据]
232
 	 * @param     boolean                  $delSon [是否删除子孙数据]
235
 	 * @return    [type]                           [description]
233
 	 * @return    [type]                           [description]
236
 	 */
234
 	 */
237
-	public function delDataById($id = '', $delSon = false)
235
+	public function delDataById($param = '', $delSon = false)
238
 	{
236
 	{
239
-		if (!$id) {
237
+		if (!$param['id']) {
240
 			$this->error = '删除失败';
238
 			$this->error = '删除失败';
241
 			return false;
239
 			return false;
242
 		}
240
 		}
249
 		//启动事务
247
 		//启动事务
250
 		Db::startTrans();
248
 		Db::startTrans();
251
 		try {
249
 		try {
252
-            db('crm_business_type')->where(['type_id' => $id])->update(['is_display' => 0]);
253
-//			db('crm_business_type')->where(['type_id' => $id])->delete();
254
-//			db('crm_business_status')->where(['type_id' => $id])->delete();
250
+            db('crm_business_type')->where(['type_id' => $param['id']])->update(['is_display' => 0]);
255
 			// 提交事务
251
 			// 提交事务
256
     		Db::commit();
252
     		Db::commit();
257
             # 系统操作日志
253
             # 系统操作日志
258
-    		$user=new ApiCommon();
259
-    		$userInfo=$user->userInfo;
260
-            $data=db('crm_business_type')->where(['type_id' => $id])->find();
261
-            SystemActionLog($userInfo['id'], 'crm_business','customer', $id,  'update',$data['name'] , '', '','删除了商机组:'.$data['name']);
254
+            $data=db('crm_business_type')->where(['type_id' => $param['id']])->find();
255
+            SystemActionLog($param['user_id'], 'crm_business','customer', $param['id'],  'update',$data['name'] , '', '','删除了商机组:'.$data['name']);
262
             
256
             
263
             return true;
257
             return true;
264
 		} catch(\Exception $e) {
258
 		} catch(\Exception $e) {

+ 509
- 300
application/crm/model/Contacts.php Bestand weergeven

6
 // +----------------------------------------------------------------------
6
 // +----------------------------------------------------------------------
7
 namespace app\crm\model;
7
 namespace app\crm\model;
8
 
8
 
9
+use app\admin\traits\FieldVerificationTrait;
9
 use think\Db;
10
 use think\Db;
10
 use app\admin\model\Common;
11
 use app\admin\model\Common;
11
-use think\Request;
12
 use think\Validate;
12
 use think\Validate;
13
 
13
 
14
 class Contacts extends Common
14
 class Contacts extends Common
15
 {
15
 {
16
-	/**
16
+    use FieldVerificationTrait;
17
+    
18
+    /**
17
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
18
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
20
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
19
      */
21
      */
20
-	protected $name = 'crm_contacts';
22
+    protected $name = 'crm_contacts';
21
     protected $createTime = 'create_time';
23
     protected $createTime = 'create_time';
22
     protected $updateTime = 'update_time';
24
     protected $updateTime = 'update_time';
23
-	protected $autoWriteTimestamp = true;
24
-
25
-	/**
25
+    protected $autoWriteTimestamp = true;
26
+    
27
+    /**
26
      * [getDataList 联系人list]
28
      * [getDataList 联系人list]
27
-     * @author Michael_xu
28
      * @param     [string]                   $map [查询条件]
29
      * @param     [string]                   $map [查询条件]
29
      * @param     [number]                   $page     [当前页数]
30
      * @param     [number]                   $page     [当前页数]
30
      * @param     [number]                   $limit    [每页数量]
31
      * @param     [number]                   $limit    [每页数量]
31
      * @return    [array]                    [description]
32
      * @return    [array]                    [description]
32
-     */		
33
-	public function getDataList($request)
34
-    {  	
35
-    	$userModel = new \app\admin\model\User();
36
-    	$structureModel = new \app\admin\model\Structure();
37
-    	$fieldModel = new \app\admin\model\Field();
38
-    	$customerModel = new \app\crm\model\Customer();
39
-    	$search = $request['search'];
40
-    	$user_id = $request['user_id'];
41
-    	$scene_id = (int)$request['scene_id'];
42
-    	$is_excel = $request['is_excel']; //导出
43
-    	$business_id = $request['business_id'];
44
-		$order_field = $request['order_field'];
45
-    	$order_type = $request['order_type'];
46
-    	$pageType = $request['pageType']; 
47
-    	$getCount = $request['getCount'];
48
-		//需要过滤的参数
49
-    	$unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap','business_id','check_status'];
50
-    	foreach ($unsetRequest as $v) {
51
-    		unset($request[$v]);
52
-    	}
53
-
54
-        $request = $this->fmtRequest( $request );
55
-        $requestMap = $request['map'] ? : [];
56
-
57
-		$sceneModel = new \app\admin\model\Scene();
58
-		if ($scene_id) {
59
-			//自定义场景
60
-			$sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'contacts') ? : [];
61
-		} else {
62
-			//默认场景
63
-			$sceneMap = $sceneModel->getDefaultData('crm_contacts', $user_id) ? : [];
64
-		}
65
-		$searchMap = [];
66
-		if ($search || $search == '0') {
67
-			//普通筛选
68
-			$searchMap = function($query) use ($search){
69
-			        $query->where('contacts.name',array('like','%'.$search.'%'))
70
-			        	->whereOr('contacts.mobile',array('like','%'.$search.'%'))
71
-			        	->whereOr('contacts.telephone',array('like','%'.$search.'%'));
72
-			};			
73
-			// $sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '联系人姓名'];
74
-		}
75
-		//优先级:普通筛选>高级筛选>场景
76
-		$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
77
-		//高级筛选
78
-		$map = where_arr($map, 'crm', 'contacts', 'index');		
79
-		//权限
80
-		$a = 'index';
81
-		if ($is_excel) $a = 'excelExport';		
82
-		$authMap = [];
83
-		$auth_user_ids = $userModel->getUserByPer('crm', 'contacts', $a);
84
-		if (isset($map['contacts.owner_user_id']) && $map['contacts.owner_user_id'][0] != 'like') {
85
-			if (!is_array($map['contacts.owner_user_id'][1])) {
86
-				$map['contacts.owner_user_id'][1] = [$map['contacts.owner_user_id'][1]];
87
-			}
88
-			if (in_array($map['contacts.owner_user_id'][0], ['neq', 'notin'])) {
89
-				$auth_user_ids = array_diff($auth_user_ids, $map['contacts.owner_user_id'][1]) ? : [];	//取差集	
90
-			} else {
91
-				$auth_user_ids = array_intersect($map['contacts.owner_user_id'][1], $auth_user_ids) ? : [];	//取交集	
92
-			}
93
-	        unset($map['contacts.owner_user_id']);
94
-	    }		    
95
-	    $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
96
-	    //负责人、相关团队
97
-	    $authMap['contacts.owner_user_id'] = ['in',$auth_user_ids];		
98
-		//联系人商机
99
-		if ($business_id) {
100
-			$contacts_id = Db::name('crm_contacts_business')->where(['business_id' => $business_id])->column('contacts_id');
101
-			if ($contacts_id) {
102
-		    	$map['contacts.contacts_id'] = array('in',$contacts_id);
103
-		    }else{
104
-		    	$map['contacts.contacts_id'] = array('eq',-1);
105
-		    }
106
-		}	    
107
-		//列表展示字段
108
-		$indexField = $fieldModel->getIndexField('crm_contacts', $user_id, 1) ? : array('name');
109
-		$userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型
110
-		$structureField = $fieldModel->getFieldByFormType('crm_contacts', 'structure');  //部门类型
33
+     * @author Michael_xu
34
+     */
35
+    public function getDataList($request)
36
+    {
37
+        $userModel = new \app\admin\model\User();
38
+        $structureModel = new \app\admin\model\Structure();
39
+        $fieldModel = new \app\admin\model\Field();
40
+        $customerModel = new \app\crm\model\Customer();
41
+        $search = $request['search'];
42
+        $user_id = $request['user_id'];
43
+        $scene_id = (int)$request['scene_id'];
44
+        $is_excel = $request['is_excel']; //导出
45
+        $business_id = $request['business_id'];
46
+        $order_field = $request['order_field'];
47
+        $order_type = $request['order_type'];
48
+        $pageType = $request['pageType'];
49
+        $getCount = $request['getCount'];
50
+        //需要过滤的参数
51
+        $unsetRequest = ['scene_id', 'search', 'user_id', 'is_excel', 'action', 'order_field', 'order_type', 'is_remind', 'getCount', 'type', 'otherMap', 'business_id', 'check_status'];
52
+        foreach ($unsetRequest as $v) {
53
+            unset($request[$v]);
54
+        }
55
+        
56
+        $request = $this->fmtRequest($request);
57
+        $requestMap = $request['map'] ?: [];
58
+        
59
+        $sceneModel = new \app\admin\model\Scene();
60
+        if ($scene_id) {
61
+            //自定义场景
62
+            $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'contacts') ?: [];
63
+        } else {
64
+            //默认场景
65
+            $sceneMap = $sceneModel->getDefaultData('crm_contacts', $user_id) ?: [];
66
+        }
67
+        $searchMap = [];
68
+        if ($search || $search == '0') {
69
+            //普通筛选
70
+            $searchMap = function ($query) use ($search) {
71
+                $query->where('contacts.name', array('like', '%' . $search . '%'))
72
+                    ->whereOr('contacts.mobile', array('like', '%' . $search . '%'))
73
+                    ->whereOr('contacts.telephone', array('like', '%' . $search . '%'));
74
+            };
75
+        }
76
+        $partMap = [];
77
+        //优先级:普通筛选>高级筛选>场景
78
+        if ($requestMap['team_id']) {
79
+            //相关团队查询
80
+            $map = $requestMap;
81
+            $partMap= advancedQueryFormatForTeam($requestMap,'crm_contacts','contacts_id');
82
+            unset($map['team_id']);
83
+        } else {
84
+            $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
85
+        }
86
+        //高级筛选
87
+        $map = advancedQuery($map, 'crm', 'contacts', 'index');
88
+        //权限
89
+        if (!$partMap) {
90
+            $a = 'index';
91
+            if ($is_excel) $a = 'excelExport';
92
+            $authMap = [];
93
+            $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', $a);
94
+            if (isset($map['contacts.owner_user_id']) && $map['contacts.owner_user_id'][0] != 'like') {
95
+                if (!is_array($map['contacts.owner_user_id'][1])) {
96
+                    $map['contacts.owner_user_id'][1] = [$map['contacts.owner_user_id'][1]];
97
+                }
98
+                if (in_array($map['contacts.owner_user_id'][0], ['neq', 'notin'])) {
99
+                    $auth_user_ids = array_diff($auth_user_ids, $map['contacts.owner_user_id'][1]) ?: [];    //取差集
100
+                } else {
101
+                    $auth_user_ids = array_intersect($map['contacts.owner_user_id'][1], $auth_user_ids) ?: [];    //取交集
102
+                }
103
+                unset($map['contacts.owner_user_id']);
104
+                $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
105
+                //负责人、相关团队
106
+                $authMap['contacts.owner_user_id'] = ['in', $auth_user_ids];
107
+            } else {
108
+                $authMapData = [];
109
+                $authMapData['auth_user_ids'] = $auth_user_ids;
110
+                $authMapData['user_id'] = $user_id;
111
+                $authMap = function ($query) use ($authMapData) {
112
+                    $query->where('contacts.owner_user_id', array('in', $authMapData['auth_user_ids']))
113
+                        ->whereOr('contacts.ro_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'))
114
+                        ->whereOr('contacts.rw_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'));
115
+                };
116
+            }
117
+        }
118
+        
119
+        
120
+        //联系人商机
121
+        if ($business_id) {
122
+            $contacts_id = Db::name('crm_contacts_business')->where(['business_id' => $business_id])->column('contacts_id');
123
+            if ($contacts_id) {
124
+                $map['contacts.contacts_id'] = array('in', $contacts_id);
125
+            } else {
126
+                $map['contacts.contacts_id'] = array('eq', -1);
127
+            }
128
+        }
129
+        //列表展示字段
130
+        $indexField = $fieldModel->getIndexField('crm_contacts', $user_id, 1) ?: array('name');
131
+        $userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型
132
+        $structureField = $fieldModel->getFieldByFormType('crm_contacts', 'structure');  //部门类型
111
         $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
133
         $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
134
+        $booleanField = $fieldModel->getFieldByFormType('crm_contacts', 'boolean_value'); //布尔值
135
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_contacts', 'date_interval'); // 日期区间类型字段
136
+        $positionField = $fieldModel->getFieldByFormType('crm_contacts', 'position'); // 地址类型字段
137
+        $handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign'); // 手写签名类型字段
138
+        $locationField = $fieldModel->getFieldByFormType('crm_contacts', 'location'); // 定位类型字段
112
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
139
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
113
         $temporaryField = str_replace('_name', '', $order_field);
140
         $temporaryField = str_replace('_name', '', $order_field);
114
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
141
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
115
             $order_field = $temporaryField;
142
             $order_field = $temporaryField;
116
         }
143
         }
117
-		//排序
118
-		if ($order_type && $order_field) {
119
-			$order = $fieldModel->getOrderByFormtype('crm_contacts','contacts',$order_field,$order_type);
120
-		} else {
121
-			$order = 'contacts.update_time desc';
122
-		}
123
-		$readAuthIds = $userModel->getUserByPer('crm', 'contacts', 'read');
144
+        //排序
145
+        if ($order_type && $order_field) {
146
+            $order = $fieldModel->getOrderByFormtype('crm_contacts', 'contacts', $order_field, $order_type);
147
+        } else {
148
+            $order = 'contacts.update_time desc';
149
+        }
150
+        $readAuthIds = $userModel->getUserByPer('crm', 'contacts', 'read');
124
         $updateAuthIds = $userModel->getUserByPer('crm', 'contacts', 'update');
151
         $updateAuthIds = $userModel->getUserByPer('crm', 'contacts', 'update');
125
-        $deleteAuthIds = $userModel->getUserByPer('crm', 'contacts', 'delete');	
126
-       	$customerWhere = [];
152
+        $deleteAuthIds = $userModel->getUserByPer('crm', 'contacts', 'delete');
153
+        $customerWhere = [];
127
         if ($pageType == !'all') {
154
         if ($pageType == !'all') {
128
-			//非客户池条件
129
-        	$customerWhere = $customerModel->getWhereByCustomer();
130
-        }
131
-		$dataCount = db('crm_contacts')
132
-        			->alias('contacts')
133
-        			->join('__CRM_CUSTOMER__ customer','contacts.customer_id = customer.customer_id','LEFT')
134
-        			->where($map)
135
-        			->where($searchMap)
136
-        			->where($authMap)
137
-        			->where($customerWhere)
138
-        			->count('contacts_id');
139
-		if ($getCount == 1) {
140
-			$data['dataCount'] = $dataCount ? : 0;
141
-	        return $data;
142
-        }               
143
-		$list = db('crm_contacts')
144
-				->alias('contacts')
145
-				->join('__CRM_CUSTOMER__ customer','contacts.customer_id = customer.customer_id','LEFT')
146
-				->where($map)
147
-				->where($searchMap)
148
-				->where($authMap)
149
-				->where($customerWhere)
150
-        		->limit($request['offset'], $request['length'])
151
-        		->field('contacts.*,customer.name as customer_name')
152
-        		->orderRaw($order)
153
-        		->select();
154
-        foreach ($list as $k=>$v) {
155
-        	$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
156
-        	$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
157
-        	$list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ? : '';
158
-        	$list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : '';
159
-			foreach ($userField as $key => $val) {
160
-			    $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
161
-                $list[$k][$val.'_name'] = implode($usernameField, ',');
162
-        	}
163
-			foreach ($structureField as $key => $val) {
164
-			    $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
165
-                $list[$k][$val.'_name'] = implode($structureNameField, ',');
166
-        	}
155
+            //非客户池条件
156
+            $customerWhere = $customerModel->getWhereByCustomer();
157
+        }
158
+        $dataCount = db('crm_contacts')
159
+            ->alias('contacts')
160
+            ->join('__CRM_CUSTOMER__ customer', 'contacts.customer_id = customer.customer_id', 'LEFT')
161
+            ->where($map)
162
+            ->where($searchMap)
163
+            ->where($authMap)
164
+            ->where($partMap)
165
+            ->where($customerWhere)
166
+            ->count('contacts_id');
167
+        if ($getCount == 1) {
168
+            $data['dataCount'] = $dataCount ?: 0;
169
+            return $data;
170
+        }
171
+        $list = db('crm_contacts')
172
+            ->alias('contacts')
173
+            ->join('__CRM_CUSTOMER__ customer', 'contacts.customer_id = customer.customer_id', 'LEFT')
174
+            ->where($map)
175
+            ->where($searchMap)
176
+            ->where($partMap)
177
+            ->where($authMap)
178
+            ->where($customerWhere)
179
+            ->limit($request['offset'], $request['length'])
180
+            ->field('contacts.*,customer.name as customer_name')
181
+            ->orderRaw($order)
182
+            ->select();
183
+        # 扩展数据
184
+        $extraData = [];
185
+        $contacts_id_list = !empty($list) ? array_column($list, 'contacts_id') : [];
186
+        $extraList = db('crm_contacts_data')->whereIn('contacts_id', $contacts_id_list)->select();
187
+        foreach ($extraList as $key => $value) {
188
+            $extraData[$value['contacts_id']][$value['field']] = $value['content'];
189
+        }
190
+        foreach ($list as $k => $v) {
191
+            $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
192
+            $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
193
+            $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ?: '';
194
+            $list[$k]['customer_id_info']['name'] = $v['customer_name'] ?: '';
195
+            foreach ($userField as $key => $val) {
196
+                $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
197
+                $list[$k][$val] = implode($usernameField, ',');
198
+            }
199
+            foreach ($structureField as $key => $val) {
200
+                $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
201
+                $list[$k][$val] = implode($structureNameField, ',');
202
+            }
167
             foreach ($datetimeField as $key => $val) {
203
             foreach ($datetimeField as $key => $val) {
168
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
204
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
169
             }
205
             }
170
-
171
-			//权限
172
-			$permission = [];
173
-			$is_read = 0;
174
-			$is_update = 0;
175
-			$is_delete = 0;
176
-			if (in_array($v['owner_user_id'],$readAuthIds)) $is_read = 1;
177
-			if (in_array($v['owner_user_id'],$updateAuthIds)) $is_update = 1;
178
-			if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1;	        
179
-	        $permission['is_read'] = $is_read;
180
-	        $permission['is_update'] = $is_update;
181
-	        $permission['is_delete'] = $is_delete;
182
-	        $list[$k]['permission']	= $permission;
183
-
206
+            foreach ($booleanField as $key => $val) {
207
+                $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
208
+            }
209
+            // 处理日期区间类型字段的格式
210
+            foreach ($dateIntervalField as $key => $val) {
211
+                $list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
212
+            }
213
+            // 处理地址类型字段的格式
214
+            foreach ($positionField as $key => $val) {
215
+                $list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
216
+            }
217
+            // 手写签名类型字段
218
+            foreach ($handwritingField as $key => $val) {
219
+                $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
220
+                $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
221
+            }
222
+            // 定位类型字段
223
+            foreach ($locationField AS $key => $val) {
224
+                $list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
225
+            }
226
+            //权限
227
+            $permission = [];
228
+            $is_read = 0;
229
+            $is_update = 0;
230
+            $is_delete = 0;
231
+            if (in_array($v['owner_user_id'], $readAuthIds)) $is_read = 1;
232
+            if (in_array($v['owner_user_id'], $updateAuthIds)) $is_update = 1;
233
+            if (in_array($v['owner_user_id'], $deleteAuthIds)) $is_delete = 1;
234
+            $permission['is_read'] = $is_read;
235
+            $permission['is_update'] = $is_update;
236
+            $permission['is_delete'] = $is_delete;
237
+            $list[$k]['permission'] = $permission;
238
+            
184
             # 关注
239
             # 关注
185
             $starWhere = ['user_id' => $user_id, 'target_id' => $v['contacts_id'], 'type' => 'crm_contacts'];
240
             $starWhere = ['user_id' => $user_id, 'target_id' => $v['contacts_id'], 'type' => 'crm_contacts'];
186
             $star = Db::name('crm_star')->where($starWhere)->value('star_id');
241
             $star = Db::name('crm_star')->where($starWhere)->value('star_id');
188
             # 日期
243
             # 日期
189
             $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
244
             $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
190
             $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
245
             $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
191
-            $list[$k]['last_time']   = !empty($v['last_time'])   ? date('Y-m-d H:i:s', $v['last_time'])   : null;
246
+            $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
192
             # 创建人
247
             # 创建人
193
             $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
248
             $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
194
             # 负责人
249
             # 负责人
196
         }
251
         }
197
         $data = [];
252
         $data = [];
198
         $data['list'] = $list;
253
         $data['list'] = $list;
199
-        $data['dataCount'] = $dataCount ? : 0;
254
+        $data['dataCount'] = $dataCount ?: 0;
200
         return $data;
255
         return $data;
201
     }
256
     }
202
-
203
-	/**
204
-	 * 创建联系人主表信息
205
-	 * @author Michael_xu
206
-	 * @param  
207
-	 * @return                            
208
-	 */	
209
-	public function createData($param)
210
-	{
211
-	    $businessId = $param['business_id'];
212
-	    unset($param['business_id']);
213
-
214
-		$fieldModel = new \app\admin\model\Field();
215
-		// 自动验证
216
-		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
217
-		$validate = new Validate($validateArr['rule'], $validateArr['message']);
218
-		$result = $validate->check($param);
219
-		if (!$result) {
220
-			$this->error = $validate->getError();
221
-			return false;
222
-		}
223
-		# 处理客户首要联系人
257
+    
258
+    /**
259
+     * 创建联系人主表信息
260
+     * @param
261
+     * @return
262
+     * @author Michael_xu
263
+     */
264
+    public function createData($param)
265
+    {
266
+        unset($param['excel']);
267
+        
268
+        // 联系人扩展表数据
269
+        $contactsData = [];
270
+        
271
+        $businessId = $param['business_id'];
272
+        unset($param['business_id']);
273
+        $fieldModel = new \app\admin\model\Field();
274
+        
275
+        // 数据验证
276
+        $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
277
+        if (!empty($validateResult)) {
278
+            $this->error = $validateResult;
279
+            return false;
280
+        }
281
+        
282
+        # 处理客户首要联系人
224
         $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
283
         $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
225
         if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
284
         if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
226
             # 设置首要联系人,去除其他首要联系人状态
285
             # 设置首要联系人,去除其他首要联系人状态
227
             Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]);
286
             Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]);
228
         }
287
         }
229
-		if (!empty($param['customer_id']) && empty($primaryStatus)) {
230
-		    # 为客户添加第一个联系人默认设置成首要联系人
288
+        if (!empty($param['customer_id']) && empty($primaryStatus)) {
289
+            # 为客户添加第一个联系人默认设置成首要联系人
231
             $param['primary'] = 1;
290
             $param['primary'] = 1;
232
         }
291
         }
233
-
234
-		// 处理部门、员工、附件、多选类型字段
235
-		$arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
236
-		foreach ($arrFieldAtt as $k=>$v) {
237
-			$param[$v] = arrayToString($param[$v]);
238
-		}
292
+        
293
+        // 处理部门、员工、附件、多选类型字段
294
+        $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
295
+        foreach ($arrFieldAtt as $k => $v) {
296
+            $param[$v] = arrayToString($param[$v]);
297
+        }
239
         // 处理日期(date)类型
298
         // 处理日期(date)类型
240
         $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
299
         $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
241
         if (!empty($dateField)) {
300
         if (!empty($dateField)) {
242
-            foreach ($param AS $key => $value) {
301
+            foreach ($param as $key => $value) {
243
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
302
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
244
             }
303
             }
245
         }
304
         }
246
-
247
-		if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
248
-			updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
249
-            RecordActionLog($param['create_user_id'],'crm_contacts','save',$param['name'],'','','新增了联系人'.$param['name']);
250
-			$data = [];
251
-			$data['contacts_id'] = $this->contacts_id;
252
-
305
+        // 处理手写签名类型
306
+        $handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign');
307
+        if (!empty($handwritingField)) {
308
+            foreach ($param as $key => $value) {
309
+                if (in_array($key, $handwritingField)) {
310
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
311
+                }
312
+            }
313
+        }
314
+        // 处理地址、定位、日期区间、明细表格类型字段
315
+        $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
316
+        $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
317
+        $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
318
+        $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
319
+        foreach ($param as $key => $value) {
320
+            // 处理地址类型字段数据
321
+            if (in_array($key, $positionField)) {
322
+                if (!empty($value)) {
323
+                    $contactsData[] = [
324
+                        'field' => $key,
325
+                        'content' => json_encode($value, JSON_NUMERIC_CHECK),
326
+                        'create_time' => time()
327
+                    ];
328
+                    $positionNames = array_column($value, 'name');
329
+                    $param[$key] = implode(',', $positionNames);
330
+                } else {
331
+                    $param[$key] = '';
332
+                }
333
+            }
334
+            // 处理定位类型字段数据
335
+            if (in_array($key, $locationField)) {
336
+                if (!empty($value)) {
337
+                    $contactsData[] = [
338
+                        'field' => $key,
339
+                        'content' => json_encode($value, JSON_NUMERIC_CHECK),
340
+                        'create_time' => time()
341
+                    ];
342
+                    $param[$key] = $value['address'];
343
+                } else {
344
+                    $param[$key] = '';
345
+                }
346
+            }
347
+            // 处理日期区间类型字段数据
348
+            if (in_array($key, $dateIntervalField)) {
349
+                if (!empty($value)) {
350
+                    $contactsData[] = [
351
+                        'field' => $key,
352
+                        'content' => json_encode($value, JSON_NUMERIC_CHECK),
353
+                        'create_time' => time()
354
+                    ];
355
+                    $param[$key] = implode('_', $value);
356
+                } else {
357
+                    $param[$key] = '';
358
+                }
359
+            }
360
+            // 处理明细表格类型字段数据
361
+            if (in_array($key, $detailTableField)) {
362
+                if (!empty($value)) {
363
+                    $contactsData[] = [
364
+                        'field' => $key,
365
+                        'content' => json_encode($value, JSON_NUMERIC_CHECK),
366
+                        'create_time' => time()
367
+                    ];
368
+                    $param[$key] = $key;
369
+                } else {
370
+                    $param[$key] = '';
371
+                }
372
+            }
373
+        }
374
+        
375
+        if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
376
+            updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
377
+            RecordActionLog($param['create_user_id'], 'crm_contacts', 'save', $param['name'], '', '', '新增了联系人' . $param['name']);
378
+            $data = [];
379
+            $data['contacts_id'] = $this->contacts_id;
380
+            
253
             # 添加活动记录
381
             # 添加活动记录
254
             Db::name('crm_activity')->insert([
382
             Db::name('crm_activity')->insert([
255
-                'type'             => 2,
256
-                'activity_type'    => 3,
383
+                'type' => 2,
384
+                'activity_type' => 3,
257
                 'activity_type_id' => $data['contacts_id'],
385
                 'activity_type_id' => $data['contacts_id'],
258
-                'content'          => $param['name'],
259
-                'create_user_id'   => $param['create_user_id'],
260
-                'update_time'      => time(),
261
-                'create_time'      => time(),
262
-                'customer_ids'     => ',' . $param['customer_id'] . ','
386
+                'content' => $param['name'],
387
+                'create_user_id' => $param['create_user_id'],
388
+                'update_time' => time(),
389
+                'create_time' => time(),
390
+                'customer_ids' => ',' . $param['customer_id'] . ','
263
             ]);
391
             ]);
264
-
392
+            
265
             # 处理商机首要联系人
393
             # 处理商机首要联系人
266
             if (!empty($businessId)) {
394
             if (!empty($businessId)) {
267
                 Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $data['contacts_id']]);
395
                 Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $data['contacts_id']]);
268
             }
396
             }
269
-
270
-			return $data;
271
-		} else {
272
-			$this->error = '添加失败';
273
-			return false;
274
-		}			
275
-	}
276
-	
277
-	//根据IDs获取数组
278
-	public function getDataByStr($idstr)
279
-	{
280
-		$idArr = stringToArray($idstr);
281
-		if (!$idArr) {
282
-			return [];
283
-		}
284
-		$list = Db::name('CrmContacts')->where(['contacts_id' => ['in',$idArr]])->select();
285
-		return $list;
286
-	}
287
-
397
+            
398
+            // 添加联系人扩展数据
399
+            array_walk($contactsData, function (&$val) use ($data) {
400
+                $val['contacts_id'] = $data['contacts_id'];
401
+            });
402
+            db('crm_contacts_data')->insertAll($contactsData);
403
+            
404
+            return $data;
405
+        } else {
406
+            $this->error = '添加失败';
407
+            return false;
408
+        }
409
+    }
410
+    
411
+    //根据IDs获取数组
412
+    public function getDataByStr($idstr)
413
+    {
414
+        $idArr = stringToArray($idstr);
415
+        if (!$idArr) {
416
+            return [];
417
+        }
418
+        $list = Db::name('CrmContacts')->where(['contacts_id' => ['in', $idArr]])->select();
419
+        return $list;
420
+    }
421
+    
288
     /**
422
     /**
289
      * 编辑联系人主表信息
423
      * 编辑联系人主表信息
290
      *
424
      *
297
      * @throws \think\exception\DbException
431
      * @throws \think\exception\DbException
298
      * @throws \think\exception\PDOException
432
      * @throws \think\exception\PDOException
299
      */
433
      */
300
-	public function updateDataById($param, $contacts_id = '')
301
-	{
302
-		$userModel = new \app\admin\model\User();
303
-		$dataInfo = $this->getDataById($contacts_id);
304
-		if (!$dataInfo) {
305
-			$this->error = '数据不存在或已删除';
306
-			return false;
307
-		}
308
-		//判断权限
434
+    public function updateDataById($param, $contacts_id = '')
435
+    {
436
+        // 联系人扩展表数据
437
+        $contactsData = [];
438
+        
439
+        $userModel = new \app\admin\model\User();
440
+        $dataInfo = $this->getDataById($contacts_id);
441
+        if (!$dataInfo) {
442
+            $this->error = '数据不存在或已删除';
443
+            return false;
444
+        }
445
+        //判断权限
309
         $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'update');
446
         $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'update');
310
-        if (!in_array($dataInfo['owner_user_id'],$auth_user_ids)) {
447
+        if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
311
             $this->error = '无权操作';
448
             $this->error = '无权操作';
312
             return false;
449
             return false;
313
-        } 		
314
-
315
-		$param['contacts_id'] = $contacts_id;
316
-		//过滤不能修改的字段
317
-		$unUpdateField = ['create_user_id','is_deleted','delete_time'];
318
-		foreach ($unUpdateField as $v) {
319
-			unset($param[$v]);
320
-		}
321
-		$fieldModel = new \app\admin\model\Field();
322
-		// 自动验证
323
-//		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
324
-		$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
325
-		$validate = new Validate($validateArr['rule'], $validateArr['message']);
326
-
327
-		$result = $validate->check($param);
328
-		if (!$result) {
329
-			$this->error = $validate->getError();
330
-			return false;
331
-		}
332
-
333
-		// 处理部门、员工、附件、多选类型字段
334
-		$arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
335
-		foreach ($arrFieldAtt as $k=>$v) {
450
+        }
451
+        
452
+        $param['contacts_id'] = $contacts_id;
453
+        //过滤不能修改的字段
454
+        $unUpdateField = ['create_user_id', 'is_deleted', 'delete_time'];
455
+        foreach ($unUpdateField as $v) {
456
+            unset($param[$v]);
457
+        }
458
+        $fieldModel = new \app\admin\model\Field();
459
+        
460
+        // 数据验证
461
+        $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['contacts_id']);
462
+        if (!empty($validateResult)) {
463
+            $this->error = $validateResult;
464
+            return false;
465
+        }
466
+        
467
+        // 处理部门、员工、附件、多选类型字段
468
+        $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
469
+        foreach ($arrFieldAtt as $k => $v) {
336
             if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
470
             if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
337
-		}
471
+        }
338
         // 处理日期(date)类型
472
         // 处理日期(date)类型
339
         $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
473
         $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
340
         if (!empty($dateField)) {
474
         if (!empty($dateField)) {
341
-            foreach ($param AS $key => $value) {
475
+            foreach ($param as $key => $value) {
342
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
476
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
343
             }
477
             }
344
         }
478
         }
345
-
479
+        // 处理手写签名类型
480
+        $handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign');
481
+        if (!empty($handwritingField)) {
482
+            foreach ($param as $key => $value) {
483
+                if (in_array($key, $handwritingField)) {
484
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
485
+                }
486
+            }
487
+        }
488
+        // 处理地址、定位、日期区间、明细表格类型字段
489
+        $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
490
+        $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
491
+        $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
492
+        $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
493
+        foreach ($param as $key => $value) {
494
+            // 处理地址类型字段数据
495
+            if (in_array($key, $positionField)) {
496
+                if (!empty($value)) {
497
+                    $contactsData[] = [
498
+                        'field' => $key,
499
+                        'content' => json_encode($value, JSON_NUMERIC_CHECK),
500
+                        'create_time' => time()
501
+                    ];
502
+                    $positionNames = array_column($value, 'name');
503
+                    $param[$key] = implode(',', $positionNames);
504
+                } else {
505
+                    $param[$key] = '';
506
+                }
507
+            }
508
+            // 处理定位类型字段数据
509
+            if (in_array($key, $locationField)) {
510
+                if (!empty($value)) {
511
+                    $contactsData[] = [
512
+                        'field' => $key,
513
+                        'content' => json_encode($value, JSON_NUMERIC_CHECK),
514
+                        'create_time' => time()
515
+                    ];
516
+                    $param[$key] = $value['address'];
517
+                } else {
518
+                    $param[$key] = '';
519
+                }
520
+            }
521
+            // 处理日期区间类型字段数据
522
+            if (in_array($key, $dateIntervalField)) {
523
+                if (!empty($value)) {
524
+                    $contactsData[] = [
525
+                        'field' => $key,
526
+                        'content' => json_encode($value, JSON_NUMERIC_CHECK),
527
+                        'create_time' => time()
528
+                    ];
529
+                    $param[$key] = implode('_', $value);
530
+                } else {
531
+                    $param[$key] = '';
532
+                }
533
+            }
534
+            // 处理明细表格类型字段数据
535
+            if (in_array($key, $detailTableField)) {
536
+                if (!empty($value)) {
537
+                    $contactsData[] = [
538
+                        'field' => $key,
539
+                        'content' => json_encode($value, JSON_NUMERIC_CHECK),
540
+                        'create_time' => time()
541
+                    ];
542
+                    $param[$key] = $key;
543
+                } else {
544
+                    $param[$key] = '';
545
+                }
546
+            }
547
+        }
548
+        
346
         # 处理首要联系人
549
         # 处理首要联系人
347
         $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
550
         $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
348
         if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
551
         if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
353
             # 为客户添加第一个联系人默认设置成首要联系人
556
             # 为客户添加第一个联系人默认设置成首要联系人
354
             $param['primary'] = 1;
557
             $param['primary'] = 1;
355
         }
558
         }
356
-
357
-		if ($this->update($param, ['contacts_id' => $contacts_id], true)) {
358
-			//修改记录
359
-			updateActionLog($param['user_id'], 'crm_contacts', $contacts_id, $dataInfo, $param);
360
-            RecordActionLog($param['user_id'], 'crm_contacts', 'update',$dataInfo['name'], $dataInfo, $param);
361
-			$data = [];
362
-			$data['contacts_id'] = $contacts_id;
363
-			return $data;
364
-		} else {
365
-			$this->error = '编辑失败';
366
-			return false;
367
-		}					
368
-	}
369
-
559
+        
560
+        if ($this->update($param, ['contacts_id' => $contacts_id], true)) {
561
+            $data['contacts_id'] = $contacts_id;
562
+            //修改记录
563
+            updateActionLog($param['user_id'], 'crm_contacts', $contacts_id, $dataInfo, $param);
564
+            RecordActionLog($param['user_id'], 'crm_contacts', 'update', $dataInfo['name'], $dataInfo, $param);
565
+            // 添加联系人扩展数据
566
+            db('crm_contacts_data')->where('contacts_id', $contacts_id)->delete();
567
+            array_walk($contactsData, function (&$val) use ($contacts_id) {
568
+                $val['contacts_id'] = $contacts_id;
569
+            });
570
+            db('crm_contacts_data')->insertAll($contactsData);
571
+            
572
+            return $data;
573
+        } else {
574
+            $this->error = '编辑失败';
575
+            return false;
576
+        }
577
+    }
578
+    
370
     /**
579
     /**
371
      * 联系人数据
580
      * 联系人数据
372
      *
581
      *
377
      * @throws \think\db\exception\ModelNotFoundException
586
      * @throws \think\db\exception\ModelNotFoundException
378
      * @throws \think\exception\DbException
587
      * @throws \think\exception\DbException
379
      */
588
      */
380
-   	public function getDataById($id = '', $userId = 0)
381
-   	{   		
382
-   		$map['contacts_id'] = $id;
383
-		$dataInfo = db('crm_contacts')->where($map)->find();
384
-		if (!$dataInfo) {
385
-			$this->error = '暂无此数据';
386
-			return false;
387
-		}
388
-		$userModel = new \app\admin\model\User();
389
-		$dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
390
-		$dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : []; 
391
-		$dataInfo['customer_id_info'] = db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name,mobile,telephone,deal_status')->find();
589
+    public function getDataById($id = '', $userId = 0)
590
+    {
591
+        $map['contacts_id'] = $id;
592
+        $dataInfo = db('crm_contacts')->where($map)->find();
593
+        if (!$dataInfo) {
594
+            $this->error = '暂无此数据';
595
+            return false;
596
+        }
597
+        $userModel = new \app\admin\model\User();
598
+        $dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
599
+        $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
600
+        $dataInfo['customer_id_info'] = db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name,mobile,telephone,deal_status')->find();
392
         $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
601
         $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
393
         $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
602
         $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
394
         $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
603
         $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
405
         }
614
         }
406
         $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
615
         $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
407
         $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
616
         $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
408
-        $dataInfo['last_time']   = !empty($dataInfo['last_time'])   ? date('Y-m-d H:i:s', $dataInfo['last_time'])   : null;
617
+        $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
409
         // 字段授权
618
         // 字段授权
410
         if (!empty($userId)) {
619
         if (!empty($userId)) {
411
             $grantData = getFieldGrantData($userId);
620
             $grantData = getFieldGrantData($userId);
412
             $userLevel = isSuperAdministrators($userId);
621
             $userLevel = isSuperAdministrators($userId);
413
-            foreach ($dataInfo AS $key => $value) {
622
+            foreach ($dataInfo as $key => $value) {
414
                 if (!$userLevel && !empty($grantData['crm_contacts'])) {
623
                 if (!$userLevel && !empty($grantData['crm_contacts'])) {
415
                     $status = getFieldGrantStatus($key, $grantData['crm_contacts']);
624
                     $status = getFieldGrantStatus($key, $grantData['crm_contacts']);
416
-
625
+                    
417
                     # 查看权限
626
                     # 查看权限
418
                     if ($status['read'] == 0) unset($dataInfo[$key]);
627
                     if ($status['read'] == 0) unset($dataInfo[$key]);
419
                 }
628
                 }
420
             }
629
             }
421
         }
630
         }
422
-		return $dataInfo;
423
-   	}
424
-
425
-	/**
631
+        return $dataInfo;
632
+    }
633
+    
634
+    /**
426
      * [联系人转移]
635
      * [联系人转移]
427
-     * @author Michael_xu
428
      * @param ids 联系人ID数组
636
      * @param ids 联系人ID数组
429
      * @param owner_user_id 变更负责人
637
      * @param owner_user_id 变更负责人
430
      * @param is_remove 1移出,2转为团队成员
638
      * @param is_remove 1移出,2转为团队成员
431
-     * @return            
432
-     */	
639
+     * @return
640
+     * @author Michael_xu
641
+     */
433
     public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
642
     public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
434
     {
643
     {
435
-	    $settingModel = new \app\crm\model\Setting();      	
436
-    	foreach ($ids as $id) {
437
-			$data = [];
438
-	        $data['owner_user_id'] = $owner_user_id;
439
-	        $data['update_time'] = time(); 
440
-	        db('crm_contacts')->where(['contacts_id' => $id])->update($data);
441
-    	}
442
-    	return true;
644
+        $settingModel = new \app\crm\model\Setting();
645
+        foreach ($ids as $id) {
646
+            $data = [];
647
+            $data['owner_user_id'] = $owner_user_id;
648
+            $data['update_time'] = time();
649
+            db('crm_contacts')->where(['contacts_id' => $id])->update($data);
650
+        }
651
+        return true;
443
     }
652
     }
444
-
653
+    
445
     /**
654
     /**
446
      * 设置首要联系人
655
      * 设置首要联系人
447
      *
656
      *
455
     {
664
     {
456
         Db::name('crm_contacts')->where('customer_id', $customerId)->update(['primary' => 0]);
665
         Db::name('crm_contacts')->where('customer_id', $customerId)->update(['primary' => 0]);
457
         Db::name('crm_contacts')->where(['customer_id' => $customerId, 'contacts_id' => $contactsId])->update(['primary' => 1]);
666
         Db::name('crm_contacts')->where(['customer_id' => $customerId, 'contacts_id' => $contactsId])->update(['primary' => 1]);
458
-
667
+        
459
         return true;
668
         return true;
460
     }
669
     }
461
-
670
+    
462
     /**
671
     /**
463
      * 获取跟进记录联系人
672
      * 获取跟进记录联系人
464
      *
673
      *
472
     {
681
     {
473
         return Db::name('crm_contacts')->field(['contacts_id', 'name', 'mobile', 'telephone', 'detail_address'])->where('customer_id', $customerId)->order('primary', 'desc')->select();
682
         return Db::name('crm_contacts')->field(['contacts_id', 'name', 'mobile', 'telephone', 'detail_address'])->where('customer_id', $customerId)->order('primary', 'desc')->select();
474
     }
683
     }
475
-
684
+    
476
     /**
685
     /**
477
      * 获取系统信息
686
      * 获取系统信息
478
      *
687
      *
488
         $contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('contacts_id', $id)->find();
697
         $contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('contacts_id', $id)->find();
489
         # 创建人
698
         # 创建人
490
         $realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname');
699
         $realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname');
491
-
700
+        
492
         return [
701
         return [
493
             'create_user_id' => $realname,
702
             'create_user_id' => $realname,
494
             'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),
703
             'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),

+ 233
- 49
application/crm/model/Contract.php Bestand weergeven

6
 // +----------------------------------------------------------------------
6
 // +----------------------------------------------------------------------
7
 namespace app\crm\model;
7
 namespace app\crm\model;
8
 
8
 
9
+use app\admin\traits\FieldVerificationTrait;
9
 use think\Db;
10
 use think\Db;
10
 use app\admin\model\Common;
11
 use app\admin\model\Common;
11
 use app\admin\model\Message;
12
 use app\admin\model\Message;
12
-use think\Request;
13
-use think\Validate;
14
 
13
 
15
 class Contract extends Common
14
 class Contract extends Common
16
 {
15
 {
16
+    use FieldVerificationTrait;
17
+
17
 	/**
18
 	/**
18
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
20
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
48
     	$is_excel = $request['is_excel']; //导出
49
     	$is_excel = $request['is_excel']; //导出
49
         $getCount = $request['getCount'];
50
         $getCount = $request['getCount'];
50
         $contractIdArray = $request['contractIdArray']; // 待办事项提醒参数
51
         $contractIdArray = $request['contractIdArray']; // 待办事项提醒参数
52
+        $isMessage = !empty($request['isMessage']);
51
 
53
 
52
 		unset($request['scene_id']);
54
 		unset($request['scene_id']);
53
 		unset($request['search']);
55
 		unset($request['search']);
57
 		unset($request['is_excel']);
59
 		unset($request['is_excel']);
58
         unset($request['getCount']);
60
         unset($request['getCount']);
59
         unset($request['contractIdArray']);
61
         unset($request['contractIdArray']);
62
+        unset($request['isMessage']);
60
 
63
 
61
         $request = $this->fmtRequest( $request );
64
         $request = $this->fmtRequest( $request );
62
 
65
 
85
                     $query->whereLike('contract.name', '%' . $search . '%');
88
                     $query->whereLike('contract.name', '%' . $search . '%');
86
                 });
89
                 });
87
             };
90
             };
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
-//            }
95
 		}
91
 		}
96
 		$partMap = [];
92
 		$partMap = [];
97
 		//优先级:普通筛选>高级筛选>场景
93
 		//优先级:普通筛选>高级筛选>场景
98
-		if ($sceneMap['contract.ro_user_id'] && $sceneMap['contract.rw_user_id']) {
99
-			//相关团队查询
100
-			$map = $requestMap;
101
-			$partMap = function($query) use ($sceneMap){
102
-			        $query->where('contract.ro_user_id',array('like','%,'.$sceneMap['ro_user_id'].',%'))
103
-			        	->whereOr('contract.rw_user_id',array('like','%,'.$sceneMap['rw_user_id'].',%'));
104
-			};
105
-		} else {
106
-			$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
107
-		}
94
+        if ($requestMap['team_id']) {
95
+            //相关团队查询
96
+            $map = $requestMap;
97
+            $partMap= advancedQueryFormatForTeam($requestMap,'crm_contract','contract_id');
98
+            unset($map['team_id']);
99
+        } else {
100
+            $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
101
+        }
108
 		//高级筛选
102
 		//高级筛选
109
-		$map = where_arr($map, 'crm', 'contract', 'index');
103
+		$map = advancedQuery($map, 'crm', 'contract', 'index');
110
 		$order = ['contract.update_time desc'];	
104
 		$order = ['contract.update_time desc'];	
111
 		$authMap = [];
105
 		$authMap = [];
112
 		if (!$partMap) {
106
 		if (!$partMap) {
126
 		        $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
120
 		        $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
127
 		        $authMap['contract.owner_user_id'] = array('in',$auth_user_ids); 
121
 		        $authMap['contract.owner_user_id'] = array('in',$auth_user_ids); 
128
 		    } else {
122
 		    } else {
129
-		    	$authMapData = [];
130
-		    	$authMapData['auth_user_ids'] = $auth_user_ids;
131
-		    	$authMapData['user_id'] = $user_id;
132
-		    	$authMap = function($query) use ($authMapData){
133
-			        $query->where('contract.owner_user_id',array('in',$authMapData['auth_user_ids']))
134
-			        	->whereOr('contract.ro_user_id',array('like','%,'.$authMapData['user_id'].',%'))
135
-			        	->whereOr('contract.rw_user_id',array('like','%,'.$authMapData['user_id'].',%'));
136
-			    };
123
+			    // 待办事项的待审核合同不一定是自己创建的
124
+			    if (!$isMessage) {
125
+                    $authMapData = [];
126
+                    $authMapData['auth_user_ids'] = $auth_user_ids;
127
+                    $authMapData['user_id'] = $user_id;
128
+                    $authMap = function($query) use ($authMapData){
129
+                        $query->where('contract.owner_user_id',array('in',$authMapData['auth_user_ids']))
130
+                            ->whereOr('contract.ro_user_id',array('like','%,'.$authMapData['user_id'].',%'))
131
+                            ->whereOr('contract.rw_user_id',array('like','%,'.$authMapData['user_id'].',%'));
132
+                    };
133
+                }
137
 		    }
134
 		    }
138
 		}
135
 		}
139
 		//合同签约人 | 与高级筛选冲突,加一个is_array判断
136
 		//合同签约人 | 与高级筛选冲突,加一个is_array判断
146
 		$userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
143
 		$userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
147
 		$structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure');  //部门类型
144
 		$structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure');  //部门类型
148
         $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
145
         $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
146
+        $booleanField = $fieldModel->getFieldByFormType('crm_contract', 'boolean_value'); //布尔值
147
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_contract', 'date_interval'); // 日期区间类型字段
148
+        $positionField = $fieldModel->getFieldByFormType('crm_contract', 'position'); // 地址类型字段
149
+        $handwritingField = $fieldModel->getFieldByFormType('crm_contract', 'handwriting_sign'); // 手写签名类型字段
150
+        $locationField = $fieldModel->getFieldByFormType('crm_contract', 'location'); // 定位类型字段
149
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
151
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
150
         $temporaryField = str_replace('_name', '', $order_field);
152
         $temporaryField = str_replace('_name', '', $order_field);
151
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
153
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
209
         		->orderRaw($order)
211
         		->orderRaw($order)
210
         		->group('contract.contract_id')
212
         		->group('contract.contract_id')
211
         		->select();
213
         		->select();
214
+        # 扩展数据
215
+        $extraData = [];
216
+        $contract_id_list = !empty($list) ? array_column($list, 'contract_id') : [];
217
+        $extraList = db('crm_contract_data')->whereIn('contract_id', $contract_id_list)->select();
218
+        foreach ($extraList AS $key => $value) {
219
+            $extraData[$value['contract_id']][$value['field']] = $value['content'];
220
+        }
212
         foreach ($list as $k=>$v) {
221
         foreach ($list as $k=>$v) {
213
         	$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
222
         	$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
214
         	$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
223
         	$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
216
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
225
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
217
 			foreach ($userField as $key => $val) {
226
 			foreach ($userField as $key => $val) {
218
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
227
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
219
-                $list[$k][$val.'_name'] = implode($usernameField, ',');
228
+                $list[$k][$val] = implode($usernameField, ',');
220
         	}
229
         	}
221
 			foreach ($structureField as $key => $val) {
230
 			foreach ($structureField as $key => $val) {
222
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
231
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
223
-                $list[$k][$val.'_name'] = implode($structureNameField, ',');
232
+                $list[$k][$val] = implode($structureNameField, ',');
224
         	}
233
         	}
225
             foreach ($datetimeField as $key => $val) {
234
             foreach ($datetimeField as $key => $val) {
226
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
235
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
236
+            }
237
+            foreach ($booleanField as $key => $val) {
238
+                $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
239
+            }
240
+            // 处理日期区间类型字段的格式
241
+            foreach ($dateIntervalField AS $key => $val) {
242
+                $list[$k][$val] = !empty($extraData[$v['contract_id']][$val]) ? json_decode($extraData[$v['contract_id']][$val], true) : null;
243
+            }
244
+            // 处理地址类型字段的格式
245
+            foreach ($positionField AS $key => $val) {
246
+                $list[$k][$val] = !empty($extraData[$v['contract_id']][$val]) ? json_decode($extraData[$v['contract_id']][$val], true) : null;
247
+            }
248
+            // 手写签名类型字段
249
+            foreach ($handwritingField AS $key => $val) {
250
+                $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
251
+                $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
252
+            }
253
+            // 定位类型字段
254
+            foreach ($locationField AS $key => $val) {
255
+                $list[$k][$val] = !empty($extraData[$v['contract_id']][$val]) ? json_decode($extraData[$v['contract_id']][$val], true) : null;
227
             }
256
             }
228
         	$list[$k]['business_id_info']['business_id'] = $v['business_id'];
257
         	$list[$k]['business_id_info']['business_id'] = $v['business_id'];
229
         	$list[$k]['business_id_info']['name'] = $v['business_name'];
258
         	$list[$k]['business_id_info']['name'] = $v['business_name'];
230
         	$list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
259
         	$list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
231
         	$list[$k]['customer_id_info']['name'] = $v['customer_name'];
260
         	$list[$k]['customer_id_info']['name'] = $v['customer_name'];
232
 			$list[$k]['contacts_id_info']['contacts_id'] = $v['contacts_id'];
261
 			$list[$k]['contacts_id_info']['contacts_id'] = $v['contacts_id'];
233
-        	$list[$k]['contacts_id_info']['name'] = $v['contacts_name'];        	
262
+        	$list[$k]['contacts_id_info']['name'] = $v['contacts_name'];
263
+            $list[$k]['check_status_info'] = $this->statusArr[$v['check_status']];
234
         	$moneyInfo = [];
264
         	$moneyInfo = [];
235
         	$moneyInfo = $receivablesModel->getMoneyByContractId($v['contract_id']);
265
         	$moneyInfo = $receivablesModel->getMoneyByContractId($v['contract_id']);
236
         	$list[$k]['unMoney'] = $moneyInfo['doneMoney'] ? : '0.00';
266
         	$list[$k]['unMoney'] = $moneyInfo['doneMoney'] ? : '0.00';
266
             # 签约人姓名
296
             # 签约人姓名
267
             $orderNames = Db::name('admin_user')->whereIn('id', trim($v['order_user_id'], ','))->column('realname');
297
             $orderNames = Db::name('admin_user')->whereIn('id', trim($v['order_user_id'], ','))->column('realname');
268
             $list[$k]['order_user_name'] = implode(',', $orderNames);
298
             $list[$k]['order_user_name'] = implode(',', $orderNames);
299
+            unset($list[$k]['order_user_id']);
300
+            $list[$k]['order_user_id_name'] = $v['order_user_id'];
269
         }
301
         }
270
         $data = [];
302
         $data = [];
271
         $data['list'] = $list;
303
         $data['list'] = $list;
364
 	 */	
396
 	 */	
365
 	public function createData($param)
397
 	public function createData($param)
366
 	{
398
 	{
399
+        // 合同扩展表数据
400
+        $contractData = [];
401
+
367
 		$fieldModel = new \app\admin\model\Field();
402
 		$fieldModel = new \app\admin\model\Field();
368
 		$userModel = new \app\admin\model\User();
403
 		$userModel = new \app\admin\model\User();
369
 		$productModel = new \app\crm\model\Product();
404
 		$productModel = new \app\crm\model\Product();
370
-		// 自动验证
371
-		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
372
-		$validate = new Validate($validateArr['rule'], $validateArr['message']);
373
 
405
 
374
-		$result = $validate->check($param);
375
-		if (!$result) {
376
-			$this->error = $validate->getError();
377
-			return false;
378
-		}
406
+        // 数据验证
407
+        $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
408
+        if (!empty($validateResult)) {
409
+            $this->error = $validateResult;
410
+            return false;
411
+        }
379
 
412
 
380
         # 处理下次联系时间
413
         # 处理下次联系时间
381
         if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
414
         if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
392
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
425
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
393
             }
426
             }
394
         }
427
         }
428
+        // 处理手写签名类型
429
+        $handwritingField = $fieldModel->getFieldByFormType('crm_contract', 'handwriting_sign');
430
+        if (!empty($handwritingField)) {
431
+            foreach ($param AS $key => $value) {
432
+                if (in_array($key, $handwritingField)) {
433
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
434
+                }
435
+            }
436
+        }
437
+        // 处理地址、定位、日期区间、明细表格类型字段
438
+        $positionField     = $fieldModel->getFieldByFormType($this->name, 'position');
439
+        $locationField     = $fieldModel->getFieldByFormType($this->name, 'location');
440
+        $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
441
+        $detailTableField  = $fieldModel->getFieldByFormType($this->name, 'detail_table');
442
+        foreach ($param AS $key => $value) {
443
+            // 处理地址类型字段数据
444
+            if (in_array($key, $positionField)) {
445
+                if (!empty($value)) {
446
+                    $contractData[] = [
447
+                        'field'       => $key,
448
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
449
+                        'create_time' => time()
450
+                    ];
451
+                    $positionNames = array_column($value, 'name');
452
+                    $param[$key] = implode(',', $positionNames);
453
+                } else {
454
+                    $param[$key] = '';
455
+                }
456
+            }
457
+            // 处理定位类型字段数据
458
+            if (in_array($key, $locationField)) {
459
+                if (!empty($value)) {
460
+                    $contractData[] = [
461
+                        'field'       => $key,
462
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
463
+                        'create_time' => time()
464
+                    ];
465
+                    $param[$key] = $value['address'];
466
+                } else {
467
+                    $param[$key] = '';
468
+                }
469
+            }
470
+            // 处理日期区间类型字段数据
471
+            if (in_array($key, $dateIntervalField)) {
472
+                if (!empty($value)) {
473
+                    $contractData[] = [
474
+                        'field'       => $key,
475
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
476
+                        'create_time' => time()
477
+                    ];
478
+                    $param[$key] = implode('_', $value);
479
+                } else {
480
+                    $param[$key] = '';
481
+                }
482
+            }
483
+            // 处理明细表格类型字段数据
484
+            if (in_array($key, $detailTableField)) {
485
+                if (!empty($value)) {
486
+                    $contractData[] = [
487
+                        'field'       => $key,
488
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
489
+                        'create_time' => time()
490
+                    ];
491
+                    $param[$key] = $key;
492
+                } else {
493
+                    $param[$key] = '';
494
+                }
495
+            }
496
+        }
395
 
497
 
396
 		# 下单时间
498
 		# 下单时间
397
         $param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
499
         $param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
456
             }
558
             }
457
             if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
559
             if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
458
 
560
 
561
+            // 添加合同扩展数据
562
+            array_walk($contractData, function (&$val) use ($data) {
563
+                $val['contract_id'] = $data['contract_id'];
564
+            });
565
+            db('crm_contract_data')->insertAll($contractData);
566
+
459
 			return $data;
567
 			return $data;
460
 		} else {
568
 		} else {
461
 			$this->error = '添加失败';
569
 			$this->error = '添加失败';
472
 	 */	
580
 	 */	
473
 	public function updateDataById($param, $contract_id = '')
581
 	public function updateDataById($param, $contract_id = '')
474
 	{
582
 	{
583
+        // 合同扩展表数据
584
+        $contractData = [];
585
+
475
 		$productModel = new \app\crm\model\Product();
586
 		$productModel = new \app\crm\model\Product();
476
 		$userModel = new \app\admin\model\User();
587
 		$userModel = new \app\admin\model\User();
477
 		$dataInfo = db('crm_contract')->where(['contract_id' => $contract_id])->find();
588
 		$dataInfo = db('crm_contract')->where(['contract_id' => $contract_id])->find();
482
 		}
593
 		}
483
 		$param['contract_id'] = $contract_id;
594
 		$param['contract_id'] = $contract_id;
484
 		$fieldModel = new \app\admin\model\Field();
595
 		$fieldModel = new \app\admin\model\Field();
485
-		// 自动验证
486
-//		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
487
-		$validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
488
-		$validate = new Validate($validateArr['rule'], $validateArr['message']);
489
-
490
-		$result = $validate->check($param);
491
-		if (!$result) {
492
-			$this->error = $validate->getError();
493
-			return false;
494
-		}
596
+
597
+        // 数据验证
598
+        $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['contract_id']);
599
+        if (!empty($validateResult)) {
600
+            $this->error = $validateResult;
601
+            return false;
602
+        }
495
 
603
 
496
         # 处理下次联系时间
604
         # 处理下次联系时间
497
         if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
605
         if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
512
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
620
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
513
             }
621
             }
514
         }
622
         }
623
+        // 处理手写签名类型
624
+        $handwritingField = $fieldModel->getFieldByFormType('crm_contract', 'handwriting_sign');
625
+        if (!empty($handwritingField)) {
626
+            foreach ($param AS $key => $value) {
627
+                if (in_array($key, $handwritingField)) {
628
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
629
+                }
630
+            }
631
+        }
632
+        // 处理地址、定位、日期区间、明细表格类型字段
633
+        $positionField     = $fieldModel->getFieldByFormType($this->name, 'position');
634
+        $locationField     = $fieldModel->getFieldByFormType($this->name, 'location');
635
+        $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
636
+        $detailTableField  = $fieldModel->getFieldByFormType($this->name, 'detail_table');
637
+        foreach ($param AS $key => $value) {
638
+            // 处理地址类型字段数据
639
+            if (in_array($key, $positionField)) {
640
+                if (!empty($value)) {
641
+                    $contractData[] = [
642
+                        'field'       => $key,
643
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
644
+                        'create_time' => time()
645
+                    ];
646
+                    $positionNames = array_column($value, 'name');
647
+                    $param[$key] = implode(',', $positionNames);
648
+                } else {
649
+                    $param[$key] = '';
650
+                }
651
+            }
652
+            // 处理定位类型字段数据
653
+            if (in_array($key, $locationField)) {
654
+                if (!empty($value)) {
655
+                    $contractData[] = [
656
+                        'field'       => $key,
657
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
658
+                        'create_time' => time()
659
+                    ];
660
+                    $param[$key] = $value['address'];
661
+                } else {
662
+                    $param[$key] = '';
663
+                }
664
+            }
665
+            // 处理日期区间类型字段数据
666
+            if (in_array($key, $dateIntervalField)) {
667
+                if (!empty($value)) {
668
+                    $contractData[] = [
669
+                        'field'       => $key,
670
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
671
+                        'create_time' => time()
672
+                    ];
673
+                    $param[$key] = implode('_', $value);
674
+                } else {
675
+                    $param[$key] = '';
676
+                }
677
+            }
678
+            // 处理明细表格类型字段数据
679
+            if (in_array($key, $detailTableField)) {
680
+                if (!empty($value)) {
681
+                    $contractData[] = [
682
+                        'field'       => $key,
683
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
684
+                        'create_time' => time()
685
+                    ];
686
+                    $param[$key] = $key;
687
+                } else {
688
+                    $param[$key] = '';
689
+                }
690
+            }
691
+        }
515
 
692
 
516
 		if ($this->update($param, ['contract_id' => $contract_id], true)) {
693
 		if ($this->update($param, ['contract_id' => $contract_id], true)) {
517
 			//产品数据处理
694
 			//产品数据处理
549
             }
726
             }
550
             if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
727
             if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
551
 
728
 
729
+            // 添加合同扩展数据
730
+            db('crm_contract_data')->where('contract_id', $contract_id)->delete();
731
+            array_walk($contractData, function (&$val) use ($contract_id) {
732
+                $val['contract_id'] = $contract_id;
733
+            });
734
+            db('crm_contract_data')->insertAll($contractData);
735
+
552
 			return $data;
736
 			return $data;
553
 		} else {
737
 		} else {
554
 			$this->error = '编辑失败';
738
 			$this->error = '编辑失败';

+ 370
- 219
application/crm/model/Customer.php Bestand weergeven

8
 
8
 
9
 use app\admin\controller\ApiCommon;
9
 use app\admin\controller\ApiCommon;
10
 use app\admin\model\User;
10
 use app\admin\model\User;
11
+use app\admin\traits\FieldVerificationTrait;
11
 use think\Db;
12
 use think\Db;
12
 use app\admin\model\Common;
13
 use app\admin\model\Common;
13
-use app\admin\model\User as UserModel;
14
-use app\admin\model\Record as RecordModel;
15
-use think\Request;
16
 use think\response\Json;
14
 use think\response\Json;
17
-use think\Validate;
18
 
15
 
19
 class Customer extends Common
16
 class Customer extends Common
20
 {
17
 {
18
+    use FieldVerificationTrait;
19
+
21
 	/**
20
 	/**
22
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
21
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
23
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
22
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
48
      */		
47
      */		
49
 	public function getDataList($request)
48
 	public function getDataList($request)
50
     {
49
     {
51
-    	$userModel = new \app\admin\model\User();
52
-    	$structureModel = new \app\admin\model\Structure();
53
-    	$fieldModel = new \app\admin\model\Field();
54
-		$search = $request['search'];
55
-    	$user_id = $request['user_id'];
56
-    	$scene_id = (int)$request['scene_id'];
57
-    	$is_excel = $request['is_excel']; //导出
58
-    	$action = $request['action'];
50
+    	$userModel   = new \app\admin\model\User();
51
+    	$fieldModel  = new \app\admin\model\Field();
52
+		$search      = $request['search'];
53
+    	$user_id     = $request['user_id'];
54
+    	$scene_id    = (int)$request['scene_id'];
55
+    	$is_excel    = $request['is_excel']; //导出
59
     	$order_field = $request['order_field'];
56
     	$order_field = $request['order_field'];
60
-    	$order_type = $request['order_type'];
61
-    	$is_remind = $request['is_remind'];
62
-    	$getCount = $request['getCount'];
63
-    	$otherMap = $request['otherMap'];
64
-    	unset($request['poolId']);
65
-    	//需要过滤的参数
66
-    	$unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap'];
57
+    	$order_type  = $request['order_type'];
58
+    	$is_remind   = $request['is_remind'];
59
+    	$getCount    = $request['getCount'];
60
+    	$otherMap    = $request['otherMap'];
61
+        $overdue = $request['overdue']; // 待办事项下需联系客户(逾期)
62
+
63
+    	# 需要过滤的参数
64
+    	$unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap','poolId','overdue'];
67
     	foreach ($unsetRequest as $v) {
65
     	foreach ($unsetRequest as $v) {
68
     		unset($request[$v]);
66
     		unset($request[$v]);
69
     	}
67
     	}
70
-        $request = $this->fmtRequest( $request );
68
+
69
+    	# 格式化参数
70
+        $request    = $this->fmtRequest( $request );
71
         $requestMap = $request['map'] ? : [];
71
         $requestMap = $request['map'] ? : [];
72
 		$sceneModel = new \app\admin\model\Scene();
72
 		$sceneModel = new \app\admin\model\Scene();
73
-		# 默认条件
73
+
74
+		# 客户默认条件
74
         $customerMap = $this->getWhereByCustomer();
75
         $customerMap = $this->getWhereByCustomer();
76
+
75
         # getCount是代办事项传来的参数,代办事项不需要使用场景
77
         # getCount是代办事项传来的参数,代办事项不需要使用场景
76
         $sceneMap = [];
78
         $sceneMap = [];
77
         if (empty($getCount)) {
79
         if (empty($getCount)) {
83
                 $sceneMap = $sceneModel->getDefaultData('crm_customer', $user_id) ? : [];
85
                 $sceneMap = $sceneModel->getDefaultData('crm_customer', $user_id) ? : [];
84
             }
86
             }
85
         }
87
         }
88
+
89
+        # 普通筛选
86
 		$searchMap = [];
90
 		$searchMap = [];
87
 		if ($search || $search == '0') {
91
 		if ($search || $search == '0') {
88
-			//普通筛选
89
 			$searchMap = function($query) use ($search){
92
 			$searchMap = function($query) use ($search){
90
 			        $query->where('customer.name',array('like','%'.$search.'%'))
93
 			        $query->where('customer.name',array('like','%'.$search.'%'))
91
 			        	->whereOr('customer.mobile',array('like','%'.$search.'%'))
94
 			        	->whereOr('customer.mobile',array('like','%'.$search.'%'))
92
 			        	->whereOr('customer.telephone',array('like','%'.$search.'%'));
95
 			        	->whereOr('customer.telephone',array('like','%'.$search.'%'));
93
 			};
96
 			};
94
 		}
97
 		}
95
-		//优先级:普通筛选>高级筛选>场景
98
+
99
+		# 优先级:普通筛选 > 高级筛选 > 场景
96
         $map = [];
100
         $map = [];
97
         $partMap = [];
101
         $partMap = [];
98
-		if (is_array($sceneMap)) {
99
-			if ($sceneMap['ro_user_id'] && $sceneMap['rw_user_id']) {
100
-				//相关团队查询
101
-				$map = $requestMap;
102
-				$partMap = function($query) use ($sceneMap){
103
-				        $query->where('FIND_IN_SET('.$sceneMap['ro_user_id'].', customer.ro_user_id)')
104
-				        	->whereOr('FIND_IN_SET('.$sceneMap['rw_user_id'].', customer.rw_user_id)');
105
-				};				
106
-			} else {
107
-				$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
108
-			}
109
-		}
110
-		//高级筛选
111
-		$map = where_arr($map, 'crm', 'customer', 'index');
112
-        //工作台仪表盘
102
+        //团队成员 高级筛选
103
+        if($requestMap['team_id']){
104
+            $partMap= advancedQueryFormatForTeam($requestMap,'crm_customer','customer_id');
105
+            unset($map['team_id']);
106
+        }else{
107
+            $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
108
+        }
109
+		# 高级筛选
110
+		$map = advancedQuery($map, 'crm', 'customer', 'index');
111
+		
112
+		
113
+        # 工作台仪表盘
113
         $requestData = $this->requestData();
114
         $requestData = $this->requestData();
114
         $dashboardWhere = [];
115
         $dashboardWhere = [];
115
         if ($requestData['a'] == 'indexlist' && $requestData['c'] == 'index') {
116
         if ($requestData['a'] == 'indexlist' && $requestData['c'] == 'index') {
119
             };
120
             };
120
             unset($map['customer.create_time']);
121
             unset($map['customer.create_time']);
121
         }
122
         }
122
-        //权限
123
+
124
+        # 权限
123
         $authMap = [];
125
         $authMap = [];
124
-        $auth_user_ids = [];
125
         if (!$partMap) {
126
         if (!$partMap) {
126
             $a = 'index';
127
             $a = 'index';
127
             if ($is_excel) $a = 'excelExport';
128
             if ($is_excel) $a = 'excelExport';
156
             }
157
             }
157
         }
158
         }
158
 
159
 
160
+
159
         # 代办事项 - 待进入公海
161
         # 代办事项 - 待进入公海
160
         $remindWhere = [];
162
         $remindWhere = [];
161
         if ($is_remind) {
163
         if ($is_remind) {
163
             $userIds[] = $user_id;
165
             $userIds[] = $user_id;
164
             $poolDays = $this->getPoolDay([], $userIds);
166
             $poolDays = $this->getPoolDay([], $userIds);
165
             $remindWhere['customer.customer_id'] = ['in', array_keys($poolDays)];
167
             $remindWhere['customer.customer_id'] = ['in', array_keys($poolDays)];
166
-            if ($getCount == 1) return ['dataCount' => count($poolDays)];
168
+            $remindWhere['customer.pool_remain'] = 0;
169
+            if ($getCount == 1) {
170
+                $intoPoolCount = db('crm_customer')->alias('customer')->where($remindWhere)->count();
171
+                return ['dataCount' => $intoPoolCount];
172
+            }
173
+        }
174
+
175
+        // 待办事项下需联系客户(逾期)
176
+        $overdueWhere = '';
177
+        if (!empty($overdue)) {
178
+            $overdueWhere = "(FROM_UNIXTIME(`customer`.`last_time`,'%Y-%m-%d') < FROM_UNIXTIME(`customer`.`next_time`,'%Y-%m-%d') OR (ISNULL(`customer`.`last_time`) AND `customer`.`next_time` < ".time()."))";
167
         }
179
         }
168
 
180
 
169
 		$dataCount = db('crm_customer')->alias('customer')
181
 		$dataCount = db('crm_customer')->alias('customer')
175
         			->where($partMap)
187
         			->where($partMap)
176
         			->where($otherMap)
188
         			->where($otherMap)
177
                     ->where($remindWhere)
189
                     ->where($remindWhere)
190
+                    ->where($overdueWhere)
178
         			->count();
191
         			->count();
179
 
192
 
180
         if ($getCount == 1) {
193
         if ($getCount == 1) {
181
 			$data['dataCount'] = $dataCount ? : 0;
194
 			$data['dataCount'] = $dataCount ? : 0;
182
 	        return $data;
195
 	        return $data;
183
         }
196
         }
184
-		//列表展示字段
185
-		$indexField = $fieldModel->getIndexField('crm_customer', $user_id, 1) ? : array('name');
186
-		$userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); //人员类型
187
-		$structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); //部门类型
188
-        $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); //日期时间类型
197
+
198
+		$indexField = $fieldModel->getIndexField('crm_customer', $user_id, 1) ? : array('name'); // 列表展示字段
199
+		$userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); // 人员类型
200
+		$structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); // 部门类型
201
+        $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); // 日期时间类型
202
+        $booleanField = $fieldModel->getFieldByFormType('crm_customer', 'boolean_value'); // 布尔值类型字段
203
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_customer', 'date_interval'); // 日期区间类型字段
204
+        $positionField = $fieldModel->getFieldByFormType('crm_customer', 'position'); // 地址类型字段
205
+        $handwritingField = $fieldModel->getFieldByFormType('crm_customer', 'handwriting_sign'); // 手写签名类型字段
206
+        $locationField = $fieldModel->getFieldByFormType('crm_customer', 'location'); // 定位类型字段
189
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
207
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
190
         $temporaryField = str_replace('_name', '', $order_field);
208
         $temporaryField = str_replace('_name', '', $order_field);
191
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
209
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
192
             $order_field = $temporaryField;
210
             $order_field = $temporaryField;
193
         }
211
         }
194
-		//排序
212
+		# 排序
195
 		if ($order_type && $order_field) {
213
 		if ($order_type && $order_field) {
196
 			$order = $fieldModel->getOrderByFormtype('crm_customer','customer',$order_field,$order_type);
214
 			$order = $fieldModel->getOrderByFormtype('crm_customer','customer',$order_field,$order_type);
197
 		} else {
215
 		} else {
198
 			$order = 'customer.update_time desc';
216
 			$order = 'customer.update_time desc';
199
 		}
217
 		}
200
-
218
+  
201
 		$list = db('crm_customer')->alias('customer')
219
 		$list = db('crm_customer')->alias('customer')
202
 				->where($map)
220
 				->where($map)
203
 				->where($dashboardWhere)
221
 				->where($dashboardWhere)
207
 				->where($partMap)
225
 				->where($partMap)
208
 				->where($otherMap)
226
 				->where($otherMap)
209
                 ->where($remindWhere)
227
                 ->where($remindWhere)
228
+                ->where($overdueWhere)
210
         		->limit($request['offset'], $request['length'])
229
         		->limit($request['offset'], $request['length'])
211
         		->field($indexField)
230
         		->field($indexField)
212
         		->orderRaw($order)
231
         		->orderRaw($order)
213
 				->select();
232
 				->select();
214
-        # 查询公海数据的条件
215
-        $poolWhere = [];
216
         $readAuthIds = $userModel->getUserByPer('crm', 'customer', 'read');
233
         $readAuthIds = $userModel->getUserByPer('crm', 'customer', 'read');
217
         $updateAuthIds = $userModel->getUserByPer('crm', 'customer', 'update');
234
         $updateAuthIds = $userModel->getUserByPer('crm', 'customer', 'update');
218
 		$deleteAuthIds = $userModel->getUserByPer('crm', 'customer', 'delete');
235
 		$deleteAuthIds = $userModel->getUserByPer('crm', 'customer', 'delete');
231
 			$business_count = array_column($business_count, null, 'customer_id');
248
 			$business_count = array_column($business_count, null, 'customer_id');
232
 			$field_list = $fieldModel->getIndexFieldConfig('crm_customer', $user_id);
249
 			$field_list = $fieldModel->getIndexFieldConfig('crm_customer', $user_id);
233
 			$field_list = array_column($field_list, 'field');
250
 			$field_list = array_column($field_list, 'field');
234
-			foreach ($list as $k => $v) {
251
+			# 扩展数据
252
+            $extraData = [];
253
+            $extraList = db('crm_customer_data')->whereIn('customer_id', $customer_id_list)->select();
254
+            foreach ($extraList AS $key => $value) {
255
+                $extraData[$value['customer_id']][$value['field']] = $value['content'];
256
+            }
257
+            # 获取进入公海天数
258
+            $poolDays = $this->getPoolDay($customer_id_list);
259
+            # 整理数据
260
+			foreach ($list AS $k => $v) {
235
 	        	$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
261
 	        	$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
236
-				$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
262
+				$list[$k]['owner_user_id_info']  = isset($v['owner_user_id'])  ? $userModel->getUserById($v['owner_user_id'])  : [];
237
 				$list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
263
 				$list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
238
-                $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
239
-				foreach ($userField as $key => $val) {
240
-					if (in_array($val, $field_list)) {
264
+                $list[$k]['owner_user_name']  = !empty($list[$k]['owner_user_id_info']['realname'])  ? $list[$k]['owner_user_id_info']['realname']  : '';
265
+                # 用户类型字段
266
+				foreach ($userField AS $key => $val) {
267
+					if (in_array($val, $indexField)) {
241
                         $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
268
                         $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
242
-                        $list[$k][$val.'_name'] = implode($usernameField, ',');
269
+                        $list[$k][$val] = implode($usernameField, ',');
243
 					}
270
 					}
244
 	        	}
271
 	        	}
245
-				foreach ($structureField as $key => $val) {
246
-					if (in_array($val, $field_list)) {
272
+				# 部门类型字段
273
+				foreach ($structureField AS $key => $val) {
274
+					if (in_array($val, $indexField)) {
247
                         $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
275
                         $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
248
-                        $list[$k][$val.'_name'] = implode($structureNameField, ',');
276
+                        $list[$k][$val] = implode($structureNameField, ',');
249
 					}
277
 					}
250
 				}
278
 				}
251
-                foreach ($datetimeField as $key => $val) {
279
+				# 日期时间类型字段
280
+                foreach ($datetimeField AS $key => $val) {
252
                     $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
281
                     $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
253
                 }
282
                 }
254
-				//商机数
283
+                // 布尔值类型字段
284
+                foreach ($booleanField AS $key => $val) {
285
+                    $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
286
+                }
287
+                // 处理日期区间类型字段的格式
288
+                foreach ($dateIntervalField AS $key => $val) {
289
+                    $list[$k][$val] = !empty($extraData[$v['customer_id']][$val]) ? json_decode($extraData[$v['customer_id']][$val], true) : null;
290
+                }
291
+                // 处理地址类型字段的格式
292
+                foreach ($positionField AS $key => $val) {
293
+                    $list[$k][$val] = !empty($extraData[$v['customer_id']][$val]) ? json_decode($extraData[$v['customer_id']][$val], true) : null;
294
+                }
295
+                // 手写签名类型字段
296
+                foreach ($handwritingField AS $key => $val) {
297
+                    $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
298
+                    $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
299
+                }
300
+                // 定位类型字段
301
+                foreach ($locationField AS $key => $val) {
302
+                    $list[$k][$val] = !empty($extraData[$v['customer_id']][$val]) ? json_decode($extraData[$v['customer_id']][$val], true) : null;
303
+                }
304
+				# 商机数
255
 				$list[$k]['business_count'] = $business_count[$v['customer_id']]['count'] ?: 0;
305
 				$list[$k]['business_count'] = $business_count[$v['customer_id']]['count'] ?: 0;
256
-	        	//权限
306
+	        	# 权限
257
 	        	$roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read');
307
 	        	$roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read');
258
 	        	$rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update');
308
 	        	$rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update');
259
 				$permission = [];
309
 				$permission = [];
272
                 $starWhere = ['user_id' => $user_id, 'target_id' => $v['customer_id'], 'type' => 'crm_customer'];
322
                 $starWhere = ['user_id' => $user_id, 'target_id' => $v['customer_id'], 'type' => 'crm_customer'];
273
                 $star = Db::name('crm_star')->where($starWhere)->value('star_id');
323
                 $star = Db::name('crm_star')->where($starWhere)->value('star_id');
274
                 $list[$k]['star'] = !empty($star) ? 1 : 0;
324
                 $list[$k]['star'] = !empty($star) ? 1 : 0;
325
+
275
                 # 日期
326
                 # 日期
276
                 $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
327
                 $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
277
                 $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
328
                 $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
278
                 $list[$k]['last_time']   = !empty($v['last_time'])   ? date('Y-m-d H:i:s', $v['last_time'])   : null;
329
                 $list[$k]['last_time']   = !empty($v['last_time'])   ? date('Y-m-d H:i:s', $v['last_time'])   : null;
279
-                //查询公海数据的条件
280
-                $poolWhere[] = $v['customer_id'];
281
-                $list[$k]['pool_day'] = '';
330
+
331
+                # 进入公海天数
332
+                $list[$k]['pool_day'] = isset($poolDays[$v['customer_id']]) ? $poolDays[$v['customer_id']] : '';
282
                 $list[$k]['is_pool'] = 0;
333
                 $list[$k]['is_pool'] = 0;
283
-	        }
284
-            # 获取公海天数
285
-            $poolDays = !empty($poolWhere) ? $this->getPoolDay($poolWhere) : [];
286
-            if (!empty($poolDays)) {
287
-                foreach ($list AS $key => $value) {
288
-                    $list[$key]['pool_day'] = isset($poolDays[$value['customer_id']]) ? $poolDays[$value['customer_id']] : '';
289
-                }
290
-            }
334
+			}
291
         }
335
         }
292
         $data = [];
336
         $data = [];
293
         $data['list'] = $list ? : [];
337
         $data['list'] = $list ? : [];
303
 	 */	
347
 	 */	
304
 	public function createData($param)
348
 	public function createData($param)
305
 	{
349
 	{
350
+        unset($param['excel']);
351
+
352
+	    // 客户扩展表数据
353
+	    $customerData = [];
354
+
355
+	    $userId = $param['user_id'];
356
+
306
 		$fieldModel = new \app\admin\model\Field();
357
 		$fieldModel = new \app\admin\model\Field();
307
-		$userModel = new \app\admin\model\User();
308
 		$customerConfigModel = new \app\crm\model\CustomerConfig();
358
 		$customerConfigModel = new \app\crm\model\CustomerConfig();
309
-		//添加上限检测
359
+
360
+		// 添加上限检测
310
 		if (!$customerConfigModel->checkData($param['create_user_id'],1)) {
361
 		if (!$customerConfigModel->checkData($param['create_user_id'],1)) {
311
 			$this->error = $customerConfigModel->getError();
362
 			$this->error = $customerConfigModel->getError();
312
 			return false;
363
 			return false;
313
 		}
364
 		}
365
+
314
 		// 获取客户时间
366
 		// 获取客户时间
315
         $param['obtain_time'] = time();
367
         $param['obtain_time'] = time();
316
-		//地址
368
+
369
+		// 地址
317
 		$param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
370
 		$param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
318
 		$param['deal_time'] = time(); //领取、分配时间
371
 		$param['deal_time'] = time(); //领取、分配时间
319
 		$param['deal_status'] = '未成交';		
372
 		$param['deal_status'] = '未成交';		
320
-		//线索转客户
373
+
374
+		// 线索转客户
321
 		if ($param['leads_id']) {
375
 		if ($param['leads_id']) {
322
 			$leadsData = $param;
376
 			$leadsData = $param;
323
 			$leadsData['create_user_id'] = $param['create_user_id'];
377
 			$leadsData['create_user_id'] = $param['create_user_id'];
327
             $leadsData['detail_address'] = $param['detail_address']	? : '';
381
             $leadsData['detail_address'] = $param['detail_address']	? : '';
328
 
382
 
329
 			$param = $leadsData;
383
 			$param = $leadsData;
330
-		} 
331
-		// 自动验证
332
-		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
333
-		$validate = new Validate($validateArr['rule'], $validateArr['message']);			
334
-		$result = $validate->check($param);
335
-		if (!$result) {
336
-			$this->error = $validate->getError();
337
-			return false;
338
 		}
384
 		}
385
+
386
+		// 数据验证
387
+        $validateResult = $this->fieldDataValidate($param, 'crm_customer', $userId);
388
+		if (!empty($validateResult)) {
389
+		    $this->error = $validateResult;
390
+		    return false;
391
+        }
392
+
393
+        // 删除无效数据
394
+		unset($param['user_id']);
339
         unset($param['customer_id']);
395
         unset($param['customer_id']);
340
 
396
 
341
 		// 处理部门、员工、附件、多选类型字段
397
 		// 处理部门、员工、附件、多选类型字段
343
 		foreach ($arrFieldAtt as $k=>$v) {
399
 		foreach ($arrFieldAtt as $k=>$v) {
344
 			$param[$v] = arrayToString($param[$v]);
400
 			$param[$v] = arrayToString($param[$v]);
345
 		}
401
 		}
402
+
346
         // 处理日期(date)类型
403
         // 处理日期(date)类型
347
         $dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
404
         $dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
348
         if (!empty($dateField)) {
405
         if (!empty($dateField)) {
351
             }
408
             }
352
         }
409
         }
353
 
410
 
411
+        // 处理手写签名类型
412
+        $handwritingField = $fieldModel->getFieldByFormType('crm_customer', 'handwriting_sign');
413
+        if (!empty($handwritingField)) {
414
+            foreach ($param AS $key => $value) {
415
+                if (in_array($key, $handwritingField)) {
416
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
417
+                }
418
+            }
419
+        }
420
+
421
+        // 处理地址、定位、日期区间、明细表格类型字段
422
+        $positionField     = $fieldModel->getFieldByFormType('crm_customer', 'position');
423
+        $locationField     = $fieldModel->getFieldByFormType('crm_customer', 'location');
424
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_customer', 'date_interval');
425
+        $detailTableField  = $fieldModel->getFieldByFormType('crm_customer', 'detail_table');
426
+        foreach ($param AS $key => $value) {
427
+            // 处理地址类型字段数据
428
+            if (in_array($key, $positionField)) {
429
+                if (!empty($value)) {
430
+                    $customerData[] = [
431
+                        'field'       => $key,
432
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
433
+                        'create_time' => time()
434
+                    ];
435
+                    $positionNames = array_column($value, 'name');
436
+                    $param[$key] = implode(',', $positionNames);
437
+                } else {
438
+                    $param[$key] = '';
439
+                }
440
+            }
441
+            // 处理定位类型字段数据
442
+            if (in_array($key, $locationField)) {
443
+                if (!empty($value)) {
444
+                    $customerData[] = [
445
+                        'field'       => $key,
446
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
447
+                        'create_time' => time()
448
+                    ];
449
+                    $param[$key] = $value['address'];
450
+                } else {
451
+                    $param[$key] = '';
452
+                }
453
+            }
454
+            // 处理日期区间类型字段数据
455
+            if (in_array($key, $dateIntervalField)) {
456
+                if (!empty($value)) {
457
+                    $customerData[] = [
458
+                        'field'       => $key,
459
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
460
+                        'create_time' => time()
461
+                    ];
462
+                    $param[$key] = implode('_', $value);
463
+                } else {
464
+                    $param[$key] = '';
465
+                }
466
+            }
467
+            // 处理明细表格类型字段数据
468
+            if (in_array($key, $detailTableField)) {
469
+                if (!empty($value)) {
470
+                    $customerData[] = [
471
+                        'field'       => $key,
472
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
473
+                        'create_time' => time()
474
+                    ];
475
+                    $param[$key] = $key;
476
+                } else {
477
+                    $param[$key] = '';
478
+                }
479
+            }
480
+        }
481
+
354
         # 设置今日需联系客户
482
         # 设置今日需联系客户
355
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
483
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
356
-
484
+        $pool_id = !empty($param['pool_id']) ? $param['pool_id'] : 0;
485
+        unset($param['pool_id']);
357
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
486
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
358
-            if(!empty($param['pool_id'])){
359
-               db('crm_customer_pool_relation') ->insertGetId(['pool_id'=>$param['pool_id'],'customer_id'=>$this->customer_id]);
487
+            $data['customer_id'] = $this->customer_id;
488
+            $data['name'] = $param['name'];
489
+
490
+            if(!empty($pool_id)){
491
+               db('crm_customer_pool_relation') ->insertGetId(['pool_id'=>$pool_id,'customer_id'=>$this->customer_id]);
360
             }
492
             }
361
-			//修改记录
362
-            if(empty($param['leads_id'])){
363
-                updateActionLog($param['create_user_id'], 'crm_customer', $this->customer_id, '', '', '创建了客户');
493
+			// 修改记录
494
+            if (empty($param['leads_id'])) {
495
+                updateActionLog($param['create_user_id'], 'crm_customer', $data['customer_id'], '', '', '创建了客户');
364
                 RecordActionLog($param['create_user_id'],'crm_customer','save',$param['name'],'','','新增了客户'.$param['name']);
496
                 RecordActionLog($param['create_user_id'],'crm_customer','save',$param['name'],'','','新增了客户'.$param['name']);
365
             }
497
             }
366
-			$data = [];
367
-			$data['customer_id'] = $this->customer_id;
368
-			$data['name'] = $param['name'];
369
-
370
-            # 添加活动记录
498
+            // 添加活动记录
371
             Db::name('crm_activity')->insert([
499
             Db::name('crm_activity')->insert([
372
                 'type'             => 2,
500
                 'type'             => 2,
373
                 'activity_type'    => 2,
501
                 'activity_type'    => 2,
377
                 'update_time'      => time(),
505
                 'update_time'      => time(),
378
                 'create_time'      => time()
506
                 'create_time'      => time()
379
             ]);
507
             ]);
508
+            // 添加客户扩展数据
509
+            array_walk($customerData, function (&$val) use ($data) {
510
+                $val['customer_id'] = $data['customer_id'];
511
+            });
512
+            db('crm_customer_data')->insertAll($customerData);
380
 
513
 
381
 			return $data;
514
 			return $data;
382
 		} else {
515
 		} else {
404
 	 */
537
 	 */
405
     public function updateDataById($param, $customer_id = '')
538
     public function updateDataById($param, $customer_id = '')
406
     {
539
     {
540
+        // 客户扩展表数据
541
+        $customerData = [];
542
+
407
         $user_id = $param['user_id'];
543
         $user_id = $param['user_id'];
408
         $dataInfo = $this->get($customer_id);
544
         $dataInfo = $this->get($customer_id);
409
         if (!$dataInfo) {
545
         if (!$dataInfo) {
410
             $this->error = '数据不存在或已删除';
546
             $this->error = '数据不存在或已删除';
411
             return false;
547
             return false;
412
         }
548
         }
413
-        $id = $param['id']?:$customer_id;
414
-        
415
-        //数据权限判断
549
+        $id = !empty($param['id']) ? $param['id'] : $customer_id;
550
+        $param['customer_id'] = $customer_id;
551
+
552
+        // 数据权限判断
416
         $userModel = new \app\admin\model\User();
553
         $userModel = new \app\admin\model\User();
417
         $auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'update');
554
         $auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'update');
418
-        //读写权限
555
+
556
+        // 读写权限
419
         $rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
557
         $rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
420
-        //判断是否客户池数据
558
+
559
+        // 判断是否客户池数据
421
         if(empty($param['pool_id'])){
560
         if(empty($param['pool_id'])){
422
             $wherePool = $this->getWhereByPool();
561
             $wherePool = $this->getWhereByPool();
423
             $resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $id])->where($wherePool)->find();
562
             $resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $id])->where($wherePool)->find();
426
                 return false;
565
                 return false;
427
             }
566
             }
428
         }
567
         }
429
-        $param['customer_id'] = $customer_id;
430
-        //过滤不能修改的字段
568
+
569
+        // 过滤不能修改的字段
431
         $unUpdateField = ['create_user_id','is_deleted','delete_time','user_id'];
570
         $unUpdateField = ['create_user_id','is_deleted','delete_time','user_id'];
432
         foreach ($unUpdateField as $v) {
571
         foreach ($unUpdateField as $v) {
433
             unset($param[$v]);
572
             unset($param[$v]);
434
         }
573
         }
435
         $param['deal_status'] = $dataInfo['deal_status'];
574
         $param['deal_status'] = $dataInfo['deal_status'];
436
         $fieldModel = new \app\admin\model\Field();
575
         $fieldModel = new \app\admin\model\Field();
437
-        // 自动验证
438
-//        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
439
-        $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
440
-        $validate = new Validate($validateArr['rule'], $validateArr['message']);
441
-        $result = $validate->check($param);
442
-        if (!$result) {
443
-            $this->error = $validate->getError();
576
+
577
+        // 数据验证
578
+        $validateResult = $this->fieldDataValidate($param, 'crm_customer', $user_id, $id);
579
+        if (!empty($validateResult)) {
580
+            $this->error = $validateResult;
444
             return false;
581
             return false;
445
         }
582
         }
446
-        //地址
583
+
584
+        // 地址
447
         $param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
585
         $param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
448
         if ($param['deal_status'] == '已成交' && $dataInfo->data['deal_status'] == '未成交') {
586
         if ($param['deal_status'] == '已成交' && $dataInfo->data['deal_status'] == '未成交') {
449
             $param['deal_time'] = time();
587
             $param['deal_time'] = time();
454
         foreach ($arrFieldAtt as $k=>$v) {
592
         foreach ($arrFieldAtt as $k=>$v) {
455
             if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
593
             if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
456
         }
594
         }
595
+
457
         // 处理日期(date)类型
596
         // 处理日期(date)类型
458
         $dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
597
         $dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
459
         if (!empty($dateField)) {
598
         if (!empty($dateField)) {
462
             }
601
             }
463
         }
602
         }
464
 
603
 
465
-        # 设置今日需联系客户
604
+        // 处理手写签名类型
605
+        $handwritingField = $fieldModel->getFieldByFormType('crm_customer', 'handwriting_sign');
606
+        if (!empty($handwritingField)) {
607
+            foreach ($param AS $key => $value) {
608
+                if (in_array($key, $handwritingField)) {
609
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
610
+                }
611
+            }
612
+        }
613
+
614
+        // 处理地址、定位、日期区间、明细表格类型字段
615
+        $positionField     = $fieldModel->getFieldByFormType('crm_customer', 'position');
616
+        $locationField     = $fieldModel->getFieldByFormType('crm_customer', 'location');
617
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_customer', 'date_interval');
618
+        $detailTableField  = $fieldModel->getFieldByFormType('crm_customer', 'detail_table');
619
+        foreach ($param AS $key => $value) {
620
+            // 处理地址类型字段数据
621
+            if (in_array($key, $positionField)) {
622
+                if (!empty($value)) {
623
+                    $customerData[] = [
624
+                        'field'       => $key,
625
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
626
+                        'create_time' => time()
627
+                    ];
628
+                    $positionNames = array_column($value, 'name');
629
+                    $param[$key] = implode(',', $positionNames);
630
+                } else {
631
+                    $param[$key] = '';
632
+                }
633
+            }
634
+            // 处理定位类型字段数据
635
+            if (in_array($key, $locationField)) {
636
+                if (!empty($value)) {
637
+                    $customerData[] = [
638
+                        'field'       => $key,
639
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
640
+                        'create_time' => time()
641
+                    ];
642
+                    $param[$key] = $value['address'];
643
+                } else {
644
+                    $param[$key] = '';
645
+                }
646
+            }
647
+            // 处理日期区间类型字段数据
648
+            if (in_array($key, $dateIntervalField)) {
649
+                if (!empty($value)) {
650
+                    $customerData[] = [
651
+                        'field'       => $key,
652
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
653
+                        'create_time' => time()
654
+                    ];
655
+                    $param[$key] = implode('_', $value);
656
+                } else {
657
+                    $param[$key] = '';
658
+                }
659
+            }
660
+            // 处理明细表格类型字段数据
661
+            if (in_array($key, $detailTableField)) {
662
+                if (!empty($value)) {
663
+                    $customerData[] = [
664
+                        'field'       => $key,
665
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
666
+                        'create_time' => time()
667
+                    ];
668
+                    $param[$key] = $key;
669
+                } else {
670
+                    $param[$key] = '';
671
+                }
672
+            }
673
+        }
674
+
675
+        // 设置今日需联系客户
466
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
676
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
677
+
678
+        // 修改数据
467
         if ($this->update($param, ['customer_id' => $customer_id], true)) {
679
         if ($this->update($param, ['customer_id' => $customer_id], true)) {
468
-            if(!empty($param['pool_id'])){
469
-                db('crm_customer_pool_relation')->where('customer_id',$customer_id) ->update(['pool_id'=>$param['pool_id']]);
680
+            $data['customer_id'] = $customer_id;
681
+            // 修改公海
682
+            if (!empty($param['pool_id'])) {
683
+                db('crm_customer_pool_relation')->where('customer_id', $customer_id) ->update(['pool_id' => $param['pool_id']]);
470
             }
684
             }
471
-            //修改记录
685
+            // 修改记录
472
             updateActionLog($user_id, 'crm_customer', $customer_id, $dataInfo->data, $param);
686
             updateActionLog($user_id, 'crm_customer', $customer_id, $dataInfo->data, $param);
473
             RecordActionLog($user_id, 'crm_customer', 'update',$dataInfo['name'], $dataInfo->data, $param);
687
             RecordActionLog($user_id, 'crm_customer', 'update',$dataInfo['name'], $dataInfo->data, $param);
474
-            $data = [];
475
-            $data['customer_id'] = $customer_id;
688
+            // 添加客户扩展数据
689
+            db('crm_customer_data')->where('customer_id', $customer_id)->delete();
690
+            array_walk($customerData, function (&$val) use ($customer_id) {
691
+                $val['customer_id'] = $customer_id;
692
+            });
693
+            db('crm_customer_data')->insertAll($customerData);
694
+
476
             return $data;
695
             return $data;
477
         } else {
696
         } else {
478
             $this->error = '编辑失败';
697
             $this->error = '编辑失败';
537
                 }
756
                 }
538
             }
757
             }
539
         }
758
         }
759
+        // 新建发票时,使用的联系人数据(首要联系人)
760
+        $contactsInfo = db('crm_contacts')->field(['mobile', 'name', 'telephone', 'detail_address'])->where(['customer_id' => $id, 'primary' => 1])->find();
761
+        $contactsMobile = !empty($contactsInfo['mobile']) ? $contactsInfo['mobile'] : $contactsInfo['telephone'];
762
+        $dataInfo['contacts_name'] = $contactsInfo['name'];
763
+        $dataInfo['contacts_mobile'] = $contactsMobile;
764
+        $dataInfo['contacts_address'] = $contactsInfo['detail_address'];
540
         return $dataInfo;
765
         return $dataInfo;
541
    	}
766
    	}
542
 
767
 
671
         return $count;		
896
         return $count;		
672
 	}
897
 	}
673
 
898
 
674
-	/**
675
-     * [客户默认条件]
676
-     * @author Michael_xu
677
-     * @param 
678
-     * @return                   
679
-     */	
899
+    /**
900
+     * 客户默认条件
901
+     *
902
+     * @author fanqi
903
+     * @since 2021-05-12
904
+     * @return array
905
+     */
680
     public function getWhereByCustomer()
906
     public function getWhereByCustomer()
681
     {
907
     {
682
         return ['customer.owner_user_id' => ['neq', 0]];
908
         return ['customer.owner_user_id' => ['neq', 0]];
683
-//		$configModel = new \app\crm\model\ConfigData();
684
-//		$userModel = new \app\admin\model\User();
685
-//        $configInfo = $configModel->getData();
686
-//    	$config = $configInfo['config'] ? : 0;
687
-//    	$follow_day = $configInfo['follow_day'] ? : 0;
688
-//    	$deal_day = $configInfo['deal_day'] ? : 0;
689
-//    	//默认条件(没有到期或已锁定)
690
-//    	$data['follow_time'] = time()-$follow_day*86400;
691
-//    	$data['deal_time'] = time()-$deal_day*86400;
692
-//    	if ($config == 1) {
693
-//    		if ($follow_day < $deal_day) {
694
-//				$whereData = function($query) use ($data){
695
-//			        		$query->where(function ($query) use ($data) {
696
-//		                        $query->where(['customer.update_time' => array('gt',$data['follow_time']),'customer.deal_time' => array('gt',$data['deal_time'])]);
697
-//		                    })
698
-//		                    ->whereOr(['customer.deal_status' => '已成交'])
699
-//		                    ->whereOr(['customer.is_lock' => 1]);
700
-//						};
701
-//    		} else {
702
-//				$whereData = function($query) use ($data){
703
-//			        		$query->where(function ($query) use ($data) {
704
-//		                        $query->where(['customer.deal_time' => array('gt',$data['deal_time'])]);
705
-//		                    })
706
-//		                    ->whereOr(['customer.deal_status' => '已成交'])
707
-//		                    ->whereOr(['customer.is_lock' => 1]);
708
-//						};
709
-//    		}
710
-//    	}
711
-//    	return $whereData ? : '';
712
-    }	
909
+    }
713
 
910
 
714
-	/**
715
-     * [客户公海条件]
716
-     * @author Michael_xu
717
-     * @param 
718
-     * @return                   
719
-     */	
911
+    /**
912
+     * 客户公海条件
913
+     *
914
+     * @author fanqi
915
+     * @since 2021-05-12
916
+     * @return array
917
+     */
720
     public function getWhereByPool()
918
     public function getWhereByPool()
721
     {
919
     {
722
-//		$configModel = new \app\crm\model\ConfigData();
723
-//        $configInfo = $configModel->getData();
724
-//    	$config = $configInfo['config'] ? : 0;
725
-//		$follow_day = $configInfo['follow_day'] ? : 0;
726
-//    	$deal_day = $configInfo['deal_day'] ? : 0;
727
-//    	$whereData = [];
728
-//    	//启用
729
-//    	if ($config == 1) {
730
-//			//默认公海条件(没有负责人或已经到期)
731
-//	    	$data['follow_time'] = time()-$follow_day*86400;
732
-//	    	$data['deal_time'] = time()-$deal_day*86400;
733
-//	    	$data['deal_status'] = '未成交';
734
-//	    	if ($follow_day < $deal_day) {
735
-//				$whereData = function($query) use ($data){
736
-//				        	$query->where(['customer.owner_user_id'=>0])
737
-//					        	->whereOr(function ($query) use ($data) {
738
-//									$query->where(function ($query) use ($data) {
739
-//				                        $query->where(['customer.update_time' => array('elt',$data['follow_time'])])
740
-//											->whereOr(['customer.deal_time' => array('elt',$data['deal_time'])]);
741
-//				                    })
742
-//				                    ->where(['customer.is_lock' => 0])
743
-//				                    ->where(['customer.deal_status' => ['neq','已成交']]);
744
-//								});
745
-//							};
746
-//	    	} else {
747
-//				$whereData = function($query) use ($data){
748
-//				        	$query->where(['customer.owner_user_id'=>0])
749
-//					        	->whereOr(function ($query) use ($data) {
750
-//									$query->where(function ($query) use ($data) {
751
-//				                        $query->where(['customer.deal_time' => array('elt',$data['deal_time'])]);
752
-//				                    })
753
-//				                    ->where(['customer.is_lock' => 0])
754
-//				                    ->where(['customer.deal_status' => ['neq','已成交']]);
755
-//								});
756
-//							};
757
-//	    	}
758
-//    	} else {
759
-    		$whereData['customer.owner_user_id'] = 0;
760
-//    	}
761
-    	return !empty($whereData) ? $whereData : '';
920
+    	return ['customer.owner_user_id' => ['eq', 0]];
762
     }
921
     }
763
 
922
 
764
 	/**
923
 	/**
1449
      */
1608
      */
1450
     public function getNearbyList($param)
1609
     public function getNearbyList($param)
1451
     {
1610
     {
1452
-        $apiCommon = new ApiCommon();
1453
         $userModel = new \app\admin\model\User();
1611
         $userModel = new \app\admin\model\User();
1454
 
1612
 
1455
-        $poolStatus = checkPerByAction('crm', 'customer', 'pool');
1456
-
1457
-        # 客户
1458
-        $customerAuth = [];
1613
+        # 客户条件
1459
         $customerWhere = [];
1614
         $customerWhere = [];
1460
-        if ((!empty($param['type']) && $param['type'] == 2) || !$poolStatus) {
1615
+        if (!empty($param['type']) && $param['type'] == 2) {
1461
             $customerWhere = $this->getWhereByCustomer();
1616
             $customerWhere = $this->getWhereByCustomer();
1462
         }
1617
         }
1463
 
1618
 
1464
-        # 公海
1619
+        # 公海条件
1465
         $poolWhere = [];
1620
         $poolWhere = [];
1466
-        if (!empty($param['type']) && $param['type'] == 9 && $poolStatus) {
1467
-            $poolWhere = ['customer.customer_id' => 0];
1621
+        if (!empty($param['type']) && $param['type'] == 9) {
1622
+            $poolWhere = ['customer.owner_user_id' => 0];
1468
             $model = '公海客户管理模块';
1623
             $model = '公海客户管理模块';
1469
         }
1624
         }
1470
 
1625
 
1471
-        if (!empty($param['type']) && $param['type'] == 9 && !$poolStatus) {
1472
-            $model = '客户管理模块';
1473
-            return [];
1474
-        }
1475
-
1476
-        # 附近
1626
+        # 距离条件
1477
         $lngLatRange = $this->getLngLatRange($param['lng'], $param['lat'], $param['distance']);
1627
         $lngLatRange = $this->getLngLatRange($param['lng'], $param['lat'], $param['distance']);
1478
         $lngLatWhere = function ($query) use ($lngLatRange) {
1628
         $lngLatWhere = function ($query) use ($lngLatRange) {
1479
             $query->where(['lng' => ['egt', $lngLatRange['minLng']]]);
1629
             $query->where(['lng' => ['egt', $lngLatRange['minLng']]]);
1493
             ->where($customerWhere)
1643
             ->where($customerWhere)
1494
             ->where($poolWhere)
1644
             ->where($poolWhere)
1495
             ->where($lngLatWhere)
1645
             ->where($lngLatWhere)
1496
-            ->where($customerAuth)
1497
             ->field(['customer_id', 'name', 'address', 'detail_address', 'owner_user_id', 'lat', 'lng','next_time','last_time'])
1646
             ->field(['customer_id', 'name', 'address', 'detail_address', 'owner_user_id', 'lat', 'lng','next_time','last_time'])
1498
             ->order('update_time', 'desc')
1647
             ->order('update_time', 'desc')
1499
             ->select();
1648
             ->select();
1500
 
1649
 
1501
         # 组装数据
1650
         # 组装数据
1502
         foreach ($list as $key => $value) {
1651
         foreach ($list as $key => $value) {
1503
-            # todo 暂时将查询写在循环中
1504
             $ownerUserInfo = !empty($value['owner_user_id'])    ? $userModel->getUserById($value['owner_user_id']) : [];
1652
             $ownerUserInfo = !empty($value['owner_user_id'])    ? $userModel->getUserById($value['owner_user_id']) : [];
1505
             $ownerUserName = !empty($ownerUserInfo['realname']) ? $ownerUserInfo['realname'] : '';
1653
             $ownerUserName = !empty($ownerUserInfo['realname']) ? $ownerUserInfo['realname'] : '';
1506
             $list[$key]['owner_user_name'] = !empty($ownerUserName) ? $ownerUserName : '暂无负责人';
1654
             $list[$key]['owner_user_name'] = !empty($ownerUserName) ? $ownerUserName : '暂无负责人';
1585
     public function getSystemInfo($id)
1733
     public function getSystemInfo($id)
1586
     {
1734
     {
1587
         # 客户
1735
         # 客户
1588
-        $field = ['obtain_time', 'deal_status', 'create_time', 'update_time', 'create_time', 'last_time', 'last_record'];
1736
+        $field = ['obtain_time', 'owner_user_id', 'create_user_id', 'deal_status', 'update_time', 'create_time', 'last_time', 'last_record'];
1589
         $customer = Db::name('crm_customer')->field($field)->where('customer_id', $id)->find();
1737
         $customer = Db::name('crm_customer')->field($field)->where('customer_id', $id)->find();
1590
         # 创建人
1738
         # 创建人
1591
-        $realname = Db::name('admin_user')->where('id', $customer['create_user_id'])->value('realname');
1739
+        $createUserName = Db::name('admin_user')->where('id', $customer['create_user_id'])->value('realname');
1740
+        # 负责人
1741
+        $ownerUserName = Db::name('admin_user')->where('id', $customer['owner_user_id'])->value('realname');
1592
 
1742
 
1593
         return [
1743
         return [
1594
             'obtain_time' => !empty($customer['obtain_time']) ? date('Y-m-d H:i:s', $customer['obtain_time']) : '',
1744
             'obtain_time' => !empty($customer['obtain_time']) ? date('Y-m-d H:i:s', $customer['obtain_time']) : '',
1595
             'last_record' => !empty($customer['last_record']) ? $customer['last_record'] : '',
1745
             'last_record' => !empty($customer['last_record']) ? $customer['last_record'] : '',
1596
-            'create_user_id' => $realname,
1746
+            'create_user_id' => $createUserName,
1747
+            'owner_user_id' => $ownerUserName,
1597
             'create_time' => date('Y-m-d H:i:s', $customer['create_time']),
1748
             'create_time' => date('Y-m-d H:i:s', $customer['create_time']),
1598
             'update_time' => date('Y-m-d H:i:s', $customer['update_time']),
1749
             'update_time' => date('Y-m-d H:i:s', $customer['update_time']),
1599
             'last_time' => !empty($customer['last_time']) ? date('Y-m-d H:i:s', $customer['last_time']) : '',
1750
             'last_time' => !empty($customer['last_time']) ? date('Y-m-d H:i:s', $customer['last_time']) : '',

+ 1
- 3
application/crm/model/CustomerConfig.php Bestand weergeven

93
                 $content='添加员工拥有、锁定客户限制';
93
                 $content='添加员工拥有、锁定客户限制';
94
                 $action='update';
94
                 $action='update';
95
             }
95
             }
96
-            $user=new ApiCommon();
97
-            $userInfo=$user->userInfo;
98
-            SystemActionLog($userInfo['id'], 'crm_customer','customer', $this->id,  $action,$content , '', '',$content);
96
+            SystemActionLog($param['user_id'], 'crm_customer','customer', $this->id,  $action,$content , '', '',$content);
99
             return $data;
97
             return $data;
100
 		} else {
98
 		} else {
101
 			$this->error = '创建失败';
99
 			$this->error = '创建失败';

+ 0
- 1
application/crm/model/Invoice.php Bestand weergeven

37
     {
37
     {
38
         return $this->hasOne('Contract', 'contract_id', 'contract_id')->bind([
38
         return $this->hasOne('Contract', 'contract_id', 'contract_id')->bind([
39
             'contract_number' => 'num',
39
             'contract_number' => 'num',
40
-            'contract_money'  => 'money'
41
         ]);
40
         ]);
42
     }
41
     }
43
 
42
 

+ 235
- 24
application/crm/model/Leads.php Bestand weergeven

6
 // +----------------------------------------------------------------------
6
 // +----------------------------------------------------------------------
7
 namespace app\crm\model;
7
 namespace app\crm\model;
8
 
8
 
9
+use app\admin\traits\FieldVerificationTrait;
9
 use think\Db;
10
 use think\Db;
10
 use app\admin\model\Common;
11
 use app\admin\model\Common;
11
-use app\admin\model\Record as RecordModel;
12
-use think\Request;
13
-use think\Validate;
14
 
12
 
15
 class Leads extends Common
13
 class Leads extends Common
16
 {
14
 {
15
+    use FieldVerificationTrait;
16
+
17
     /**
17
     /**
18
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
18
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
19
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
43
         $order_field = $request['order_field'];
43
         $order_field = $request['order_field'];
44
         $order_type = $request['order_type'];
44
         $order_type = $request['order_type'];
45
         $getCount = $request['getCount'];
45
         $getCount = $request['getCount'];
46
+        $overdue = $request['overdue']; // 待办事项下需联系线索(逾期)
46
         unset($request['scene_id']);
47
         unset($request['scene_id']);
47
         unset($request['search']);
48
         unset($request['search']);
48
         unset($request['user_id']);
49
         unset($request['user_id']);
50
         unset($request['order_field']);
51
         unset($request['order_field']);
51
         unset($request['order_type']);
52
         unset($request['order_type']);
52
         unset($request['getCount']);
53
         unset($request['getCount']);
54
+        unset($request['overdue']);
53
 
55
 
54
         $request = $this->fmtRequest($request);
56
         $request = $this->fmtRequest($request);
55
         $requestMap = $request['map'] ?: [];
57
         $requestMap = $request['map'] ?: [];
74
                     ->whereOr('leads.mobile', array('like', '%' . $search . '%'))
76
                     ->whereOr('leads.mobile', array('like', '%' . $search . '%'))
75
                     ->whereOr('leads.telephone', array('like', '%' . $search . '%'));
77
                     ->whereOr('leads.telephone', array('like', '%' . $search . '%'));
76
             };
78
             };
77
-            // $sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '线索名称'];
78
         }
79
         }
79
         //优先级:普通筛选>高级筛选>场景
80
         //优先级:普通筛选>高级筛选>场景
80
 
81
 
81
         $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
82
         $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
82
         //高级筛选
83
         //高级筛选
83
-        $map = where_arr($map, 'crm', 'leads', 'index');
84
+        $map = advancedQuery($map, 'crm', 'leads', 'index');
85
+//        $map = where_arr($map, 'crm', 'leads', 'index');
84
         //权限
86
         //权限
85
         $a = 'index';
87
         $a = 'index';
86
         if ($is_excel) $a = 'excelExport';
88
         if ($is_excel) $a = 'excelExport';
105
         $userField = $fieldModel->getFieldByFormType('crm_leads', 'user'); //人员类型
107
         $userField = $fieldModel->getFieldByFormType('crm_leads', 'user'); //人员类型
106
         $structureField = $fieldModel->getFieldByFormType('crm_leads', 'structure');  //部门类型
108
         $structureField = $fieldModel->getFieldByFormType('crm_leads', 'structure');  //部门类型
107
         $datetimeField = $fieldModel->getFieldByFormType('crm_leads', 'datetime'); //日期时间类型
109
         $datetimeField = $fieldModel->getFieldByFormType('crm_leads', 'datetime'); //日期时间类型
110
+        $booleanField = $fieldModel->getFieldByFormType('crm_leads', 'boolean_value'); //布尔值
111
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_leads', 'date_interval'); // 日期区间类型字段
112
+        $positionField = $fieldModel->getFieldByFormType('crm_leads', 'position'); // 地址类型字段
113
+        $handwritingField = $fieldModel->getFieldByFormType('crm_leads', 'handwriting_sign'); // 手写签名类型字段
114
+        $locationField = $fieldModel->getFieldByFormType('crm_leads', 'location'); // 定位类型字段
108
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
115
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
109
         $temporaryField = str_replace('_name', '', $order_field);
116
         $temporaryField = str_replace('_name', '', $order_field);
110
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
117
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
121
             $map['leads.is_transform'] = array('neq', 1);
128
             $map['leads.is_transform'] = array('neq', 1);
122
         }
129
         }
123
 
130
 
131
+        // 待办事项下需联系线索(逾期)
132
+        $overdueWhere = '';
133
+        if (!empty($overdue)) {
134
+            $overdueWhere = "(FROM_UNIXTIME(`leads`.`last_time`,'%Y-%m-%d') < FROM_UNIXTIME(`leads`.`next_time`,'%Y-%m-%d') OR (ISNULL(`leads`.`last_time`) AND `leads`.`next_time` < ".time()."))";
135
+        }
136
+
124
         $readAuthIds = $userModel->getUserByPer('crm', 'leads', 'read');
137
         $readAuthIds = $userModel->getUserByPer('crm', 'leads', 'read');
125
         $updateAuthIds = $userModel->getUserByPer('crm', 'leads', 'update');
138
         $updateAuthIds = $userModel->getUserByPer('crm', 'leads', 'update');
126
         $deleteAuthIds = $userModel->getUserByPer('crm', 'leads', 'delete');
139
         $deleteAuthIds = $userModel->getUserByPer('crm', 'leads', 'delete');
127
-        $dataCount = db('crm_leads')->alias('leads')->where($map)->where($searchMap)->where($authMap)->count('leads_id');
140
+        $dataCount = db('crm_leads')->alias('leads')->where($map)->where($searchMap)->where($authMap)->where($overdueWhere)->count('leads_id');
128
         if (!empty($getCount) && $getCount == 1) {
141
         if (!empty($getCount) && $getCount == 1) {
129
             $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
142
             $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
130
             return $data;
143
             return $data;
131
         }
144
         }
145
+
132
         $list = db('crm_leads')
146
         $list = db('crm_leads')
133
             ->alias('leads')
147
             ->alias('leads')
134
             ->where($map)
148
             ->where($map)
135
             ->where($searchMap)
149
             ->where($searchMap)
136
             ->where($authMap)
150
             ->where($authMap)
151
+            ->where($overdueWhere)
137
             ->limit($request['offset'], $request['length'])
152
             ->limit($request['offset'], $request['length'])
138
             ->field(implode(',', $indexField))
153
             ->field(implode(',', $indexField))
139
             ->orderRaw($order)
154
             ->orderRaw($order)
140
             ->select();
155
             ->select();
156
+//        echo db('crm_leads')->getLastSql();exit;
157
+        # 扩展数据
158
+        $extraData = [];
159
+        $leads_id_list = !empty($list) ? array_column($list, 'leads_id') : [];
160
+        $extraList = db('crm_leads_data')->whereIn('leads_id', $leads_id_list)->select();
161
+        foreach ($extraList AS $key => $value) {
162
+            $extraData[$value['leads_id']][$value['field']] = $value['content'];
163
+        }
141
         foreach ($list as $k => $v) {
164
         foreach ($list as $k => $v) {
142
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
165
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
143
             $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
166
             $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
145
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
168
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
146
             foreach ($userField as $key => $val) {
169
             foreach ($userField as $key => $val) {
147
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
170
                 $usernameField  = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
148
-                $list[$k][$val.'_name'] = implode($usernameField, ',');
171
+                $list[$k][$val] = implode($usernameField, ',');
149
             }
172
             }
150
             foreach ($structureField as $key => $val) {
173
             foreach ($structureField as $key => $val) {
151
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
174
                 $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
152
-                $list[$k][$val.'_name'] = implode($structureNameField, ',');
175
+                $list[$k][$val] = implode($structureNameField, ',');
153
             }
176
             }
154
             foreach ($datetimeField as $key => $val) {
177
             foreach ($datetimeField as $key => $val) {
155
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
178
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
156
             }
179
             }
180
+            foreach ($booleanField as $key => $val) {
181
+                $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
182
+            }
183
+            // 处理日期区间类型字段的格式
184
+            foreach ($dateIntervalField AS $key => $val) {
185
+                $list[$k][$val] = !empty($extraData[$v['leads_id']][$val]) ? json_decode($extraData[$v['leads_id']][$val], true) : null;
186
+            }
187
+            // 处理地址类型字段的格式
188
+            foreach ($positionField AS $key => $val) {
189
+                $list[$k][$val] = !empty($extraData[$v['leads_id']][$val]) ? json_decode($extraData[$v['leads_id']][$val], true) : null;
190
+            }
191
+            // 手写签名类型字段
192
+            foreach ($handwritingField AS $key => $val) {
193
+                $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
194
+                $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
195
+            }
196
+            // 定位类型字段
197
+            foreach ($locationField AS $key => $val) {
198
+                $list[$k][$val] = !empty($extraData[$v['leads_id']][$val]) ? json_decode($extraData[$v['leads_id']][$val], true) : null;
199
+            }
157
             //权限
200
             //权限
158
             $permission = [];
201
             $permission = [];
159
             $is_read = 0;
202
             $is_read = 0;
201
      */
244
      */
202
     public function createData($param)
245
     public function createData($param)
203
     {
246
     {
247
+        unset($param['excel']);
248
+
249
+        // 线索扩展表数据
250
+        $leadsData = [];
251
+
204
         $fieldModel = new \app\admin\model\Field();
252
         $fieldModel = new \app\admin\model\Field();
205
-        // 自动验证
206
-        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
207
-        $validate = new Validate($validateArr['rule'], $validateArr['message']);
208
 
253
 
209
-        $result = $validate->check($param);
210
-        if (!$result) {
211
-            $this->error = $validate->getError();
254
+//        // 自动验证
255
+//        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
256
+//        $validate = new Validate($validateArr['rule'], $validateArr['message']);
257
+//        $result = $validate->check($param);
258
+//        if (!$result) {
259
+//            $this->error = $validate->getError();
260
+//            return false;
261
+//        }
262
+
263
+        // 数据验证
264
+        $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
265
+        if (!empty($validateResult)) {
266
+            $this->error = $validateResult;
212
             return false;
267
             return false;
213
         }
268
         }
214
 
269
 
224
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
279
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
225
             }
280
             }
226
         }
281
         }
282
+        // 处理手写签名类型
283
+        $handwritingField = $fieldModel->getFieldByFormType('crm_leads', 'handwriting_sign');
284
+        if (!empty($handwritingField)) {
285
+            foreach ($param AS $key => $value) {
286
+                if (in_array($key, $handwritingField)) {
287
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
288
+                }
289
+            }
290
+        }
291
+        // 处理地址、定位、日期区间、明细表格类型字段
292
+        $positionField     = $fieldModel->getFieldByFormType($this->name, 'position');
293
+        $locationField     = $fieldModel->getFieldByFormType($this->name, 'location');
294
+        $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
295
+        $detailTableField  = $fieldModel->getFieldByFormType($this->name, 'detail_table');
296
+        foreach ($param AS $key => $value) {
297
+            // 处理地址类型字段数据
298
+            if (in_array($key, $positionField)) {
299
+                if (!empty($value)) {
300
+                    $leadsData[] = [
301
+                        'field'       => $key,
302
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
303
+                        'create_time' => time()
304
+                    ];
305
+                    $positionNames = array_column($value, 'name');
306
+                    $param[$key] = implode(',', $positionNames);
307
+                } else {
308
+                    $param[$key] = '';
309
+                }
310
+            }
311
+            // 处理定位类型字段数据
312
+            if (in_array($key, $locationField)) {
313
+                if (!empty($value)) {
314
+                    $leadsData[] = [
315
+                        'field'       => $key,
316
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
317
+                        'create_time' => time()
318
+                    ];
319
+                    $param[$key] = $value['address'];
320
+                } else {
321
+                    $param[$key] = '';
322
+                }
323
+            }
324
+            // 处理日期区间类型字段数据
325
+            if (in_array($key, $dateIntervalField)) {
326
+                if (!empty($value)) {
327
+                    $leadsData[] = [
328
+                        'field'       => $key,
329
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
330
+                        'create_time' => time()
331
+                    ];
332
+                    $param[$key] = implode('_', $value);
333
+                } else {
334
+                    $param[$key] = '';
335
+                }
336
+            }
337
+            // 处理明细表格类型字段数据
338
+            if (in_array($key, $detailTableField)) {
339
+                if (!empty($value)) {
340
+                    $leadsData[] = [
341
+                        'field'       => $key,
342
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
343
+                        'create_time' => time()
344
+                    ];
345
+                    $param[$key] = $key;
346
+                } else {
347
+                    $param[$key] = '';
348
+                }
349
+            }
350
+        }
227
 
351
 
228
         # 设置今日需联系线索
352
         # 设置今日需联系线索
229
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
353
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
230
 
354
 
231
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
355
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
356
+            $data['leads_id'] = $this->leads_id;
232
             //修改记录
357
             //修改记录
233
             updateActionLog($param['create_user_id'], 'crm_leads', $this->leads_id, '', '', '创建了线索');
358
             updateActionLog($param['create_user_id'], 'crm_leads', $this->leads_id, '', '', '创建了线索');
234
             RecordActionLog($param['create_user_id'],'crm_leads','save',$param['name'],'','','新增了线索'.$param['name']);
359
             RecordActionLog($param['create_user_id'],'crm_leads','save',$param['name'],'','','新增了线索'.$param['name']);
245
                 'contacts_ids'     => null,
370
                 'contacts_ids'     => null,
246
                 'business_ids'     => null
371
                 'business_ids'     => null
247
             ]);
372
             ]);
248
-            $data = [];
249
-            $data['leads_id'] = $this->leads_id;
373
+            // 添加线索扩展数据
374
+            array_walk($leadsData, function (&$val) use ($data) {
375
+                $val['leads_id'] = $data['leads_id'];
376
+            });
377
+            db('crm_leads_data')->insertAll($leadsData);
378
+
250
             return $data;
379
             return $data;
251
         } else {
380
         } else {
252
             $this->error = '添加失败';
381
             $this->error = '添加失败';
262
      */
391
      */
263
     public function updateDataById($param, $leads_id = '')
392
     public function updateDataById($param, $leads_id = '')
264
     {
393
     {
394
+        // 线索扩展表数据
395
+        $leadsData = [];
396
+
265
         $userModel = new \app\admin\model\User();
397
         $userModel = new \app\admin\model\User();
266
         $dataInfo = $this->getDataById($leads_id);
398
         $dataInfo = $this->getDataById($leads_id);
267
         if (!$dataInfo) {
399
         if (!$dataInfo) {
284
 
416
 
285
         $fieldModel = new \app\admin\model\Field();
417
         $fieldModel = new \app\admin\model\Field();
286
         // 自动验证
418
         // 自动验证
287
-//        $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
288
-        $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
289
-        $validate = new Validate($validateArr['rule'], $validateArr['message']);
290
-        $result = $validate->check($param);
291
-        if (!$result) {
292
-            $this->error = $validate->getError();
419
+//        $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
420
+//        $validate = new Validate($validateArr['rule'], $validateArr['message']);
421
+//        $result = $validate->check($param);
422
+//        if (!$result) {
423
+//            $this->error = $validate->getError();
424
+//            return false;
425
+//        }
426
+        // 数据验证
427
+        $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $leads_id);
428
+        if (!empty($validateResult)) {
429
+            $this->error = $validateResult;
293
             return false;
430
             return false;
294
         }
431
         }
295
 
432
 
305
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
442
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
306
             }
443
             }
307
         }
444
         }
445
+        // 处理手写签名类型
446
+        $handwritingField = $fieldModel->getFieldByFormType('crm_leads', 'handwriting_sign');
447
+        if (!empty($handwritingField)) {
448
+            foreach ($param AS $key => $value) {
449
+                if (in_array($key, $handwritingField)) {
450
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
451
+                }
452
+            }
453
+        }
454
+        // 处理地址、定位、日期区间、明细表格类型字段
455
+        $positionField     = $fieldModel->getFieldByFormType($this->name, 'position');
456
+        $locationField     = $fieldModel->getFieldByFormType($this->name, 'location');
457
+        $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
458
+        $detailTableField  = $fieldModel->getFieldByFormType($this->name, 'detail_table');
459
+        foreach ($param AS $key => $value) {
460
+            // 处理地址类型字段数据
461
+            if (in_array($key, $positionField)) {
462
+                if (!empty($value)) {
463
+                    $leadsData[] = [
464
+                        'field'       => $key,
465
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
466
+                        'create_time' => time()
467
+                    ];
468
+                    $positionNames = array_column($value, 'name');
469
+                    $param[$key] = implode(',', $positionNames);
470
+                } else {
471
+                    $param[$key] = '';
472
+                }
473
+            }
474
+            // 处理定位类型字段数据
475
+            if (in_array($key, $locationField)) {
476
+                if (!empty($value)) {
477
+                    $leadsData[] = [
478
+                        'field'       => $key,
479
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
480
+                        'create_time' => time()
481
+                    ];
482
+                    $param[$key] = $value['address'];
483
+                } else {
484
+                    $param[$key] = '';
485
+                }
486
+            }
487
+            // 处理日期区间类型字段数据
488
+            if (in_array($key, $dateIntervalField)) {
489
+                if (!empty($value)) {
490
+                    $leadsData[] = [
491
+                        'field'       => $key,
492
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
493
+                        'create_time' => time()
494
+                    ];
495
+                    $param[$key] = implode('_', $value);
496
+                } else {
497
+                    $param[$key] = '';
498
+                }
499
+            }
500
+            // 处理明细表格类型字段数据
501
+            if (in_array($key, $detailTableField)) {
502
+                if (!empty($value)) {
503
+                    $leadsData[] = [
504
+                        'field'       => $key,
505
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
506
+                        'create_time' => time()
507
+                    ];
508
+                    $param[$key] = $key;
509
+                } else {
510
+                    $param[$key] = '';
511
+                }
512
+            }
513
+        }
308
 
514
 
309
         # 设置今日需联系线索
515
         # 设置今日需联系线索
310
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
516
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
311
 
517
 
312
         if ($this->update($param, ['leads_id' => $leads_id], true)) {
518
         if ($this->update($param, ['leads_id' => $leads_id], true)) {
519
+            $data['leads_id'] = $leads_id;
313
             //修改记录
520
             //修改记录
314
             updateActionLog($param['user_id'], 'crm_leads', $leads_id, $dataInfo, $param);
521
             updateActionLog($param['user_id'], 'crm_leads', $leads_id, $dataInfo, $param);
315
             RecordActionLog($param['user_id'], 'crm_leads','update', $dataInfo['name'], $dataInfo, $param);
522
             RecordActionLog($param['user_id'], 'crm_leads','update', $dataInfo['name'], $dataInfo, $param);
316
-            $data = [];
317
-            $data['leads_id'] = $leads_id;
523
+            // 添加线索扩展数据
524
+            db('crm_leads_data')->where('leads_id', $leads_id)->delete();
525
+            array_walk($leadsData, function (&$val) use ($leads_id) {
526
+                $val['leads_id'] = $leads_id;
527
+            });
528
+            db('crm_leads_data')->insertAll($leadsData);
318
             return $data;
529
             return $data;
319
         } else {
530
         } else {
320
             $this->error = '编辑失败';
531
             $this->error = '编辑失败';

+ 213
- 27
application/crm/model/Product.php Bestand weergeven

6
 // +----------------------------------------------------------------------
6
 // +----------------------------------------------------------------------
7
 namespace app\crm\model;
7
 namespace app\crm\model;
8
 
8
 
9
+use app\admin\traits\FieldVerificationTrait;
9
 use think\Db;
10
 use think\Db;
10
 use app\admin\model\Common;
11
 use app\admin\model\Common;
11
 use app\admin\model\User as UserModel;
12
 use app\admin\model\User as UserModel;
12
-use app\admin\model\File as FileModel;
13
-use think\Request;
14
-use think\Validate;
15
 use traits\model\SoftDelete;
13
 use traits\model\SoftDelete;
16
 
14
 
17
 class Product extends Common
15
 class Product extends Common
18
 {
16
 {
19
-    use SoftDelete;
17
+    use SoftDelete, FieldVerificationTrait;
20
     
18
     
21
     protected $deleteTime = 'delete_time';
19
     protected $deleteTime = 'delete_time';
22
     
20
     
72
         //优先级:普通筛选>高级筛选>场景
70
         //优先级:普通筛选>高级筛选>场景
73
         $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
71
         $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
74
         //高级筛选
72
         //高级筛选
75
-        $map = where_arr($map, 'crm', 'product', 'index');
73
+        $map = advancedQuery($map, 'crm', 'product', 'index');
76
         if (!empty($isStatus)) {
74
         if (!empty($isStatus)) {
77
             $map['product.status'] = '上架';
75
             $map['product.status'] = '上架';
78
         }
76
         }
104
         $userField = $fieldModel->getFieldByFormType('crm_product', 'user'); //人员类型
102
         $userField = $fieldModel->getFieldByFormType('crm_product', 'user'); //人员类型
105
         $structureField = $fieldModel->getFieldByFormType('crm_product', 'structure');  //部门类型
103
         $structureField = $fieldModel->getFieldByFormType('crm_product', 'structure');  //部门类型
106
         $datetimeField = $fieldModel->getFieldByFormType('crm_product', 'datetime'); //日期时间类型
104
         $datetimeField = $fieldModel->getFieldByFormType('crm_product', 'datetime'); //日期时间类型
105
+        $booleanField = $fieldModel->getFieldByFormType('crm_product', 'boolean_value'); //布尔值
106
+        $dateIntervalField = $fieldModel->getFieldByFormType('crm_product', 'date_interval'); // 日期区间类型字段
107
+        $positionField = $fieldModel->getFieldByFormType('crm_product', 'position'); // 地址类型字段
108
+        $handwritingField = $fieldModel->getFieldByFormType('crm_product', 'handwriting_sign'); // 手写签名类型字段
109
+        $locationField = $fieldModel->getFieldByFormType('crm_product', 'location'); // 定位类型字段
107
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
110
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
108
         $temporaryField = str_replace('_name', '', $order_field);
111
         $temporaryField = str_replace('_name', '', $order_field);
109
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
112
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
132
         $dataCount = db('crm_product')->alias('product')
135
         $dataCount = db('crm_product')->alias('product')
133
             ->where($map)->where($authMap)
136
             ->where($map)->where($authMap)
134
             ->count('product_id');
137
             ->count('product_id');
138
+        # 扩展数据
139
+        $extraData = [];
140
+        $product_id_list = !empty($list) ? array_column($list, 'product_id') : [];
141
+        $extraList = db('crm_product_data')->whereIn('product_id', $product_id_list)->select();
142
+        foreach ($extraList AS $key => $value) {
143
+            $extraData[$value['product_id']][$value['field']] = $value['content'];
144
+        }
135
         foreach ($list as $k => $v) {
145
         foreach ($list as $k => $v) {
136
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
146
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
137
             $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
147
             $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
148
             foreach ($datetimeField as $key => $val) {
158
             foreach ($datetimeField as $key => $val) {
149
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
159
                 $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
150
             }
160
             }
161
+            foreach ($booleanField as $key => $val) {
162
+                $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
163
+            }
164
+            // 处理日期区间类型字段的格式
165
+            foreach ($dateIntervalField AS $key => $val) {
166
+                $list[$k][$val] = !empty($extraData[$v['product_id']][$val]) ? json_decode($extraData[$v['product_id']][$val], true) : null;
167
+            }
168
+            // 处理地址类型字段的格式
169
+            foreach ($positionField AS $key => $val) {
170
+                $list[$k][$val] = !empty($extraData[$v['product_id']][$val]) ? json_decode($extraData[$v['product_id']][$val], true) : null;
171
+            }
172
+            // 手写签名类型字段
173
+            foreach ($handwritingField AS $key => $val) {
174
+                $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
175
+                $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
176
+            }
177
+            // 定位类型字段
178
+            foreach ($locationField AS $key => $val) {
179
+                $list[$k][$val] = !empty($extraData[$v['product_id']][$val]) ? json_decode($extraData[$v['product_id']][$val], true) : null;
180
+            }
151
             //产品类型
181
             //产品类型
152
             $list[$k]['category_id_info'] = $v['category_name'];
182
             $list[$k]['category_id_info'] = $v['category_name'];
153
             # 处理日期格式
183
             # 处理日期格式
169
      */
199
      */
170
     public function createData($param)
200
     public function createData($param)
171
     {
201
     {
202
+        // 产品扩展表数据
203
+        $productData = [];
204
+
172
         $fieldModel = new \app\admin\model\Field();
205
         $fieldModel = new \app\admin\model\Field();
173
         $productCategoryModel = model('ProductCategory');
206
         $productCategoryModel = model('ProductCategory');
174
-        $dataInfo = db('crm_product')->where(['name' => $param['name'], 'delete_user_id' => 0])->find();
175
-        if (isset($dataInfo)) {
176
-            // 自动验证
177
-            $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
178
-            $validate = new Validate($validateArr['rule'], $validateArr['message']);
179
-            
180
-            $result = $validate->check($param);
181
-            if (!$result) {
182
-                $this->error = $validate->getError();
207
+
208
+        $productStatus = false;
209
+        if (!empty($param['excel'])) {
210
+            $productStatus = db('crm_product')->where(['name' => $param['name'], 'delete_user_id' => 0])->value('product_id');
211
+        }
212
+
213
+        // 数据验证
214
+        if (empty($param['excel']) || $productStatus) {
215
+            $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
216
+            if (!empty($validateResult)) {
217
+                $this->error = $validateResult;
183
                 return false;
218
                 return false;
219
+
184
             }
220
             }
185
         }
221
         }
222
+        unset($param['excel']);
223
+
186
         // 处理部门、员工、附件、多选类型字段
224
         // 处理部门、员工、附件、多选类型字段
187
         $arrFieldAtt = $fieldModel->getArrayField('crm_product');
225
         $arrFieldAtt = $fieldModel->getArrayField('crm_product');
188
         foreach ($arrFieldAtt as $k => $v) {
226
         foreach ($arrFieldAtt as $k => $v) {
195
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
233
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
196
             }
234
             }
197
         }
235
         }
236
+        // 处理手写签名类型
237
+        $handwritingField = $fieldModel->getFieldByFormType('crm_product', 'handwriting_sign');
238
+        if (!empty($handwritingField)) {
239
+            foreach ($param AS $key => $value) {
240
+                if (in_array($key, $handwritingField)) {
241
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
242
+                }
243
+            }
244
+        }
245
+        // 处理地址、定位、日期区间、明细表格类型字段
246
+        $positionField     = $fieldModel->getFieldByFormType($this->name, 'position');
247
+        $locationField     = $fieldModel->getFieldByFormType($this->name, 'location');
248
+        $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
249
+        $detailTableField  = $fieldModel->getFieldByFormType($this->name, 'detail_table');
250
+        foreach ($param AS $key => $value) {
251
+            // 处理地址类型字段数据
252
+            if (in_array($key, $positionField)) {
253
+                if (!empty($value)) {
254
+                    $productData[] = [
255
+                        'field'       => $key,
256
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
257
+                        'create_time' => time()
258
+                    ];
259
+                    $positionNames = array_column($value, 'name');
260
+                    $param[$key] = implode(',', $positionNames);
261
+                } else {
262
+                    $param[$key] = '';
263
+                }
264
+            }
265
+            // 处理定位类型字段数据
266
+            if (in_array($key, $locationField)) {
267
+                if (!empty($value)) {
268
+                    $productData[] = [
269
+                        'field'       => $key,
270
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
271
+                        'create_time' => time()
272
+                    ];
273
+                    $param[$key] = $value['address'];
274
+                } else {
275
+                    $param[$key] = '';
276
+                }
277
+            }
278
+            // 处理日期区间类型字段数据
279
+            if (in_array($key, $dateIntervalField)) {
280
+                if (!empty($value)) {
281
+                    $productData[] = [
282
+                        'field'       => $key,
283
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
284
+                        'create_time' => time()
285
+                    ];
286
+                    $param[$key] = implode('_', $value);
287
+                } else {
288
+                    $param[$key] = '';
289
+                }
290
+            }
291
+            // 处理明细表格类型字段数据
292
+            if (in_array($key, $detailTableField)) {
293
+                if (!empty($value)) {
294
+                    $productData[] = [
295
+                        'field'       => $key,
296
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
297
+                        'create_time' => time()
298
+                    ];
299
+                    $param[$key] = $key;
300
+                } else {
301
+                    $param[$key] = '';
302
+                }
303
+            }
304
+        }
198
         
305
         
199
         //产品分类
306
         //产品分类
200
         $category_id = $param['category_id'];
307
         $category_id = $param['category_id'];
213
         }
320
         }
214
         
321
         
215
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
322
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
323
+            $data['product_id'] = $this->product_id;
216
             updateActionLog($param['create_user_id'], 'crm_product', $this->product_id, '', '', '创建了产品');
324
             updateActionLog($param['create_user_id'], 'crm_product', $this->product_id, '', '', '创建了产品');
217
             RecordActionLog($param['create_user_id'], 'crm_product', 'save', $param['name'], '', '', '新增了产品' . $param['name']);
325
             RecordActionLog($param['create_user_id'], 'crm_product', 'save', $param['name'], '', '', '新增了产品' . $param['name']);
218
-            $data = [];
219
-            $data['product_id'] = $this->product_id;
326
+            // 添加产品扩展数据
327
+            array_walk($productData, function (&$val) use ($data) {
328
+                $val['product_id'] = $data['product_id'];
329
+            });
330
+            db('crm_product_data')->insertAll($productData);
331
+
220
             return $data;
332
             return $data;
221
         } else {
333
         } else {
222
             $this->error = '添加失败';
334
             $this->error = '添加失败';
232
      */
344
      */
233
     public function updateDataById($param, $product_id = '')
345
     public function updateDataById($param, $product_id = '')
234
     {
346
     {
347
+        // 产品扩展表数据
348
+        $productData = [];
349
+
235
         $userModel = new \app\admin\model\User();
350
         $userModel = new \app\admin\model\User();
236
         $dataInfo = $this->getDataById($product_id);
351
         $dataInfo = $this->getDataById($product_id);
237
         $productCategoryModel = model('ProductCategory');
352
         $productCategoryModel = model('ProductCategory');
254
         }
369
         }
255
         
370
         
256
         $fieldModel = new \app\admin\model\Field();
371
         $fieldModel = new \app\admin\model\Field();
257
-        // 自动验证
258
-//            $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
259
-        $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
260
-        $validate = new Validate($validateArr['rule'], $validateArr['message']);
261
-        
262
-        $result = $validate->check($param);
263
-        if (!$result) {
264
-            $this->error = $validate->getError();
372
+
373
+        // 数据验证
374
+        $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['product_id']);
375
+        if (!empty($validateResult)) {
376
+            $this->error = $validateResult;
265
             return false;
377
             return false;
266
         }
378
         }
267
         
379
         
268
-        
269
         // 处理部门、员工、附件、多选类型字段
380
         // 处理部门、员工、附件、多选类型字段
270
         $arrFieldAtt = $fieldModel->getArrayField('crm_product');
381
         $arrFieldAtt = $fieldModel->getArrayField('crm_product');
271
         foreach ($arrFieldAtt as $k => $v) {
382
         foreach ($arrFieldAtt as $k => $v) {
278
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
389
                 if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
279
             }
390
             }
280
         }
391
         }
392
+        // 处理手写签名类型
393
+        $handwritingField = $fieldModel->getFieldByFormType('crm_product', 'handwriting_sign');
394
+        if (!empty($handwritingField)) {
395
+            foreach ($param AS $key => $value) {
396
+                if (in_array($key, $handwritingField)) {
397
+                    $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
398
+                }
399
+            }
400
+        }
401
+        // 处理地址、定位、日期区间、明细表格类型字段
402
+        $positionField     = $fieldModel->getFieldByFormType($this->name, 'position');
403
+        $locationField     = $fieldModel->getFieldByFormType($this->name, 'location');
404
+        $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
405
+        $detailTableField  = $fieldModel->getFieldByFormType($this->name, 'detail_table');
406
+        foreach ($param AS $key => $value) {
407
+            // 处理地址类型字段数据
408
+            if (in_array($key, $positionField)) {
409
+                if (!empty($value)) {
410
+                    $productData[] = [
411
+                        'field'       => $key,
412
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
413
+                        'create_time' => time()
414
+                    ];
415
+                    $positionNames = array_column($value, 'name');
416
+                    $param[$key] = implode(',', $positionNames);
417
+                } else {
418
+                    $param[$key] = '';
419
+                }
420
+            }
421
+            // 处理定位类型字段数据
422
+            if (in_array($key, $locationField)) {
423
+                if (!empty($value)) {
424
+                    $productData[] = [
425
+                        'field'       => $key,
426
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
427
+                        'create_time' => time()
428
+                    ];
429
+                    $param[$key] = $value['address'];
430
+                } else {
431
+                    $param[$key] = '';
432
+                }
433
+            }
434
+            // 处理日期区间类型字段数据
435
+            if (in_array($key, $dateIntervalField)) {
436
+                if (!empty($value)) {
437
+                    $productData[] = [
438
+                        'field'       => $key,
439
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
440
+                        'create_time' => time()
441
+                    ];
442
+                    $param[$key] = implode('_', $value);
443
+                } else {
444
+                    $param[$key] = '';
445
+                }
446
+            }
447
+            // 处理明细表格类型字段数据
448
+            if (in_array($key, $detailTableField)) {
449
+                if (!empty($value)) {
450
+                    $productData[] = [
451
+                        'field'       => $key,
452
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
453
+                        'create_time' => time()
454
+                    ];
455
+                    $param[$key] = $key;
456
+                } else {
457
+                    $param[$key] = '';
458
+                }
459
+            }
460
+        }
281
         
461
         
282
         //产品分类
462
         //产品分类
283
         $category_id = $param['category_id'];
463
         $category_id = $param['category_id'];
295
             }
475
             }
296
         }
476
         }
297
         if ($this->update($param, ['product_id' => $product_id], true)) {
477
         if ($this->update($param, ['product_id' => $product_id], true)) {
478
+            $data['product_id'] = $product_id;
298
             //修改记录
479
             //修改记录
299
             updateActionLog($param['user_id'], 'crm_product', $product_id, $dataInfo, $param);
480
             updateActionLog($param['user_id'], 'crm_product', $product_id, $dataInfo, $param);
300
             RecordActionLog($param['user_id'], 'crm_product', 'update', $dataInfo['name'], $dataInfo, $param);
481
             RecordActionLog($param['user_id'], 'crm_product', 'update', $dataInfo['name'], $dataInfo, $param);
301
-            $data = [];
302
-            $data['product_id'] = $product_id;
482
+            // 添加产品扩展数据
483
+            db('crm_product_data')->where('product_id', $product_id)->delete();
484
+            array_walk($productData, function (&$val) use ($product_id) {
485
+                $val['product_id'] = $product_id;
486
+            });
487
+            db('crm_product_data')->insertAll($productData);
488
+
303
             return $data;
489
             return $data;
304
         } else {
490
         } else {
305
             $this->rollback();
491
             $this->rollback();

+ 13
- 18
application/crm/model/ProductCategory.php Bestand weergeven

62
 			$data = [];
62
 			$data = [];
63
 			$data['id'] = $this->category_id;
63
 			$data['id'] = $this->category_id;
64
             # 系统操作日志
64
             # 系统操作日志
65
-            $user=new ApiCommon();
66
-            $userInfo=$user->userInfo;
67
-            SystemActionLog($userInfo['id'], 'crm_product','customer', $this->category_id, 'save',$param['name'] , '', '','添加了产品分类:'.$param['name']);
65
+            SystemActionLog($param['create_user_id'], 'crm_product','customer', $this->category_id, 'save',$param['name'] , '', '','添加了产品分类:'.$param['name']);
68
             return $data;
66
             return $data;
69
 		} else {
67
 		} else {
70
 			$this->error = '添加失败';
68
 			$this->error = '添加失败';
93
 			$this->error = $validate->getError();
91
 			$this->error = $validate->getError();
94
 			return false;
92
 			return false;
95
 		}
93
 		}
96
-
94
+		$user_id=$param['user_id'];
95
+        unset($param['user_id']);
97
 		if ($this->allowField(true)->save($param, ['category_id' => $category_id])) {
96
 		if ($this->allowField(true)->save($param, ['category_id' => $category_id])) {
98
             # 系统操作日志
97
             # 系统操作日志
99
-            $user=new ApiCommon();
100
-            $userInfo=$user->userInfo;
101
-            SystemActionLog($userInfo['id'], 'crm_product','customer', $category_id,  'update',$dataInfo['name'] , '', '','编辑了产品分类:'.$dataInfo['name']);
98
+            SystemActionLog($user_id, 'crm_product','customer', $category_id,  'update',$dataInfo['name'] , '', '','编辑了产品分类:'.$dataInfo['name']);
102
             return true;
99
             return true;
103
 		} else {
100
 		} else {
104
 			$this->error = '编辑失败';
101
 			$this->error = '编辑失败';
108
 
105
 
109
 	/**
106
 	/**
110
 	 * [delDataById 根据id删除数据]
107
 	 * [delDataById 根据id删除数据]
111
-	 * @param     string                   $id     [主键]
108
+	 * @param     string                   $param['id']    [主键]
112
 	 * @param     boolean                  $delSon [是否删除子孙数据]
109
 	 * @param     boolean                  $delSon [是否删除子孙数据]
113
 	 * @return    [type]                           [description]
110
 	 * @return    [type]                           [description]
114
 	 */
111
 	 */
115
-	public function delDataById($id = '', $delSon = false)
112
+	public function delDataById($param = '', $delSon = false)
116
 	{
113
 	{
117
-		if (!$id) {
114
+		if (!$param['id']) {
118
 			$this->error = '删除失败';
115
 			$this->error = '删除失败';
119
 			return false;
116
 			return false;
120
 		}
117
 		}
121
 		//分类下已有产品,则不能删除
118
 		//分类下已有产品,则不能删除
122
 		$resDel = true;
119
 		$resDel = true;
123
-		if (db('crm_product')->where(['category_id' => $id])->find()) {
120
+		if (db('crm_product')->where(['category_id' => $param['id']])->find()) {
124
 			$resDel = false;			
121
 			$resDel = false;			
125
 		}
122
 		}
126
 		if ($delSon && is_numeric($id)) {
123
 		if ($delSon && is_numeric($id)) {
135
 			$this->error = '请先移除该类型及子类下的相关产品';
132
 			$this->error = '请先移除该类型及子类下的相关产品';
136
 			return false;			
133
 			return false;			
137
 		}
134
 		}
138
-        $data=db('crm_product_category')->where('category_id' , $id)->find();
135
+        $data=db('crm_product_category')->where('category_id' , $param['id'])->find();
139
 		//提交事务
136
 		//提交事务
140
 		$this->startTrans();
137
 		$this->startTrans();
141
 		try {
138
 		try {
142
-			$this->where(['category_id' => $id])->delete();
143
-			if ($delSon && is_numeric($id)) {
139
+			$this->where(['category_id' => $param['id']])->delete();
140
+			if ($delSon && is_numeric($param['id'])) {
144
 				// 删除子孙
141
 				// 删除子孙
145
-				$childIds = $this->getAllChild($id);
142
+				$childIds = $this->getAllChild($param['id']);
146
 				if ($childIds) {
143
 				if ($childIds) {
147
 					$this->where('category_id', 'in', $childIds)->delete();
144
 					$this->where('category_id', 'in', $childIds)->delete();
148
 				}
145
 				}
149
 			}
146
 			}
150
             # 系统操作日志
147
             # 系统操作日志
151
-            $user=new ApiCommon();
152
-            $userInfo=$user->userInfo;
153
-            SystemActionLog($userInfo['id'], 'crm_product','customer', $id,  'update',$data['name'] , '', '','删除了产品分类:'.$data['name']);
148
+            SystemActionLog($param['user_id'], 'crm_product','customer', $id,  'update',$data['name'] , '', '','删除了产品分类:'.$data['name']);
154
             $this->commit();
149
             $this->commit();
155
 			return true;
150
 			return true;
156
 		} catch(\Exception $e) {
151
 		} catch(\Exception $e) {

+ 717
- 511
application/crm/model/Receivables.php
Diff onderdrukt omdat het te groot bestand
Bestand weergeven


+ 213
- 21
application/crm/model/ReceivablesPlan.php Bestand weergeven

6
 // +----------------------------------------------------------------------
6
 // +----------------------------------------------------------------------
7
 namespace app\crm\model;
7
 namespace app\crm\model;
8
 
8
 
9
+use app\admin\traits\FieldVerificationTrait;
9
 use think\Db;
10
 use think\Db;
10
 use app\admin\model\Common;
11
 use app\admin\model\Common;
11
 use app\crm\model\Contract as ContractModel;
12
 use app\crm\model\Contract as ContractModel;
14
 
15
 
15
 class ReceivablesPlan extends Common
16
 class ReceivablesPlan extends Common
16
 {
17
 {
18
+    use FieldVerificationTrait;
19
+
17
 	/**
20
 	/**
18
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
21
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
22
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
59
 			$map['name'] = ['like', '%'.$map['search'].'%'];
62
 			$map['name'] = ['like', '%'.$map['search'].'%'];
60
 			unset($map['search']);
63
 			unset($map['search']);
61
 		} else {
64
 		} else {
62
-			$map = where_arr($map, 'crm', 'receivables_plan', 'index'); //高级筛选
65
+            // 高级筛选
66
+			$map = advancedQuery($map, 'crm', 'receivables_plan', 'index');
63
 		}
67
 		}
64
 		if ($map['receivables_plan.owner_user_id']) {
68
 		if ($map['receivables_plan.owner_user_id']) {
65
 			$map['contract.owner_user_id'] = $map['receivables_plan.owner_user_id'];
69
 			$map['contract.owner_user_id'] = $map['receivables_plan.owner_user_id'];
99
             }
103
             }
100
         }
104
         }
101
 
105
 
102
-        # 待办事项-待回款提醒-已回款
103
-        if (!empty($dealt)) {
104
-            $map = " (`receivables_plan`.`receivables_id` > ".$request['map']['receivables_id'][1]." )";
105
-        }
106
-
107
-
108
         $dataCount = db('crm_receivables_plan')
106
         $dataCount = db('crm_receivables_plan')
109
             ->alias('receivables_plan')
107
             ->alias('receivables_plan')
110
             ->join('__CRM_CONTRACT__ contract','receivables_plan.contract_id = contract.contract_id','LEFT')
108
             ->join('__CRM_CONTRACT__ contract','receivables_plan.contract_id = contract.contract_id','LEFT')
147
 	 * @return                            
145
 	 * @return                            
148
 	 */	
146
 	 */	
149
 	public function createData($param)
147
 	public function createData($param)
150
-	{	
148
+	{
149
+	    $userId = $param['user_id'];
150
+	    unset($param['user_id']);
151
 		if (!$param['contract_id']) {
151
 		if (!$param['contract_id']) {
152
 			$this->error = '请先选择合同';
152
 			$this->error = '请先选择合同';
153
 			return false;
153
 			return false;
166
 			$this->error = '提前提醒最大时间为 90 天';
166
 			$this->error = '提前提醒最大时间为 90 天';
167
 			return false;
167
 			return false;
168
 		}
168
 		}
169
-		// 自动验证
170
-		$validate = validate($this->name);
171
-		if (!$validate->check($param)) {
172
-			$this->error = $validate->getError();
173
-			return false;
174
-		}
169
+//		// 自动验证
170
+//		$validate = validate($this->name);
171
+//		if (!$validate->check($param)) {
172
+//			$this->error = $validate->getError();
173
+//			return false;
174
+//		}
175
+        // 数据验证
176
+        $validateResult = $this->fieldDataValidate($param, 'crm_receivables_plan', $userId);
177
+        if (!empty($validateResult)) {
178
+            $this->error = $validateResult;
179
+            return false;
180
+        }
175
 		if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件
181
 		if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件
176
 		//期数规则(1,2,3..)
182
 		//期数规则(1,2,3..)
177
 		$maxNum = db('crm_receivables_plan')->where(['contract_id' => $param['contract_id']])->max('num');
183
 		$maxNum = db('crm_receivables_plan')->where(['contract_id' => $param['contract_id']])->max('num');
178
 		$param['num'] = $maxNum ? $maxNum+1 : 1;
184
 		$param['num'] = $maxNum ? $maxNum+1 : 1;
179
 		//提醒日期
185
 		//提醒日期
180
 		$param['remind_date'] = $param['remind'] ? date('Y-m-d',strtotime($param['return_date'])-86400*$param['remind']) : $param['return_date'];
186
 		$param['remind_date'] = $param['remind'] ? date('Y-m-d',strtotime($param['return_date'])-86400*$param['remind']) : $param['return_date'];
187
+
188
+        $fieldModel = new \app\admin\model\Field();
189
+
190
+        // 处理部门、员工、附件、多选类型字段
191
+        $arrFieldAtt = $fieldModel->getArrayField('crm_receivables_plan');
192
+        foreach ($arrFieldAtt AS $key => $value) {
193
+            $param[$value] = !empty($param[$value]) ? arrayToString($param[$value]) : '';
194
+        }
195
+
196
+        // 处理日期(date)类型
197
+        $dateField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'date');
198
+        foreach ($dateField AS $key => $value) {
199
+            $param[$value] = !empty($param[$value]) ? $param[$value] : null;
200
+        }
201
+
202
+        // 处理手写签名类型
203
+        $handwritingField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'handwriting_sign');
204
+        foreach ($handwritingField AS $key => $value) {
205
+            $param[$value] = !empty($param[$value]['file_id']) ? $param[$value]['file_id'] : '';
206
+        }
207
+
208
+        // 处理地址、定位、日期区间、明细表格类型字段
209
+        $receivablesPlanData = [];
210
+        $positionField       = $fieldModel->getFieldByFormType('crm_receivables_plan', 'position');
211
+        $locationField       = $fieldModel->getFieldByFormType('crm_receivables_plan', 'location');
212
+        $dateIntervalField   = $fieldModel->getFieldByFormType('crm_receivables_plan', 'date_interval');
213
+        $detailTableField    = $fieldModel->getFieldByFormType('crm_receivables_plan', 'detail_table');
214
+        foreach ($param AS $key => $value) {
215
+            // 处理地址类型字段数据
216
+            if (in_array($key, $positionField)) {
217
+                if (!empty($value)) {
218
+                    $receivablesPlanData[] = [
219
+                        'field'       => $key,
220
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
221
+                        'create_time' => time()
222
+                    ];
223
+                    $positionNames = array_column($value, 'name');
224
+                    $param[$key] = implode(',', $positionNames);
225
+                } else {
226
+                    $param[$key] = '';
227
+                }
228
+            }
229
+            // 处理定位类型字段数据
230
+            if (in_array($key, $locationField)) {
231
+                if (!empty($value)) {
232
+                    $receivablesPlanData[] = [
233
+                        'field'       => $key,
234
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
235
+                        'create_time' => time()
236
+                    ];
237
+                    $param[$key] = $value['address'];
238
+                } else {
239
+                    $param[$key] = '';
240
+                }
241
+            }
242
+            // 处理日期区间类型字段数据
243
+            if (in_array($key, $dateIntervalField)) {
244
+                if (!empty($value)) {
245
+                    $receivablesPlanData[] = [
246
+                        'field'       => $key,
247
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
248
+                        'create_time' => time()
249
+                    ];
250
+                    $param[$key] = implode('_', $value);
251
+                } else {
252
+                    $param[$key] = '';
253
+                }
254
+            }
255
+            // 处理明细表格类型字段数据
256
+            if (in_array($key, $detailTableField)) {
257
+                if (!empty($value)) {
258
+                    $receivablesPlanData[] = [
259
+                        'field'       => $key,
260
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
261
+                        'create_time' => time()
262
+                    ];
263
+                    $param[$key] = $key;
264
+                } else {
265
+                    $param[$key] = '';
266
+                }
267
+            }
268
+        }
269
+
181
 		if ($this->data($param)->allowField(true)->save()) {
270
 		if ($this->data($param)->allowField(true)->save()) {
182
 			$data = [];
271
 			$data = [];
183
 			$data['plan_id'] = $this->plan_id;
272
 			$data['plan_id'] = $this->plan_id;
273
+            // 添加回款计划扩展数据
274
+            array_walk($receivablesPlanData, function (&$val) use ($data) {
275
+                $val['plan_id'] = $data['plan_id'];
276
+            });
277
+            db('crm_receivables_plan_data')->insertAll($receivablesPlanData);
184
 			return $data;
278
 			return $data;
185
 		} else {
279
 		} else {
186
 			$this->error = '添加失败';
280
 			$this->error = '添加失败';
196
 	 */	
290
 	 */	
197
 	public function updateDataById($param, $plan_id = '')
291
 	public function updateDataById($param, $plan_id = '')
198
 	{
292
 	{
293
+	    $userId = $param['user_id'];
294
+	    unset($param['user_id']);
199
 		$dataInfo = $this->getDataById($plan_id);
295
 		$dataInfo = $this->getDataById($plan_id);
200
 		if (!$dataInfo) {
296
 		if (!$dataInfo) {
201
 			$this->error = '数据不存在或已删除';
297
 			$this->error = '数据不存在或已删除';
208
 			unset($param[$v]);
304
 			unset($param[$v]);
209
 		}
305
 		}
210
 		
306
 		
211
-		// 自动验证
212
-		$validate = validate($this->name);
213
-		if (!$validate->check($param)) {
214
-			$this->error = $validate->getError();
215
-			return false;
216
-		}
307
+//		// 自动验证
308
+//		$validate = validate($this->name);
309
+//		if (!$validate->check($param)) {
310
+//			$this->error = $validate->getError();
311
+//			return false;
312
+//		}
313
+        // 数据验证
314
+        $validateResult = $this->fieldDataValidate($param, 'crm_receivables_plan', $userId, $plan_id);
315
+        if (!empty($validateResult)) {
316
+            $this->error = $validateResult;
317
+            return false;
318
+        }
217
 		if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件
319
 		if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件
218
 		//提醒日期
320
 		//提醒日期
219
-		$param['remind_date'] = $param['remind'] ? date('Y-m-d',strtotime($param['return_date'])-86400*$param['remind']) : $param['return_date'];		
321
+		$param['remind_date'] = $param['remind'] ? date('Y-m-d',strtotime($param['return_date'])-86400*$param['remind']) : $param['return_date'];
322
+
323
+        $fieldModel = new \app\admin\model\Field();
324
+
325
+        // 处理部门、员工、附件、多选类型字段
326
+        $arrFieldAtt = $fieldModel->getArrayField('crm_receivables_plan');
327
+        foreach ($arrFieldAtt AS $key => $value) {
328
+            $param[$value] = !empty($param[$value]) ? arrayToString($param[$value]) : '';
329
+        }
330
+
331
+        // 处理日期(date)类型
332
+        $dateField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'date');
333
+        foreach ($dateField AS $key => $value) {
334
+            $param[$value] = !empty($param[$value]) ? $param[$value] : null;
335
+        }
336
+
337
+        // 处理手写签名类型
338
+        $handwritingField = $fieldModel->getFieldByFormType('crm_receivables_plan', 'handwriting_sign');
339
+        foreach ($handwritingField AS $key => $value) {
340
+            $param[$value] = !empty($param[$value]['file_id']) ? $param[$value]['file_id'] : '';
341
+        }
342
+
343
+
344
+        // 处理地址、定位、日期区间、明细表格类型字段
345
+        $receivablesPlanData = [];
346
+        $positionField       = $fieldModel->getFieldByFormType('crm_receivables_plan', 'position');
347
+        $locationField       = $fieldModel->getFieldByFormType('crm_receivables_plan', 'location');
348
+        $dateIntervalField   = $fieldModel->getFieldByFormType('crm_receivables_plan', 'date_interval');
349
+        $detailTableField    = $fieldModel->getFieldByFormType('crm_receivables_plan', 'detail_table');
350
+        foreach ($param AS $key => $value) {
351
+            // 处理地址类型字段数据
352
+            if (in_array($key, $positionField)) {
353
+                if (!empty($value)) {
354
+                    $receivablesPlanData[] = [
355
+                        'field'       => $key,
356
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
357
+                        'create_time' => time()
358
+                    ];
359
+                    $positionNames = array_column($value, 'name');
360
+                    $param[$key] = implode(',', $positionNames);
361
+                } else {
362
+                    $param[$key] = '';
363
+                }
364
+            }
365
+            // 处理定位类型字段数据
366
+            if (in_array($key, $locationField)) {
367
+                if (!empty($value)) {
368
+                    $receivablesPlanData[] = [
369
+                        'field'       => $key,
370
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
371
+                        'create_time' => time()
372
+                    ];
373
+                    $param[$key] = $value['address'];
374
+                } else {
375
+                    $param[$key] = '';
376
+                }
377
+            }
378
+            // 处理日期区间类型字段数据
379
+            if (in_array($key, $dateIntervalField)) {
380
+                if (!empty($value)) {
381
+                    $receivablesPlanData[] = [
382
+                        'field'       => $key,
383
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
384
+                        'create_time' => time()
385
+                    ];
386
+                    $param[$key] = implode('_', $value);
387
+                } else {
388
+                    $param[$key] = '';
389
+                }
390
+            }
391
+            // 处理明细表格类型字段数据
392
+            if (in_array($key, $detailTableField)) {
393
+                if (!empty($value)) {
394
+                    $receivablesPlanData[] = [
395
+                        'field'       => $key,
396
+                        'content'     => json_encode($value, JSON_NUMERIC_CHECK),
397
+                        'create_time' => time()
398
+                    ];
399
+                    $param[$key] = $key;
400
+                } else {
401
+                    $param[$key] = '';
402
+                }
403
+            }
404
+        }
405
+
220
 		if ($this->allowField(true)->save($param, ['plan_id' => $plan_id])) {
406
 		if ($this->allowField(true)->save($param, ['plan_id' => $plan_id])) {
221
 			$data = [];
407
 			$data = [];
222
 			$data['plan_id'] = $plan_id;
408
 			$data['plan_id'] = $plan_id;
409
+            // 添加回款计划扩展数据
410
+            db('crm_receivables_plan_data')->where('plan_id', $data['plan_id'])->delete();
411
+            array_walk($receivablesPlanData, function (&$val) use ($data) {
412
+                $val['plan_id'] = $data['plan_id'];
413
+            });
414
+            db('crm_receivables_plan_data')->insertAll($receivablesPlanData);
223
 			return $data;
415
 			return $data;
224
 		} else {
416
 		} else {
225
 			$this->error = '编辑失败';
417
 			$this->error = '编辑失败';

+ 46
- 11
application/crm/model/Setting.php Bestand weergeven

36
         if (!is_array($param['types_id'])) {
36
         if (!is_array($param['types_id'])) {
37
             $param['types_id'] = [intval($param['types_id'])];
37
             $param['types_id'] = [intval($param['types_id'])];
38
         }
38
         }
39
-        $res = teamUserId($param['types'], $param['types_id'], $param['type'], $param['user_id'], $param['is_del'], $param['owner_user_id']);
39
+        $res = teamUserId($param,$param['types'], $param['types_id'], $param['type'], $param['user_id'], $param['is_del'], $param['owner_user_id']);
40
 		if ($res == '1') {
40
 		if ($res == '1') {
41
             //同时关联其他模块(仅限客户模块)
41
             //同时关联其他模块(仅限客户模块)
42
             if (is_array($param['module']) && $param['types'] == 'crm_customer') {
42
             if (is_array($param['module']) && $param['types'] == 'crm_customer') {
49
                         case 'crm_contacts' : $module_id = 'contacts_id'; break;
49
                         case 'crm_contacts' : $module_id = 'contacts_id'; break;
50
                         case 'crm_business' : $module_id = 'business_id'; break;
50
                         case 'crm_business' : $module_id = 'business_id'; break;
51
                         case 'crm_contract' : $module_id = 'contract_id'; break;
51
                         case 'crm_contract' : $module_id = 'contract_id'; break;
52
-                    }   
52
+                        case 'crm_leads' : $module_id = 'leads_id'; break;
53
+                        case 'crm_receivables' : $module_id = 'receivables_id'; break;
54
+                    }
53
                     foreach ($moduleList as $val) {
55
                     foreach ($moduleList as $val) {
54
-                        teamUserId($v, $val[$module_id], $param['type'], $param['user_id'], $param['is_del'], $param['owner_user_id'], 0);
56
+                        teamUserId($param,$v, $val[$module_id], $param['type'], $param['user_id'], $param['is_del'], $param['owner_user_id'], 0);
55
                     }                             
57
                     }                             
56
                 }
58
                 }
57
             }
59
             }
70
      * @throws \think\Exception
72
      * @throws \think\Exception
71
      * @throws \think\exception\PDOException
73
      * @throws \think\exception\PDOException
72
      */
74
      */
73
-    public function setVisitDay($status, $day)
75
+    public function setVisitDay($status, $day,$userId)
74
     {
76
     {
75
         $status = intval($status);
77
         $status = intval($status);
76
         $day    = intval($day);
78
         $day    = intval($day);
99
             }
101
             }
100
         }
102
         }
101
         # 系统操作日志
103
         # 系统操作日志
102
-        $user=new ApiCommon();
103
-        $userInfo=$user->userInfo;
104
-        SystemActionLog($userInfo['id'], 'crm_config','customer', 1, 'update','客户回访提醒' , '', '','设置了客户回访提醒');
104
+        SystemActionLog($userId, 'crm_config','customer', 1, 'update','客户回访提醒' , '', '','设置了客户回访提醒');
105
         return true;
105
         return true;
106
     }
106
     }
107
 
107
 
124
      * @param $param
124
      * @param $param
125
      * @return bool
125
      * @return bool
126
      */
126
      */
127
-    public function setNumber($param)
127
+    public function setNumber($param,$userId)
128
     {
128
     {
129
         $apiCommon = new ApiCommon();
129
         $apiCommon = new ApiCommon();
130
 
130
 
176
 
176
 
177
             Db::commit();
177
             Db::commit();
178
             # 系统操作日志
178
             # 系统操作日志
179
-            $user=new ApiCommon();
180
-            $userInfo=$user->userInfo;
181
-            SystemActionLog($userInfo['id'], 'crm_number_sequence','customer', 1, 'update','编号规则设置' , '', '','设置了编号规则');
179
+            SystemActionLog($userId, 'crm_number_sequence','customer', 1, 'update','编号规则设置' , '', '','设置了编号规则');
182
             return true;
180
             return true;
183
         } catch (Exception $e) {
181
         } catch (Exception $e) {
184
             Db::rollback();
182
             Db::rollback();
186
             return false;
184
             return false;
187
         }
185
         }
188
     }
186
     }
187
+    
188
+    /**
189
+     * 导航列表
190
+     * @param $param
191
+     *
192
+     * @author      alvin guogaobo
193
+     * @version     1.0 版本号
194
+     * @since       2021/6/22 0022 11:39
195
+     */
196
+    public function appMenuConfig($param)
197
+        {
198
+            $data = db('app_navigation')->where('create_user_id', $param)->value('data');
199
+            $data = unserialize($data);
200
+            return $data?:[];
201
+        }
202
+    
203
+    /**
204
+     * 修改导航信息
205
+     * @param $param
206
+     * @param $userId
207
+     *
208
+     * @author      alvin guogaobo
209
+     * @version     1.0 版本号
210
+     * @since       2021/6/22 0022 14:49
211
+     */
212
+    public function setMenuConfig($param,$userId){
213
+            $data = db('app_navigation')->where('create_user_id', $userId)->value('data');
214
+            $res=[];
215
+            $res['data']=serialize($param);
216
+            if($data){
217
+                $list=db('app_navigation')->where('create_user_id', $userId)->update($res);
218
+            }else{
219
+                $res['create_user_id']=$userId;
220
+                $list=db('app_navigation')->insertGetId($res);
221
+            }
222
+            return $list;
223
+    }
189
 } 		
224
 } 		

+ 1
- 1
application/crm/traits/AutoNumberTrait.php Bestand weergeven

47
                 
47
                 
48
                 if ($currentDate[$value['reset']] != $lastDate[$value['reset']]) {
48
                 if ($currentDate[$value['reset']] != $lastDate[$value['reset']]) {
49
                     Db::name('crm_number_sequence')->where('number_sequence_id', $value['number_sequence_id'])->update([
49
                     Db::name('crm_number_sequence')->where('number_sequence_id', $value['number_sequence_id'])->update([
50
-                        'last_number' => 1
50
+                        'last_number' => !empty($value['value']) ? $value['value'] : 1
51
                     ]);
51
                     ]);
52
                 }
52
                 }
53
             }
53
             }

+ 0
- 188
application/oa/controller/Addresslist.php Bestand weergeven

90
 
90
 
91
         return resultArray(['data' => '设置关注成功!']);
91
         return resultArray(['data' => '设置关注成功!']);
92
     }
92
     }
93
-
94
-    
95
-    //通讯录列表
96
-//    public function index()
97
-//    {
98
-//		$param = $this->param;
99
-//		$where = array();
100
-//		$where['user.status'] = 1;
101
-//		if ($param['search']) {
102
-//			$where['user.realname']  = array('like', '%'.$param['search'].'%');
103
-//		}
104
-//		if ($param['type'] == 1) {
105
-//			$datalist =  Db::name('AdminUser')
106
-//				->where($where)
107
-//				->alias('user')
108
-//				->join('AdminStructure structure', 'structure.id = user.structure_id', 'LEFT')
109
-//				->field('user.id,user.realname,user.thumb_img,user.post,user.structure_id,structure.name as structure_name,user.username,user.mobile,user.sex,user.email,user.status')
110
-//				->select();
111
-//				foreach( $datalist as $k=>$v){
112
-//					$datalist[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath( $v['thumb_img'] ) : '';
113
-//				}
114
-//				$newarray = $this->groupByInitials($datalist,'realname');
115
-//				return resultArray(['data' => $newarray]);
116
-//		} else {
117
-//			$structureList = Db::name('AdminStructure')->select();
118
-//			foreach($structureList as $key=>$value){
119
-//				$where['user.structure_id'] = $value['id'];
120
-//				$userList = Db::name('AdminUser')
121
-//					->where($where)
122
-//					->alias('user')
123
-//					->field('user.id,user.realname,user.username,user.thumb_img,user.post,user.structure_id,user.mobile,user.sex,user.email')
124
-//					->order('realname asc')
125
-//					->select();
126
-//				foreach ($userList as $k=>$v){
127
-//					$userList[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath( $v['thumb_img'] ) : '';
128
-//				}
129
-//				$structureList[$key]['userList'] = $userList;
130
-//				$structureList[$key]['structure_name'] = $value['name'];
131
-//			}
132
-//			return resultArray(['data' => $structureList]);
133
-//		}
134
-//    }
135
-//
136
-//	/**
137
-//     * 二维数组根据首字母分组排序
138
-//     * @param  array  $data      二维数组
139
-//     * @param  string $targetKey 首字母的键名
140
-//     * @return array             根据首字母关联的二维数组
141
-//     */
142
-//    public function groupByInitials(array $data, $targetKey = 'name')
143
-//    {
144
-//        $data = array_map(function ($item) use ($targetKey) {
145
-//            return array_merge($item, [
146
-//                'initials' => $this->getInitials($item[$targetKey]),
147
-//            ]);
148
-//        }, $data);
149
-//        $data = $this->sortInitials($data);
150
-//        return $data;
151
-//    }
152
-//
153
-//    /**
154
-//     * 按字母排序
155
-//     * @param  array  $data
156
-//     * @return array
157
-//     */
158
-//    public function sortInitials(array $data)
159
-//    {
160
-//        $sortData = [];
161
-//        foreach ($data as $key => $value) {
162
-//            $sortData[$value['initials']][] = $value;
163
-//        }
164
-//        ksort($sortData);
165
-//        return $sortData;
166
-//    }
167
-//
168
-//    /**
169
-//     * 获取首字母
170
-//     * @param  string $str 汉字字符串
171
-//     * @return string 首字母
172
-//     */
173
-//    public function getInitials($str)
174
-//    {
175
-//        if (empty($str)) {return '';}
176
-//        $fchar = ord($str{0});
177
-//        if ($fchar >= ord('A') && $fchar <= ord('z')) {
178
-//            return strtoupper($str{0});
179
-//        }
180
-//
181
-//        $s1  = iconv('UTF-8', 'gb2312', $str);
182
-//        $s2  = iconv('gb2312', 'UTF-8', $s1);
183
-//        $s   = $s2 == $str ? $s1 : $str;
184
-//        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
185
-//        if($asc == -9300){
186
-//            return 'G';
187
-//        }
188
-//        if ($asc >= -20319 && $asc <= -20284) {
189
-//            return 'A';
190
-//        }
191
-//
192
-//        if ($asc >= -20283 && $asc <= -19776) {
193
-//            return 'B';
194
-//        }
195
-//
196
-//        if ($asc >= -19775 && $asc <= -19219) {
197
-//            return 'C';
198
-//        }
199
-//
200
-//        if ($asc >= -19218 && $asc <= -18711) {
201
-//            return 'D';
202
-//        }
203
-//
204
-//        if ($asc >= -18710 && $asc <= -18527) {
205
-//            return 'E';
206
-//        }
207
-//
208
-//        if ($asc >= -18526 && $asc <= -18240) {
209
-//            return 'F';
210
-//        }
211
-//
212
-//        if ($asc >= -18239 && $asc <= -17923) {
213
-//            return 'G';
214
-//        }
215
-//
216
-//        if ($asc >= -17922 && $asc <= -17418) {
217
-//            return 'H';
218
-//        }
219
-//
220
-//        if ($asc >= -17417 && $asc <= -16475) {
221
-//            return 'J';
222
-//        }
223
-//
224
-//        if ($asc >= -16474 && $asc <= -16213) {
225
-//            return 'K';
226
-//        }
227
-//
228
-//        if ($asc >= -16212 && $asc <= -15641) {
229
-//            return 'L';
230
-//        }
231
-//
232
-//        if ($asc >= -15640 && $asc <= -15166) {
233
-//            return 'M';
234
-//        }
235
-//
236
-//        if ($asc >= -15165 && $asc <= -14923) {
237
-//            return 'N';
238
-//        }
239
-//
240
-//        if ($asc >= -14922 && $asc <= -14915) {
241
-//            return 'O';
242
-//        }
243
-//
244
-//        if ($asc >= -14914 && $asc <= -14631) {
245
-//            return 'P';
246
-//        }
247
-//
248
-//        if ($asc >= -14630 && $asc <= -14150) {
249
-//            return 'Q';
250
-//        }
251
-//
252
-//        if ($asc >= -14149 && $asc <= -14091) {
253
-//            return 'R';
254
-//        }
255
-//
256
-//        if ($asc >= -14090 && $asc <= -13319) {
257
-//            return 'S';
258
-//        }
259
-//
260
-//        if ($asc >= -13318 && $asc <= -12839) {
261
-//            return 'T';
262
-//        }
263
-//
264
-//        if ($asc >= -12838 && $asc <= -12557) {
265
-//            return 'W';
266
-//        }
267
-//
268
-//        if ($asc >= -12556 && $asc <= -11848) {
269
-//            return 'X';
270
-//        }
271
-//
272
-//        if ($asc >= -11847 && $asc <= -11056) {
273
-//            return 'Y';
274
-//        }
275
-//
276
-//        if ($asc >= -11055 && $asc <= -10247) {
277
-//            return 'Z';
278
-//        }
279
-//        return '#';
280
-//    }
281
 }
93
 }

+ 6
- 0
application/oa/controller/Examine.php Bestand weergeven

161
         $param = $this->param;
161
         $param = $this->param;
162
         $userInfo = $this->userInfo;
162
         $userInfo = $this->userInfo;
163
         $param['create_user_id'] = $userInfo['id'];
163
         $param['create_user_id'] = $userInfo['id'];
164
+        $param['user_id'] = $userInfo['id'];
164
         $dataInfo = db('oa_examine')->where(['examine_id' => $param['id']])->find();
165
         $dataInfo = db('oa_examine')->where(['examine_id' => $param['id']])->find();
165
         if (!$dataInfo) {
166
         if (!$dataInfo) {
166
             return resultArray(['error' => '数据不存在或已删除']);
167
             return resultArray(['error' => '数据不存在或已删除']);
249
             return resultArray(['error' => $examineModel->getError()]);
250
             return resultArray(['error' => $examineModel->getError()]);
250
         }
251
         }
251
         $fileModel = new \app\admin\model\File();
252
         $fileModel = new \app\admin\model\File();
253
+        // 删除自定义字段数据
254
+        db('oa_examine_data')->where('examine_id', $param['id'])->delete();
252
         //删除关联附件
255
         //删除关联附件
253
         $fileModel->delRFileByModule('oa_examine',$param['id']);
256
         $fileModel->delRFileByModule('oa_examine',$param['id']);
254
         # 删除记录
257
         # 删除记录
445
                               ->whereOr('c.user_ids','like','%,'.$userInfo['id'].',%');
448
                               ->whereOr('c.user_ids','like','%,'.$userInfo['id'].',%');
446
                     });
449
                     });
447
                 })->order($orderField,$orderSort)->select();
450
                 })->order($orderField,$orderSort)->select();
451
+        foreach ($list AS $key => $value) {
452
+            $list[$key]['category_name'] = $value['title'];
453
+        }
448
         return resultArray(['data' => $list]);
454
         return resultArray(['data' => $list]);
449
     }
455
     }
450
 
456
 

+ 19
- 1
application/oa/controller/Log.php Bestand weergeven

38
                 'activitycount',
38
                 'activitycount',
39
                 'activitylist',
39
                 'activitylist',
40
                 'querylog',
40
                 'querylog',
41
-                'onebulletin'
41
+                'onebulletin',
42
+                'favourupdate'
42
             ]
43
             ]
43
         ];
44
         ];
44
         Hook::listen('check_auth', $action);
45
         Hook::listen('check_auth', $action);
331
         $param = $this->param;
332
         $param = $this->param;
332
         $userInfo = $this->userInfo;
333
         $userInfo = $this->userInfo;
333
         $log_id = $param['log_id'];
334
         $log_id = $param['log_id'];
335
+        $param['user_id']=$userInfo['id'];
334
         if ($log_id) {
336
         if ($log_id) {
335
             $dataInfo = db('oa_log')->where(['log_id' => $log_id])->find();
337
             $dataInfo = db('oa_log')->where(['log_id' => $log_id])->find();
336
             $adminTypes = adminGroupTypes($userInfo['id']);
338
             $adminTypes = adminGroupTypes($userInfo['id']);
494
         $data = $TaskLogic->queryLog($param);
496
         $data = $TaskLogic->queryLog($param);
495
         return resultArray(['data' => $data]);
497
         return resultArray(['data' => $data]);
496
     }
498
     }
499
+    
500
+    /**
501
+     * 点赞取消点赞
502
+     *
503
+     * @author      alvin guogaobo
504
+     * @version     1.0 版本号
505
+     * @since       2021/5/17 0017 10:00
506
+     */
507
+    public function favourUpdate(){
508
+        $param = $this->param;
509
+        $userInfo = $this->userInfo;
510
+        $param['user_id'] = $userInfo['id'];
511
+        $TaskLogic = new LogLogic();
512
+        $data = $TaskLogic->favourUpdate($param);
513
+        return resultArray(['data' => $data]);
514
+    }
497
 }
515
 }

+ 49
- 12
application/oa/logic/LogLogic.php Bestand weergeven

243
             $query->where('create_time', array('between', $between_time))
243
             $query->where('create_time', array('between', $between_time))
244
                 ->whereOr('obtain_time', array('between', $between_time));
244
                 ->whereOr('obtain_time', array('between', $between_time));
245
         };
245
         };
246
+        $userMap=function ($query) use ($user_id) {
247
+            $query->where('owner_user_id', array('eq', $user_id));
248
+        };
246
         $customerNum = Db::name('CrmCustomer')
249
         $customerNum = Db::name('CrmCustomer')
250
+            ->where($userMap)
247
             ->where($logMap)
251
             ->where($logMap)
248
             ->count();
252
             ->count();
249
         $businessNum = Db::name('CrmBusiness')
253
         $businessNum = Db::name('CrmBusiness')
304
         if ($search) {
308
         if ($search) {
305
             $map['name'] = array('like', '%' . $search . '%');
309
             $map['name'] = array('like', '%' . $search . '%');
306
         }
310
         }
307
-        $customerModel=new \app\crm\model\Customer();
308
-        $customerMap =$customerModel->getWhereByCustomer();
309
         $type = $param['log_type'];
311
         $type = $param['log_type'];
310
         switch ($type) {
312
         switch ($type) {
311
             case '1':
313
             case '1':
312
                 if ($search) $map['customer.name'] = array('like', '%' . $search . '%');
314
                 if ($search) $map['customer.name'] = array('like', '%' . $search . '%');
313
-                $map['customer.create_time'] = array('between', $between_time);
314
-                $logMap['obtain_time'] = array('between', $between_time);
315
+                $logMap=function ($query) use ($between_time) {
316
+                    $query->where('customer.create_time', array('between', $between_time))
317
+                        ->whereOr('customer.obtain_time', array('between', $between_time));
318
+                };
315
                 $activityData = Db::name('CrmCustomer')
319
                 $activityData = Db::name('CrmCustomer')
316
                     ->alias('customer')
320
                     ->alias('customer')
317
                     ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
321
                     ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
318
                     ->where($map)
322
                     ->where($map)
319
                     ->where($map1)
323
                     ->where($map1)
320
-                    ->where($customerMap)
321
-                    ->whereOr($logMap)
324
+                    ->where($logMap)
322
                     ->order('customer.customer_id desc')
325
                     ->order('customer.customer_id desc')
323
                     ->field('customer.customer_id,customer.level,customer.name,customer.deal_status,customer.create_time,user.realname as owner_user_name,customer.last_time,customer.next_time')
326
                     ->field('customer.customer_id,customer.level,customer.name,customer.deal_status,customer.create_time,user.realname as owner_user_name,customer.last_time,customer.next_time')
324
                     ->page($param['page'],$param['limit'])
327
                     ->page($param['page'],$param['limit'])
331
                     ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
334
                     ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
332
                     ->where($map)
335
                     ->where($map)
333
                     ->where($map1)
336
                     ->where($map1)
334
-                    ->where($customerMap)
337
+                    ->where($logMap)
338
+                    ->where('customer.owner_user_id' , ['neq', 0])
335
                     ->count();
339
                     ->count();
336
                 break;
340
                 break;
337
             case '2':
341
             case '2':
378
                 $activityData = Db::name('CrmContract')
382
                 $activityData = Db::name('CrmContract')
379
                     ->alias('contract')
383
                     ->alias('contract')
380
                     ->join('__ADMIN_USER__ u', 'u.id = contract.owner_user_id', 'LEFT')
384
                     ->join('__ADMIN_USER__ u', 'u.id = contract.owner_user_id', 'LEFT')
381
-                    ->join('CrmReceivables receivables','receivables.contract_id = contract.contract_id AND receivables.check_status = 2','LEFT')
382
                     ->where($map)
385
                     ->where($map)
383
                     ->where($map3)
386
                     ->where($map3)
384
                     ->order('contract.contract_id desc')
387
                     ->order('contract.contract_id desc')
385
                     ->page($param['page'],$param['limit'])
388
                     ->page($param['page'],$param['limit'])
386
-                    ->field(['contract.contract_id',
389
+                    ->field([
390
+                        'contract.contract_id',
387
                         'contract.name',
391
                         'contract.name',
388
                         'contract.create_time',
392
                         'contract.create_time',
389
                         'contract.check_status',
393
                         'contract.check_status',
390
                         'contract.order_date',
394
                         'contract.order_date',
391
                         'contract.money',
395
                         'contract.money',
392
                         'u.realname as order_user_name',
396
                         'u.realname as order_user_name',
393
-                        'ifnull(SUM(receivables.money), 0)' => 'done_money',
394
-                        '(contract.money - ifnull(SUM(receivables.money), 0))' => 'un_money'])
397
+                    ])
395
                     ->select();
398
                     ->select();
396
                 foreach ($activityData as $k => $v){
399
                 foreach ($activityData as $k => $v){
397
                     if(!empty($v['contract_id'])){
400
                     if(!empty($v['contract_id'])){
835
         } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
838
         } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
836
             $data['firstPage'] = false;
839
             $data['firstPage'] = false;
837
             $data['lastPage'] = false;
840
             $data['lastPage'] = false;
838
-        } else if ($param['page'] == 1) {
841
+        } else if ($param['page'] == 1  && (int)($param['page'] * $param['limit']) < $dataCount ) {
839
             $data['firstPage'] = true;
842
             $data['firstPage'] = true;
840
             $data['lastPage'] = false;
843
             $data['lastPage'] = false;
841
         }
844
         }
1015
         $data['list'] = $item;
1018
         $data['list'] = $item;
1016
         return $data;
1019
         return $data;
1017
     }
1020
     }
1021
+    
1022
+    /**
1023
+     * 点赞取消点赞功能
1024
+     * @param $param
1025
+     *
1026
+     * @author      alvin guogaobo
1027
+     * @version     1.0 版本号
1028
+     * @since       2021/5/17 0017 10:10
1029
+     */
1030
+    public function favourUpdate($param){
1031
+        $logModel= new Log();
1032
+        if(empty($param['favour_status'])){
1033
+            $request=db('oa_log_favour')->where(['log_id'=>$param['log_id'],'user_id'=>$param['user_id']])->update(['status'=>$param['favour_status']]);
1034
+            $status=0;
1035
+        }else{
1036
+            $res=db('oa_log_favour')->where(['log_id'=>$param['log_id'],'user_id'=>$param['user_id']])->find();
1037
+            if(!empty($res) && $res['status']==0){
1038
+                $request=db('oa_log_favour')->where(['log_id'=>$param['log_id'],'user_id'=>$param['user_id']])->update(['status'=>1]);
1039
+                $status=1;
1040
+            }elseif(!empty($res) && $res['status']==1){
1041
+                $request=db('oa_log_favour')->where(['log_id'=>$param['log_id'],'user_id'=>$param['user_id']])->update(['status'=>0]);
1042
+                $status=1;
1043
+            }else{
1044
+                $param['status']=$param['favour_status'];
1045
+                unset($param['favour_status']);
1046
+                $request=db('oa_log_favour')->insertGetId($param);
1047
+                $status=1;
1048
+            }
1049
+        }
1050
+        $data=[];
1051
+        $data['favourUser']=$logModel->favourList($param['log_id'])?:[];
1052
+        $data['favour_status']=$status;
1053
+        return $data;
1054
+    }
1018
 }
1055
 }

+ 0
- 1
application/oa/logic/UserLogic.php Bestand weergeven

311
         if ($asc >= -10247 && $asc <= -10247) {
311
         if ($asc >= -10247 && $asc <= -10247) {
312
             return 'Z';
312
             return 'Z';
313
         }
313
         }
314
-//        return '#';
315
     }
314
     }
316
 }
315
 }

+ 3
- 0
application/oa/model/Event.php Bestand weergeven

360
             }
360
             }
361
         } else {
361
         } else {
362
             $list = db('admin_oa_schedule')->select();
362
             $list = db('admin_oa_schedule')->select();
363
+            foreach ($list as $k=>$v){
364
+                $list[$k]['is_select'] = 1;
365
+            }
363
         }
366
         }
364
         $data['list'] = $list;
367
         $data['list'] = $list;
365
         return $data;
368
         return $data;

+ 45
- 24
application/oa/model/Examine.php Bestand weergeven

6
 // +----------------------------------------------------------------------
6
 // +----------------------------------------------------------------------
7
 namespace app\oa\model;
7
 namespace app\oa\model;
8
 
8
 
9
+use app\admin\traits\FieldVerificationTrait;
9
 use think\Db;
10
 use think\Db;
10
 use app\admin\model\Common;
11
 use app\admin\model\Common;
11
 use app\admin\model\Message;
12
 use app\admin\model\Message;
12
-use think\Request;
13
 use think\Validate;
13
 use think\Validate;
14
-use app\admin\model\Field;
15
 
14
 
16
 class Examine extends Common
15
 class Examine extends Common
17
 {
16
 {
17
+    use FieldVerificationTrait;
18
+
18
     /**
19
     /**
19
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
20
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
20
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
21
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
284
             $this->error = '参数错误';
285
             $this->error = '参数错误';
285
             return false;
286
             return false;
286
         }
287
         }
287
-        // 自动验证
288
-        $validateArr = $fieldModel->validateField($this->name, $param['category_id']); //获取自定义字段验证规则
289
-        $validate = new Validate($validateArr['rule'], $validateArr['message']);
290
-        $result = $validate->check($param);
291
-        if (!$result) {
292
-            $this->error = $validate->getError();
288
+//        // 自动验证
289
+//        $validateArr = $fieldModel->validateField($this->name, $param['category_id']); //获取自定义字段验证规则
290
+//        $validate = new Validate($validateArr['rule'], $validateArr['message']);
291
+//        $result = $validate->check($param);
292
+//        if (!$result) {
293
+//            $this->error = $validate->getError();
294
+//            return false;
295
+//        }
296
+
297
+        // 数据验证
298
+        $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id'], 0, $param['category_id']);
299
+        if (!empty($validateResult)) {
300
+            $this->error = $validateResult;
293
             return false;
301
             return false;
294
         }
302
         }
295
         
303
         
297
         
305
         
298
         $fileArr = $param['file_id']; //接收表单附件
306
         $fileArr = $param['file_id']; //接收表单附件
299
         unset($param['file_id']);
307
         unset($param['file_id']);
300
-        $param['start_time'] = $param['start_time'] ? strtotime($param['start_time']) : 0;
301
-        $param['end_time'] = $param['end_time'] ? strtotime($param['end_time']) : 0;
308
+        $param['start_time'] = $param['start_time'] ? : 0;
309
+        $param['end_time'] = $param['end_time'] ? : 0;
302
         if ($this->data($param)->allowField(true)->save()) {
310
         if ($this->data($param)->allowField(true)->save()) {
303
             //处理自定义字段数据
311
             //处理自定义字段数据
304
             $resData = $examineDataModel->createData($param, $this->examine_id);
312
             $resData = $examineDataModel->createData($param, $this->examine_id);
394
         $examineCategoryModel = new \app\oa\model\ExamineCategory();
402
         $examineCategoryModel = new \app\oa\model\ExamineCategory();
395
         $examineDataModel = new \app\oa\model\ExamineData();
403
         $examineDataModel = new \app\oa\model\ExamineData();
396
         $create_user_id = $param['create_user_id'];
404
         $create_user_id = $param['create_user_id'];
405
+        $userId = $param['user_id'];
397
         unset($param['id']);
406
         unset($param['id']);
407
+        unset($param['user_id']);
398
         $dataInfo = db('oa_examine')->where(['examine_id' => $examine_id])->find();
408
         $dataInfo = db('oa_examine')->where(['examine_id' => $examine_id])->find();
399
         if (!$dataInfo) {
409
         if (!$dataInfo) {
400
             $this->error = '数据不存在或已删除';
410
             $this->error = '数据不存在或已删除';
409
         $categoryInfo = $examineCategoryModel->getDataById($dataInfo['category_id']);
419
         $categoryInfo = $examineCategoryModel->getDataById($dataInfo['category_id']);
410
         
420
         
411
         //验证
421
         //验证
412
-        $fieldModel = new \app\admin\model\Field();
413
-        $validateArr = $fieldModel->validateField($this->name, $dataInfo['category_id']); //获取自定义字段验证规则
414
-        $validate = new Validate($validateArr['rule'], $validateArr['message']);
415
-        $result = $validate->check($param);
416
-        if (!$result) {
417
-            $this->error = $validate->getError();
422
+//        $fieldModel = new \app\admin\model\Field();
423
+//        $validateArr = $fieldModel->validateField($this->name, $dataInfo['category_id']); //获取自定义字段验证规则
424
+//        $validate = new Validate($validateArr['rule'], $validateArr['message']);
425
+//        $result = $validate->check($param);
426
+//        if (!$result) {
427
+//            $this->error = $validate->getError();
428
+//            return false;
429
+//        }
430
+        // 数据验证
431
+        $validateResult = $this->fieldDataValidate($param, $this->name, $userId, $examine_id, $param['category_id']);
432
+        if (!empty($validateResult)) {
433
+            $this->error = $validateResult;
418
             return false;
434
             return false;
419
         }
435
         }
420
         
436
         
524
     public function getDataById($id = '')
540
     public function getDataById($id = '')
525
     {
541
     {
526
         $examineData = new \app\oa\model\ExamineData();
542
         $examineData = new \app\oa\model\ExamineData();
527
-        $fieldModel = new \app\admin\model\Field();
528
         $fileModel = new \app\admin\model\File();
543
         $fileModel = new \app\admin\model\File();
529
         $userModel = new \app\admin\model\User();
544
         $userModel = new \app\admin\model\User();
530
         $recordModel = new \app\admin\model\Record();
545
         $recordModel = new \app\admin\model\Record();
549
         $dataInfo['create_time'] = $dataInfo['create_time'] ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;;
564
         $dataInfo['create_time'] = $dataInfo['create_time'] ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;;
550
         $realname=$userModel->getUserById($dataInfo['create_user_id']);
565
         $realname=$userModel->getUserById($dataInfo['create_user_id']);
551
         $dataInfo['value'] =  !empty($realname)?$realname['realname']: '';
566
         $dataInfo['value'] =  !empty($realname)?$realname['realname']: '';
552
-        //表格数据处理
553
-        // $fieldList = $fieldModel->getFieldByFormType('oa_examine', 'form');
554
-        // foreach ($fieldList as $k=>$v) {
555
-        // 	$dataInfo[$v] = $fieldModel->getFormValueByField($v, $dataInfo[$v]);
556
-        // }
567
+
568
+        // 处理自定义字段格式
569
+        $fieldWhere = [
570
+            'types' => 'oa_examine',
571
+            'types_id' => $dataInfo['category_id'],
572
+            'form_type' => ['in', ['position', 'location', 'handwriting_sign', 'date_interval', 'detail_table']]
573
+        ];
574
+        $fieldList = db('admin_field')->field(['field', 'form_type'])->where($fieldWhere)->select();
575
+        foreach ($fieldList AS $key => $value) {
576
+            if (!empty($dataInfo[$value['field']])) {
577
+                $dataInfo[$value['field']] = json_decode($dataInfo[$value['field']], true);
578
+            }
579
+        }
557
         
580
         
558
         //关联业务
581
         //关联业务
559
-        $relationArr = [];
560
         $relationArr = $recordModel->getListByRelationId('examine', $id);
582
         $relationArr = $recordModel->getListByRelationId('examine', $id);
561
         $dataInfo['businessList'] = $relationArr['businessList'];
583
         $dataInfo['businessList'] = $relationArr['businessList'];
562
         $dataInfo['contactsList'] = $relationArr['contactsList'];
584
         $dataInfo['contactsList'] = $relationArr['contactsList'];
604
         $where = [];
626
         $where = [];
605
         $where['module'] = 'oa_examine';
627
         $where['module'] = 'oa_examine';
606
         $where['module_id'] = $id;
628
         $where['module_id'] = $id;
607
-        $newFileList = [];
608
         $newFileList = $fileModel->getDataList($where, 'all');
629
         $newFileList = $fileModel->getDataList($where, 'all');
609
         foreach ($newFileList['list'] as $val) {
630
         foreach ($newFileList['list'] as $val) {
610
             if ($val['types'] == 'file') {
631
             if ($val['types'] == 'file') {

+ 1
- 3
application/oa/model/ExamineCategory.php Bestand weergeven

249
             $data['delete_user_id'] = $user_id;
249
             $data['delete_user_id'] = $user_id;
250
             $this->allowField(true)->save($data, ['category_id' => $id]);
250
             $this->allowField(true)->save($data, ['category_id' => $id]);
251
             # 系统操作记录
251
             # 系统操作记录
252
-            $user=new ApiCommon();
253
-            $userInfo=$user->userInfo;
254
-            SystemActionLog($userInfo['id'],'oa_examine', 'approval', $id, 'delete',$info['title'] , '', '','删除了:'.$info['title']);
252
+            SystemActionLog($user_id,'oa_examine', 'approval', $id, 'delete',$info['title'] , '', '','删除了:'.$info['title']);
255
             $this->commit();
253
             $this->commit();
256
             return true;
254
             return true;
257
         } catch (\Exception $e) {
255
         } catch (\Exception $e) {

+ 19
- 10
application/oa/model/ExamineData.php Bestand weergeven

37
 		$unField = ['content','remark','start_time','end_time','duration','cause','money','category_id','check_user_id','check_status','flow_id','order_id','create_user_id'];
37
 		$unField = ['content','remark','start_time','end_time','duration','cause','money','category_id','check_user_id','check_status','flow_id','order_id','create_user_id'];
38
 		$data = [];
38
 		$data = [];
39
 		foreach ($fieldList as $k=>$v) {
39
 		foreach ($fieldList as $k=>$v) {
40
-			$field_arr = [];
41
-			if (is_array($param[$v['field']])) {
42
-				foreach ($param[$v['field']] as $key=>$val) {
43
-					$field_arr[] = str_replace(',', ',', $val);
44
-				}
45
-				$param[$v['field']] = $field_arr ? ','.implode(',',$field_arr).',' : '';
46
-			}
47
 			if (!in_array($v['field'], $unField)) {
40
 			if (!in_array($v['field'], $unField)) {
48
-				$data[$k]['examine_id'] = $examine_id;
49
-				$data[$k]['field'] = $v['field'];
50
-				$data[$k]['value'] = $param[$v['field']];
41
+                $data[$k]['examine_id'] = $examine_id;
42
+                $data[$k]['field'] = $v['field'];
43
+                // 处理数据格式是对象的字段:position 地址、location 定位、date_interval 日期区间、detail_table 明细表格
44
+                if (in_array($v['form_type'], ['position', 'location', 'date_interval', 'detail_table'])) {
45
+                    $data[$k]['value'] = !empty($param[$v['field']]) ? json_encode($param[$v['field']], JSON_NUMERIC_CHECK) : '';
46
+                } else {
47
+                    $data[$k]['value'] = !empty($param[$v['field']]) ? $param[$v['field']] : '';
48
+                }
49
+
50
+                // 处理手写签名
51
+                if ($v['form_type'] == 'handwriting_sign') {
52
+                    $data[$k]['value'] = !empty($param[$v['field']]['file_id']) ? $param[$v['field']]['file_id'] : '';
53
+                }
54
+                // 处理附件
55
+                if ($v['form_type'] == 'file') {
56
+                    $data[$k]['value'] = !empty($param[$v['field']]) ? arrayToString($param[$v['field']]) : '';
57
+                }
51
 			}
58
 			}
52
 		}
59
 		}
53
 		if ($data) {
60
 		if ($data) {
61
+		    db('oa_examine_data')->where('examine_id', $examine_id)->delete();
62
+//		    print_r($data);exit;
54
 			$resData = db('oa_examine_data')->insertAll($data);
63
 			$resData = db('oa_examine_data')->insertAll($data);
55
 			if (!$resData) {
64
 			if (!$resData) {
56
 				$this->error = '添加失败';
65
 				$this->error = '添加失败';

+ 33
- 18
application/oa/model/Log.php Bestand weergeven

40
         $fileModel = new \app\admin\model\File();
40
         $fileModel = new \app\admin\model\File();
41
         $commonModel = new \app\admin\model\Comment();
41
         $commonModel = new \app\admin\model\Comment();
42
         $recordModel = new \app\admin\model\Record();
42
         $recordModel = new \app\admin\model\Record();
43
-        
44
         $user_id = $request['read_user_id'];
43
         $user_id = $request['read_user_id'];
45
         $by = $request['by'] ?: '';
44
         $by = $request['by'] ?: '';
46
-        
47
         $map = [];
45
         $map = [];
48
         $search = $request['search'];
46
         $search = $request['search'];
49
         if (isset($request['search']) && $request['search']) {
47
         if (isset($request['search']) && $request['search']) {
130
             $list[$k]['imgList'] = $imgList ?: [];
128
             $list[$k]['imgList'] = $imgList ?: [];
131
             $list[$k]['sendUserList'] = $userModel->getDataByStr($v['send_user_ids']) ?: [];
129
             $list[$k]['sendUserList'] = $userModel->getDataByStr($v['send_user_ids']) ?: [];
132
             $list[$k]['sendStructList'] = $structureModel->getDataByStr($v['send_structure_ids']) ?: [];
130
             $list[$k]['sendStructList'] = $structureModel->getDataByStr($v['send_structure_ids']) ?: [];
131
+            $favour=$this->favourList($v['log_id']);
132
+            $list[$k]['favourUser'] = $favour ?: [];
133
+            $list[$k]['favour_status'] =!empty($favour)?1:0 ;
133
             $param['type_id'] = $v['log_id'];
134
             $param['type_id'] = $v['log_id'];
134
             $param['type'] = 'oa_log';
135
             $param['type'] = 'oa_log';
135
             $list[$k]['replyList'] = $commonModel->read($param);
136
             $list[$k]['replyList'] = $commonModel->read($param);
174
         $data = [];
175
         $data = [];
175
         $data['page']['list'] = $list;
176
         $data['page']['list'] = $list;
176
         $data['page']['dataCount'] = $dataCount ?: 0;
177
         $data['page']['dataCount'] = $dataCount ?: 0;
177
-        if ($request['page'] != 1 && (int)($request['page'] * $request['limit']) >= (int)$dataCount) {
178
-            $data['page']['firstPage'] = false;
179
-            $data['page']['lastPage'] = true;
180
-        } else if ($request['page'] != 1 && (int)($request['page'] * $request['limit']) < (int)$dataCount) {
181
-            $data['page']['firstPage'] = false;
182
-            $data['page']['lastPage'] = false;
183
-        } else if ($request['page'] == 1) {
184
-            $data['page']['firstPage'] = true;
185
-            $data['page']['lastPage'] = false;
178
+ 
179
+        if ($param['page'] != 1 && ($param['page'] * $param['limit']) >= $dataCount) {
180
+            $data['firstPage'] = false;
181
+            $data['lastPage'] = true;
182
+        } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
183
+            $data['firstPage'] = false;
184
+            $data['lastPage'] = false;
185
+        } else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
186
+            $data['firstPage'] = true;
187
+            $data['lastPage'] = true;
186
         }
188
         }
187
-        
188
         return $data;
189
         return $data;
189
     }
190
     }
190
     
191
     
375
                     'contract_ids' => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : ''
376
                     'contract_ids' => !empty($rdata['contract_ids']) ? $rdata['contract_ids'] : ''
376
                 ]);
377
                 ]);
377
             }
378
             }
378
-            $user=new ApiCommon();
379
-            $userInfo=$user->userInfo;
380
-            RecordActionLog($userInfo['id'], 'oa_log', 'update',$dataInfo['title'], '','','修改了日志:'.$dataInfo['title']);
379
+            RecordActionLog($param['user_id'], 'oa_log', 'update',$dataInfo['title'], '','','修改了日志:'.$dataInfo['title']);
381
             return $data;
380
             return $data;
382
         } else {
381
         } else {
383
             $this->error = '编辑失败';
382
             $this->error = '编辑失败';
453
      */
452
      */
454
     public function delDataById($param)
453
     public function delDataById($param)
455
     {
454
     {
456
-        $user=new ApiCommon();
457
-        $userInfo=$user->userInfo;
458
         $map['log_id'] = $param['log_id'];
455
         $map['log_id'] = $param['log_id'];
459
         $dataInfo = $this->get($map['log_id']);
456
         $dataInfo = $this->get($map['log_id']);
460
         if (!$dataInfo) {
457
         if (!$dataInfo) {
469
             $fileModel->delRFileByModule('oa_log', $param['log_id']);
466
             $fileModel->delRFileByModule('oa_log', $param['log_id']);
470
             //删除相关评论
467
             //删除相关评论
471
             $commentModel->delDataById(['type' => 'oa_log', 'type_id' => $param['log_id']]);
468
             $commentModel->delDataById(['type' => 'oa_log', 'type_id' => $param['log_id']]);
472
-            RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $dataInfo['title'], '', '', '删除了日志:' . $dataInfo['title']);
469
+            RecordActionLog($param['user_id'], 'oa_log', 'delete', $dataInfo['title'], '', '', '删除了日志:' . $dataInfo['title']);
473
             # 删除活动记录
470
             # 删除活动记录
474
             Db::name('crm_activity')->where(['activity_type' => 8, 'activity_type_id' => $param['log_id']])->delete();
471
             Db::name('crm_activity')->where(['activity_type' => 8, 'activity_type_id' => $param['log_id']])->delete();
475
             return true;
472
             return true;
478
             return false;
475
             return false;
479
         }
476
         }
480
     }
477
     }
478
+    
479
+    /**
480
+     * 点赞数据
481
+     * @param string $log_id 日志id
482
+     *
483
+     * @author      alvin guogaobo
484
+     * @version     1.0 版本号
485
+     * @since       2021/5/18 0018 09:29
486
+     */
487
+    public function favourList($log_id=''){
488
+            $list= db('oa_log_favour')
489
+                ->alias('favour')
490
+                ->join('__ADMIN_USER__ user','user.id=favour.user_id','LEFT')
491
+                ->where(['favour.log_id'=>$log_id,'favour.status'=>1])
492
+                ->field('user.id,user.realname,user.img,favour.status')
493
+                ->select();
494
+        return $list?:[];
495
+    }
481
 }
496
 }

+ 13
- 11
application/work/controller/Work.php Bestand weergeven

158
 
158
 
159
         $workInfo['auth'] = $this->getRuleList($this->param['work_id'], $userId, $groupId);
159
         $workInfo['auth'] = $this->getRuleList($this->param['work_id'], $userId, $groupId);
160
         # 下次升级
160
         # 下次升级
161
-//        $userInfo=$this->userInfo;
162
-//        $rule=db('work_user')
163
-//            ->where('user_id',$userInfo['id'])
164
-//            ->value('group_id');
165
-//        $list=db('admin_rule')->where('name','manageTaskOwnerUser')->value('id');
166
-//        $groupList = db('admin_group')->where(['pid' => 5, 'types' => 7, 'type' => 0,'id'=>$rule])->order('system desc')->value('rules');
167
-//        if(!in_array($list,stringToArray($groupList))){
168
-//            $workInfo['is_open']=1;
169
-//        }
161
+        $userInfo=$this->userInfo;
162
+        $rule=db('work_user')
163
+            ->where('user_id',$userInfo['id'])
164
+            ->value('group_id');
165
+        $list=db('admin_rule')->where('name','manageTaskOwnerUser')->value('id');
166
+        $groupList = db('admin_group')->where(['pid' => 5, 'types' => 7, 'type' => 0,'id'=>$rule])->order('system desc')->value('rules');
167
+        if(!in_array($list,stringToArray($groupList))){
168
+            $workInfo['is_open']=1;
169
+        }
170
+       
170
         return resultArray(['data' => $workInfo]);
171
         return resultArray(['data' => $workInfo]);
171
     }
172
     }
172
 
173
 
288
     {   
289
     {   
289
         $param = $this->param;
290
         $param = $this->param;
290
         $userInfo = $this->userInfo;
291
         $userInfo = $this->userInfo;
292
+        $userId=$userInfo['id'];
291
         if (!$param['work_id'] || !$param['owner_user_id']) {
293
         if (!$param['work_id'] || !$param['owner_user_id']) {
292
             return resultArray(['error'=>'参数错误']);
294
             return resultArray(['error'=>'参数错误']);
293
         }
295
         }
301
 //            header('Content-Type:application/json; charset=utf-8');
303
 //            header('Content-Type:application/json; charset=utf-8');
302
 //            exit(json_encode(['code'=>102,'error'=>'无权操作']));
304
 //            exit(json_encode(['code'=>102,'error'=>'无权操作']));
303
 //        }
305
 //        }
304
-        $res = $workModel->delOwner($param);
306
+        $res = $workModel->delOwner($param,$userId);
305
         if ($res) {
307
         if ($res) {
306
             
308
             
307
             return resultArray(['data'=>'操作成功']);
309
             return resultArray(['data'=>'操作成功']);
381
 //            header('Content-Type:application/json; charset=utf-8');
383
 //            header('Content-Type:application/json; charset=utf-8');
382
 //            exit(json_encode(['code'=>102,'error'=>'无权操作']));
384
 //            exit(json_encode(['code'=>102,'error'=>'无权操作']));
383
 //        }
385
 //        }
384
-        $ret = $workModel->arRecover($param['work_id']);
386
+        $ret = $workModel->arRecover($param['work_id'],$userInfo['id']);
385
         if ($ret) {
387
         if ($ret) {
386
             return resultArray(['data'=>'操作成功']);
388
             return resultArray(['data'=>'操作成功']);
387
         } else {
389
         } else {

+ 10
- 23
application/work/model/Task.php Bestand weergeven

330
             ->select();
330
             ->select();
331
         $complete = 0;
331
         $complete = 0;
332
         foreach ($subTaskList as $key => $value) {
332
         foreach ($subTaskList as $key => $value) {
333
+            $subTaskList[$key]['main_user'] = [
334
+                'id' => $value['main_user_id'],
335
+                'img' => $value['thumb_img'],
336
+                'realname' => $value['realname']
337
+            ];
333
             $subTaskList[$key]['thumb_img'] = $value['thumb_img'] ? getFullPath($value['thumb_img']) : '';
338
             $subTaskList[$key]['thumb_img'] = $value['thumb_img'] ? getFullPath($value['thumb_img']) : '';
334
             $subTaskList[$key]['stop_time'] = !empty($value['stop_time']) ? date('Y-m-d', $value['stop_time']) : null;
339
             $subTaskList[$key]['stop_time'] = !empty($value['stop_time']) ? date('Y-m-d', $value['stop_time']) : null;
335
             if ($value['status'] == 5) ++$complete;
340
             if ($value['status'] == 5) ++$complete;
442
                 $datalog['task_id'] = $task_id;
447
                 $datalog['task_id'] = $task_id;
443
                 $datalog['work_id'] = $param['work_id'] ?: '';
448
                 $datalog['work_id'] = $param['work_id'] ?: '';
444
                 $ret = $taskLog->newTaskLog($datalog);
449
                 $ret = $taskLog->newTaskLog($datalog);
445
-                //操作日志
446
-//                actionLog($task_id, '', '', '新建了任务');
447
                 //抄送站内信
450
                 //抄送站内信
448
                 (new Message())->send(
451
                 (new Message())->send(
449
                     Message::TASK_ALLOCATION,
452
                     Message::TASK_ALLOCATION,
480
                 }
483
                 }
481
                 db('work_task_file')->insertAll($fileData);
484
                 db('work_task_file')->insertAll($fileData);
482
             }
485
             }
483
-            $user=new ApiCommon();
484
-            $userInfo=$user->userInfo;
485
             # 添加子任务
486
             # 添加子任务
486
             if (!empty($subtask)) {
487
             if (!empty($subtask)) {
487
                 $subtaskData = [];
488
                 $subtaskData = [];
503
                 }
504
                 }
504
                 Db::name('task')->insertAll($subtaskData);
505
                 Db::name('task')->insertAll($subtaskData);
505
                 foreach ($subtaskData as $v){
506
                 foreach ($subtaskData as $v){
506
-                    RecordActionLog($userInfo['id'],'work_task','save',$param['name'],'','','新增了子任务'.$v['name']);
507
+                    RecordActionLog($param['create_user_id'],'work_task','save',$param['name'],'','','新增了子任务'.$v['name']);
507
                 }
508
                 }
508
             }
509
             }
509
-            if(!empty($param['pid'])){
510
-                $dataInfo=Db::name('task')->where('task_id',$param['pid'])->find();
511
-                RecordActionLog($userInfo['id'],'work_task','save',$dataInfo['name'],'','','新增了子任务'.$param['name']);
512
-            }else{
513
-                RecordActionLog($userInfo['id'],'work_task','save',$param['name'],'','','新增任务'.$param['name']);
514
-            }
510
+            RecordActionLog($param['create_user_id'],'work_task','save',$param['name'],'','','新增任务'.$param['name']);
515
             return $task_id;
511
             return $task_id;
516
         } else {
512
         } else {
517
             $this->error = '添加失败';
513
             $this->error = '添加失败';
701
             if (!$param['pid']) {
697
             if (!$param['pid']) {
702
                 $LogModel = new LogModel();
698
                 $LogModel = new LogModel();
703
                 $taskInfo = $LogModel->taskLogAdd($data);
699
                 $taskInfo = $LogModel->taskLogAdd($data);
704
-//                actionLog($param['task_id'], $param['owner_user_id'], $param['structure_ids'], '修改了任务');
705
-                $user=new ApiCommon();
706
-                $userInfo=$user->userInfo;
707
                 if(empty($name)){
700
                 if(empty($name)){
708
                     if(!empty($param['description'])){
701
                     if(!empty($param['description'])){
709
                         $name='描述';
702
                         $name='描述';
710
                     }
703
                     }
711
                 }
704
                 }
712
                 $count_name=empty($count_name)?$target_name:$count_name;
705
                 $count_name=empty($count_name)?$target_name:$count_name;
713
-                RecordActionLog($userInfo['id'], 'work_task', 'update',$target_name, '','','修改任务'.$name.':'.$count_name);
706
+                RecordActionLog($createUserId, 'work_task', 'update',$target_name, '','','修改任务'.$name.':'.$count_name);
714
                 $resRelation = Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->find();
707
                 $resRelation = Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->find();
715
                 if ($resRelation) {
708
                 if ($resRelation) {
716
                     Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->update($rdata); //更新关联关系
709
                     Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->update($rdata); //更新关联关系
847
         $dataInfo = json_decode(json_encode($dataInfo), true);
840
         $dataInfo = json_decode(json_encode($dataInfo), true);
848
         $flag = $this->where(['task_id' => $param['task_id']])->update($data);
841
         $flag = $this->where(['task_id' => $param['task_id']])->update($data);
849
         if ($flag) {
842
         if ($flag) {
850
-            //添加归档日志
851
-//            actionLog($param['task_id'], '', '', '归档了任务');
852
-            $user=new ApiCommon();
853
-            $userInfo=$user->userInfo;
854
-            RecordActionLog($userInfo['id'], 'work_task', 'archiveData',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
843
+            RecordActionLog($param['create_user_id'], 'work_task', 'archiveData',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
855
             return true;
844
             return true;
856
         } else {
845
         } else {
857
             $this->error = '归档失败';
846
             $this->error = '归档失败';
872
         $flag = $this->where(['task_id' => $param['task_id']])->setField('is_archive', 0);
861
         $flag = $this->where(['task_id' => $param['task_id']])->setField('is_archive', 0);
873
         if ($flag) {
862
         if ($flag) {
874
             //添加日志
863
             //添加日志
875
-            $user=new ApiCommon();
876
-            $userInfo=$user->userInfo;
877
-            RecordActionLog($userInfo['id'], 'work_task', 'recover',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
864
+            RecordActionLog($param['create_user_id'], 'work_task', 'recover',$dataInfo['name'], '','','归档了任务:'.$dataInfo['name']);
878
             return true;
865
             return true;
879
         } else {
866
         } else {
880
             $this->error = '操作失败';
867
             $this->error = '操作失败';

+ 20
- 22
application/work/model/Work.php Bestand weergeven

76
 			$ownerData['work_id']        = $workId;
76
 			$ownerData['work_id']        = $workId;
77
 			$ownerData['create_user_id'] = $createUserId;
77
 			$ownerData['create_user_id'] = $createUserId;
78
 			$ownerData['owner_user_id']  = $ownerUserId;
78
 			$ownerData['owner_user_id']  = $ownerUserId;
79
-			$ownerData['group_id']       = !empty($param['group_id']) ? $param['group_id'] : 0;
79
+           $group= Db::name('admin_group')->field(['id', 'title', 'rules', 'remark', 'system'])->where(['pid' => 5, 'types' => 7, 'status' => 1])->order('id','asc')->select();
80
+			$ownerData['group_id']       = !empty($param['group_id']) ? $param['group_id'] : $group[0]['id'];
80
             # 创建项目下的相关成员
81
             # 创建项目下的相关成员
81
 			$this->addOwner($ownerData);
82
 			$this->addOwner($ownerData);
82
 
83
 
173
 			$datalog['work_id'] = $param['work_id'];
174
 			$datalog['work_id'] = $param['work_id'];
174
 			$datalog['user_id'] = $userId;
175
 			$datalog['user_id'] = $userId;
175
 			$ret = $logmodel->workLogAdd($datalog);
176
 			$ret = $logmodel->workLogAdd($datalog);
176
-            $user=new ApiCommon();
177
-            $userInfo=$user->userInfo;
178
-            RecordActionLog($userInfo['id'], 'work', 'update',$param['name'], '','','编辑了项目:'.$param['name']);
177
+            RecordActionLog($userId, 'work', 'update',$param['name'], '','','编辑了项目:'.$param['name']);
179
             return true;
178
             return true;
180
 		} else {
179
 		} else {
181
 			$this->error = '重命名失败';
180
 			$this->error = '重命名失败';
227
 			$data['status'] = 3;
226
 			$data['status'] = 3;
228
 			$data['archive_time'] = time();
227
 			$data['archive_time'] = time();
229
 			Db::name('task')->where($map)->update($data);
228
 			Db::name('task')->where($map)->update($data);
230
-            $user=new ApiCommon();
231
-            $userInfo=$user->userInfo;
232
-            RecordActionLog($userInfo['id'], 'work', 'archiveData',$dataInfo['name'], '','','归档了项目:'.$dataInfo['name']);
229
+            RecordActionLog($param['create_user_id'], 'work', 'archiveData',$dataInfo['name'], '','','归档了项目:'.$dataInfo['name']);
233
             return true;
230
             return true;
234
 		} else {
231
 		} else {
235
 			$this->error = '归档失败';
232
 			$this->error = '归档失败';
268
      * @param
265
      * @param
269
      * @return
266
      * @return
270
      */	
267
      */	
271
-	public function arRecover($work_id='')
268
+	public function arRecover($work_id='',$userId)
272
 	{
269
 	{
273
 		if (!$work_id) {
270
 		if (!$work_id) {
274
 			$this->error = '参数错误';
271
 			$this->error = '参数错误';
281
 		$this->where($map)->setField('status',1);
278
 		$this->where($map)->setField('status',1);
282
 		$map['status'] = 3;
279
 		$map['status'] = 3;
283
 		Db::name('Task')->where($map)->setField('status',1);
280
 		Db::name('Task')->where($map)->setField('status',1);
284
-        $user=new ApiCommon();
285
-        $userInfo=$user->userInfo;
286
-        RecordActionLog($userInfo['id'], 'work', 'recover',$dataInfo['name'], '','','归档恢复项目:'.$dataInfo['name']);
281
+        RecordActionLog($userId, 'work', 'recover',$dataInfo['name'], '','','归档恢复项目:'.$dataInfo['name']);
287
         
282
         
288
         return true;
283
         return true;
289
 	}
284
 	}
301
 			$this->error = '项目创建人不可以退出';
296
 			$this->error = '项目创建人不可以退出';
302
 			return false;
297
 			return false;
303
 		}
298
 		}
304
-		$user=new ApiCommon();
305
-		$userInfo=$user->userInfo;
306
 		//从项目成员中移除
299
 		//从项目成员中移除
307
 		db('work_user')->where(['work_id' => $work_id,'user_id' => $user_id])->delete();
300
 		db('work_user')->where(['work_id' => $work_id,'user_id' => $user_id])->delete();
308
 		$str = ','.$user_id.',';
301
 		$str = ','.$user_id.',';
317
 				$new_own_user_id = str_replace($str,',',$value['owner_user_id']);
310
 				$new_own_user_id = str_replace($str,',',$value['owner_user_id']);
318
 				$data['owner_user_id'] = $new_own_user_id;
311
 				$data['owner_user_id'] = $new_own_user_id;
319
 			}
312
 			}
320
-			if ($value['main_user_id'] == $param['create_user_id']) {
313
+			if ($value['main_user_id'] == $workInfo['create_user_id']) {
321
 				$data['main_user_id'] = '';
314
 				$data['main_user_id'] = '';
322
 			}
315
 			}
323
 			if ($data) Db::name('Task')->where(['task_id' => $value['task_id']])->update($data);
316
 			if ($data) Db::name('Task')->where(['task_id' => $value['task_id']])->update($data);
324
-            RecordActionLog($userInfo['id'], 'work_task', 'recover',$value['name'], '','','退出了项目:'.$value['name']);
317
+            RecordActionLog($user_id, 'work_task', 'recover',$value['name'], '','','退出了项目:'.$value['name']);
325
         }
318
         }
326
-        RecordActionLog($userInfo['id'], 'work', 'update',$workInfo['name'], '','','退出了项目:'.$workInfo['name']);
319
+        RecordActionLog($user_id, 'work', 'update',$workInfo['name'], '','','退出了项目:'.$workInfo['name']);
327
         return true;
320
         return true;
328
 	}
321
 	}
329
 
322
 
356
 			$data['types'] = 0;
349
 			$data['types'] = 0;
357
 			if ($v == $create_user_id) {
350
 			if ($v == $create_user_id) {
358
 				$data['types'] = 1;
351
 				$data['types'] = 1;
359
-				$group_id = 1;
352
+				$group_id = $param['group_id'];
360
 			} else {
353
 			} else {
361
 				# 默认角色
354
 				# 默认角色
362
 				$group_id = !empty($param['group_id']) ? $param['group_id'] : db('admin_group')->where(['pid' => 5, 'system' => 1])->order('id asc')->value('id');
355
 				$group_id = !empty($param['group_id']) ? $param['group_id'] : db('admin_group')->where(['pid' => 5, 'system' => 1])->order('id asc')->value('id');
380
      * @param
373
      * @param
381
      * @return
374
      * @return
382
      */	
375
      */	
383
-	public function delOwner($param)
376
+	public function delOwner($param,$userId)
384
 	{
377
 	{
385
 		$work_id = $param['work_id'];
378
 		$work_id = $param['work_id'];
386
 		$workUserInfo = db('work_user')->where(['work_id' => $work_id,'user_id' => $param['owner_user_id']])->find();
379
 		$workUserInfo = db('work_user')->where(['work_id' => $work_id,'user_id' => $param['owner_user_id']])->find();
403
 			$this->error = '删除失败,请重试!';
396
 			$this->error = '删除失败,请重试!';
404
 			return false;
397
 			return false;
405
 		}
398
 		}
406
-        $user=new ApiCommon();
407
-        $userInfo=$user->userInfo;
408
         $user= new \app\admin\model\User();
399
         $user= new \app\admin\model\User();
409
         $user_info=$user->getUserById($param['owner_user_id']);
400
         $user_info=$user->getUserById($param['owner_user_id']);
410
-        RecordActionLog($userInfo['id'], 'work', 'save',$workInfo['name'], '','','删除了项目成员:'.$user_info['realname']);
401
+        RecordActionLog($userId, 'work', 'save',$workInfo['name'], '','','删除了项目成员:'.$user_info['realname']);
411
         return true;
402
         return true;
412
 	}
403
 	}
413
 	
404
 	
423
 			$workInfo = $this->get($param['work_id']);
414
 			$workInfo = $this->get($param['work_id']);
424
 			if ($workInfo['is_open'] == 1) {
415
 			if ($workInfo['is_open'] == 1) {
425
 				//公开项目
416
 				//公开项目
426
-				$list = db('admin_user')->where(['status' => 1])->field('username,realname,thumb_img,id')->select();
417
+//				$list = db('admin_user')->where(['status' => 1])->field('username,realname,thumb_img,id')->select();
418
+                $list = db('work_user')
419
+                    ->alias('work')
420
+                    ->join('__ADMIN_USER__ user', 'user.id = work.user_id', 'LEFT')
421
+                    ->where(['work.work_id' => $param['work_id']])
422
+                    ->field('work.*,user.username,user.realname,user.thumb_img')
423
+                    ->order('work.types desc,user.id asc')
424
+                    ->select();
427
 			} else {
425
 			} else {
428
 				// $exp = new \think\db\Expression('field(types,1,0,2)');
426
 				// $exp = new \think\db\Expression('field(types,1,0,2)');
429
 				$list = db('work_user')
427
 				$list = db('work_user')

+ 2
- 6
application/work/model/WorkClass.php Bestand weergeven

69
 			$data['order_id'] = $max_order_id ? $max_order_id+1 : 0;
69
 			$data['order_id'] = $max_order_id ? $max_order_id+1 : 0;
70
 			$this->insert($data);
70
 			$this->insert($data);
71
 			$this->commit();
71
 			$this->commit();
72
-            $user=new ApiCommon();
73
-            $userInfo=$user->userInfo;
74
-            RecordActionLog($userInfo['id'], 'work', 'save',$param['name'], '','','添加了任务分类:'.$param['name']);
72
+            RecordActionLog( $param['create_user_id'], 'work', 'save',$param['name'], '','','添加了任务分类:'.$param['name']);
75
             return true;
73
             return true;
76
 		} catch(\Exception $e) {
74
 		} catch(\Exception $e) {
77
 			$this->rollback();
75
 			$this->rollback();
95
 			$this->error = '重命名失败';
93
 			$this->error = '重命名失败';
96
 			return false;
94
 			return false;
97
 		}
95
 		}
98
-        $user=new ApiCommon();
99
-        $userInfo=$user->userInfo;
100
-        RecordActionLog($userInfo['id'], 'work', 'save',$classInfo['name'], '','','编辑了任务分类:'.$classInfo['name']);
96
+        RecordActionLog($param['create_user_id'], 'work', 'save',$classInfo['name'], '','','编辑了任务分类:'.$classInfo['name']);
101
         
97
         
102
         return true;
98
         return true;
103
 	}
99
 	}

+ 2882
- 0
composer.lock
Diff onderdrukt omdat het te groot bestand
Bestand weergeven


+ 8
- 4
config/config.php Bestand weergeven

182
     'cache'                  => [
182
     'cache'                  => [
183
         // 驱动方式
183
         // 驱动方式
184
         'type'   => 'redis',
184
         'type'   => 'redis',
185
-        // 缓存保存目录
186
-        'path'   => CACHE_PATH,
185
+        // 连接地址
186
+        'host' => '127.0.0.1',
187
+        // 端口
188
+        'port' => 6379,
189
+        // 密码
190
+        'password' => '',
187
         // 缓存前缀
191
         // 缓存前缀
188
         'prefix' => '',
192
         'prefix' => '',
189
         // 缓存有效期 0表示永久缓存
193
         // 缓存有效期 0表示永久缓存
190
         'expire' => 86400*30,
194
         'expire' => 86400*30,
195
+        // 缓存保存目录
196
+        'path'   => CACHE_PATH,
191
         // 禁用缓存子目录
197
         // 禁用缓存子目录
192
         'cache_subdir' => false,
198
         'cache_subdir' => false,
193
-        // 密码
194
-        'password' => ''
195
     ],
199
     ],
196
 
200
 
197
     // +----------------------------------------------------------------------
201
     // +----------------------------------------------------------------------

+ 39
- 0
config/database_template.php Bestand weergeven

1
+<?php
2
+return [
3
+    // 数据库类型
4
+    'type'            => 'mysql',
5
+    // 服务器地址
6
+    'hostname'        => '127.0.0.1',
7
+    // 数据库名
8
+    'database'        => '',
9
+    // 用户名
10
+    'username'        => '',
11
+    // 密码
12
+    'password'        => '',
13
+    // 端口
14
+    'hostport'        => '3306',
15
+    // 连接dsn
16
+    'dsn'             => '',
17
+    // 数据库连接参数
18
+    'params'          => [],
19
+    // 数据库编码默认采用utf8
20
+    'charset'         => 'utf8',
21
+    // 数据库表前缀
22
+    'prefix'          => '5kcrm_', // 默认表前缀,不要改为其他值。
23
+    // 数据库调试模式
24
+    'debug'           => true,
25
+    // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
26
+    'deploy'          => 0,
27
+    // 数据库读写是否分离 主从式有效
28
+    'rw_separate'     => false,
29
+    // 读写分离后 主服务器数量
30
+    'master_num'      => 1,
31
+    // 指定从服务器序号
32
+    'slave_no'        => '',
33
+    // 自动读取主库数据
34
+    'read_master'     => false,
35
+    // 是否严格检查字段是否存在
36
+    'fields_strict'   => true,
37
+    // 数据集返回类型
38
+    'resultset_type'  => 'array',
39
+];

+ 23
- 1
config/route_admin.php Bestand weergeven

344
     'admin/setting/customerLevel' => ['admin/setting/customerLevel', ['method' => 'POST']],
344
     'admin/setting/customerLevel' => ['admin/setting/customerLevel', ['method' => 'POST']],
345
     //【设置】公海字段
345
     //【设置】公海字段
346
     'admin/setting/poolField' => ['admin/setting/poolField', ['method' => 'POST']],
346
     'admin/setting/poolField' => ['admin/setting/poolField', ['method' => 'POST']],
347
-
347
+    // 获取配置角色查看范围
348
+	'admin/rules/groupauth' => ['admin/rules/groupauth', ['method' => 'POST']],
349
+	// 授权配置角色查看范围
350
+	'admin/rules/upgroupauth' => ['admin/rules/upgroupauth', ['method' => 'POST']],
351
+	// 获取配置角色
352
+	'admin/rules/getgroupauth' => ['admin/rules/getgroupauth', ['method' => 'POST']],
353
+	// 授权配置角色查看范围id
354
+	'admin/rules/groupauthid' => ['admin/rules/groupauthid', ['method' => 'POST']],
355
+    
356
+    //【市场活动】市场活动列表
357
+    'admin/market/index' => ['admin/market/index', ['method' => 'POST']],
358
+    //【市场活动】市场活动添加
359
+    'admin/market/save' => ['admin/market/save', ['method' => 'POST']],
360
+    //【市场活动】市场活动修改
361
+    'admin/market/update' => ['admin/market/update', ['method' => 'POST']],
362
+    //【市场活动】市场活动删除
363
+    'admin/market/delete' => ['admin/market/delete', ['method' => 'POST']],
364
+    //【市场活动】市场活动启用停用
365
+    'admin/market/enables' => ['admin/market/enables', ['method' => 'POST']],
366
+    //【市场活动】市场活动自定义字段列表
367
+    'admin/market/getField' => ['admin/market/getField', ['method' => 'POST']],
368
+    //【市场活动】市场活动自定义字段表单
369
+    'admin/market/updateFields' => ['admin/market/updateFields', ['method' => 'POST']],
348
 	// MISS路由
370
 	// MISS路由
349
 	'__miss__'  => 'admin/base/miss',
371
 	'__miss__'  => 'admin/base/miss',
350
 ];
372
 ];

+ 26
- 5
config/route_crm.php Bestand weergeven

298
     'crm/invoice/count' => ['crm/invoice/count', ['method' => 'POST']],
298
     'crm/invoice/count' => ['crm/invoice/count', ['method' => 'POST']],
299
     // 【发票】重置开票信息
299
     // 【发票】重置开票信息
300
     'crm/invoice/resetInvoiceStatus' => ['crm/invoice/resetInvoiceStatus', ['method' => 'POST']],
300
     'crm/invoice/resetInvoiceStatus' => ['crm/invoice/resetInvoiceStatus', ['method' => 'POST']],
301
-
301
+    // 【发票】导出
302
+    'crm/invoice/excelExport' => ['crm/invoice/excelExport', ['method' => 'POST']],
303
+    
302
     // 【发票-开户行】列表
304
     // 【发票-开户行】列表
303
     'crm/invoiceInfo/index' => ['crm/invoiceInfo/index', ['method' => 'POST']],
305
     'crm/invoiceInfo/index' => ['crm/invoiceInfo/index', ['method' => 'POST']],
304
     // 【发票-开户行】详情
306
     // 【发票-开户行】详情
380
     'crm/index/queryDataInfo' => ['crm/index/queryDataInfo', ['method' => 'POST']],
382
     'crm/index/queryDataInfo' => ['crm/index/queryDataInfo', ['method' => 'POST']],
381
     // 【获取自动编号开启状态】
383
     // 【获取自动编号开启状态】
382
     'crm/index/autoNumberStatus' => ['crm/index/autoNumberStatus', ['method' => 'POST']],
384
     'crm/index/autoNumberStatus' => ['crm/index/autoNumberStatus', ['method' => 'POST']],
383
-
385
+    // 【商机阶段列表】
386
+    'crm/index/businessList' => ['crm/index/businessList', ['method' => 'POST']],
387
+    
384
     // 【获取仪表盘布局】
388
     // 【获取仪表盘布局】
385
     'crm/index/dashboard' => ['crm/index/dashboard', ['method' => 'POST']],
389
     'crm/index/dashboard' => ['crm/index/dashboard', ['method' => 'POST']],
386
     // 【修改仪表盘布局】
390
     // 【修改仪表盘布局】
477
     'crm/printing/down' => ['crm/printing/down', ['method' => 'POST']],
481
     'crm/printing/down' => ['crm/printing/down', ['method' => 'POST']],
478
     
482
     
479
     //跟进记录导入模板
483
     //跟进记录导入模板
480
-    'crm/activity/excelDownload' => ['crm/activity/excelDownload', ['method' => 'GET']],
484
+    'crm/activity/excelDownload' => ['crm/activity/excelDownload', ['method' => 'POST']],
481
     //跟进记录导入
485
     //跟进记录导入
482
     'crm/activity/excelImport' => ['crm/activity/excelImport', ['method' => 'POST']],
486
     'crm/activity/excelImport' => ['crm/activity/excelImport', ['method' => 'POST']],
483
     //跟进记录导出
487
     //跟进记录导出
495
     'crm/market/enables' => ['crm/market/enables', ['method' => 'POST']],
499
     'crm/market/enables' => ['crm/market/enables', ['method' => 'POST']],
496
     //市场活动状态删除
500
     //市场活动状态删除
497
     'crm/market/delete' => ['crm/market/delete', ['method' => 'POST']],
501
     'crm/market/delete' => ['crm/market/delete', ['method' => 'POST']],
498
-    
502
+    //市场活动对象列表
503
+    'crm/market/marketList' => ['crm/market/marketList', ['method' => 'POST']],
504
+    //市场活动手机页面信息
505
+    'crm/market/marketId' => ['crm/market/marketId', ['method' => 'POST']],
506
+    //市场活动表单列表
507
+    'crm/market/marketFormList' => ['crm/market/marketFormList', ['method' => 'POST']],
508
+    //市场活动表单添加
509
+    'crm/market/marketFormSave' => ['crm/market/marketFormSave', ['method' => 'POST']],
510
+    //市场活动表单同步数据
511
+    'crm/market/marketFormUpdate' => ['crm/market/marketFormUpdate', ['method' => 'POST']],
512
+    //市场活动表单下载
513
+    'crm/market/importDown' => ['crm/market/importDown', ['method' => 'POST']],
514
+    //市场活动表单字段
515
+    'crm/market/marketGetField' => ['crm/market/marketGetField', ['method' => 'POST']],
499
     //【通用】快捷编辑
516
     //【通用】快捷编辑
500
     'crm/common/quickEdit' => ['crm/common/quickEdit', ['method' => 'POST']],
517
     'crm/common/quickEdit' => ['crm/common/quickEdit', ['method' => 'POST']],
501
-
518
+    
519
+    //手机导航列表
520
+    'crm/setting/appMenuConfig' => ['crm/setting/appMenuConfig', ['method' => 'POST']],
521
+    //办公数量
522
+    'crm/setting/oaNumber' => ['crm/setting/oaNumber', ['method' => 'POST']],
502
     // MISS路由
523
     // MISS路由
503
     '__miss__' => 'admin/base/miss',
524
     '__miss__' => 'admin/base/miss',
504
 ];
525
 ];

+ 5
- 2
config/route_oa.php Bestand weergeven

162
     'oa/log/queryLog' => ['oa/log/queryLog', ['method' => 'POST']],
162
     'oa/log/queryLog' => ['oa/log/queryLog', ['method' => 'POST']],
163
     //日志销售简报
163
     //日志销售简报
164
     'oa/log/oneBulletin' => ['oa/log/oneBulletin', ['method' => 'POST']],
164
     'oa/log/oneBulletin' => ['oa/log/oneBulletin', ['method' => 'POST']],
165
+    //日志销售简报
166
+    'oa/log/favourUpdate' => ['oa/log/favourUpdate', ['method' => 'POST']],
165
     
167
     
166
     // 【审批】类型列表
168
     // 【审批】类型列表
167
 	'oa/examine/category'=>['oa/examine/category', ['method' => 'POST']],
169
 	'oa/examine/category'=>['oa/examine/category', ['method' => 'POST']],
203
     'oa/addresslist/userStar'=>['oa/addresslist/userStar', ['method' => 'POST']],
205
     'oa/addresslist/userStar'=>['oa/addresslist/userStar', ['method' => 'POST']],
204
 
206
 
205
     // 【代办事项】办公
207
     // 【代办事项】办公
206
-	'oa/message/num'=>['oa/message/num', ['method' => 'POST']],		
207
-	
208
+	'oa/message/num'=>['oa/message/num', ['method' => 'POST']],
209
+    //手机导航
210
+    'admin/setting/appMenuConfig' => ['admin/setting/appMenuConfig', ['method' => 'POST']],
208
 	// MISS路由
211
 	// MISS路由
209
 	'__miss__'  => 'admin/base/miss',
212
 	'__miss__'  => 'admin/base/miss',
210
 ];
213
 ];

+ 2
- 2
config/version.php Bestand weergeven

1
 <?php
1
 <?php
2
 return array(
2
 return array(
3
-'VERSION'=>'11.0.3',
4
-'RELEASE'=>'202105014',
3
+'VERSION'=>'11.1.0',
4
+'RELEASE'=>'20210625',
5
 );
5
 );

BIN
favicon.ico Bestand weergeven


+ 1
- 0
index.html
Diff onderdrukt omdat het te groot bestand
Bestand weergeven


+ 4
- 0
nginx.htaccess Bestand weergeven

1
+ if ( !-e $request_filename) {
2
+            rewrite ^/(.*)$ /index.php/$1 last;
3
+            break;
4
+        } 

+ 589
- 252
public/sql/5kcrm.sql
Diff onderdrukt omdat het te groot bestand
Bestand weergeven


+ 0
- 0
public/sql/5kcrm_all.sql Bestand weergeven


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