瀏覽代碼

v11.1.0-20210625

Michael_xu 5 年之前
父節點
當前提交
26b0e8466b
共有 100 個文件被更改,包括 13130 次插入5521 次删除
  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. 二進制
      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 查看文件

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

+ 0
- 43
application/admin/controller/Base.php 查看文件

@@ -32,52 +32,9 @@ class Base extends Common
32 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 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 39
     public function logout()
83 40
     {

+ 0
- 1
application/admin/controller/ExamineFlow.php 查看文件

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

+ 146
- 46
application/admin/controller/Field.php 查看文件

@@ -56,14 +56,16 @@ class Field extends ApiCommon
56 56
         }         
57 57
         $param = $this->param;
58 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 70
         $examine_types_arr = [];    
69 71
         switch ($param['type']) {
@@ -99,11 +101,6 @@ class Field extends ApiCommon
99 101
      */
100 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 105
         if ($this->param['types'] == 'oa_examine' && $this->param['types_id'] < 7) {
109 106
             return resultArray(['error' => '系统审批类型暂不支持编辑']);
@@ -114,7 +111,6 @@ class Field extends ApiCommon
114 111
         $param      = $this->param;
115 112
         $types      = $param['types'];
116 113
         $types_id   = $param['types_id'] ? : 0;
117
-//        $data['types'] = $param['types'];
118 114
 
119 115
         $data         = $param['data'];
120 116
         $saveParam    = []; # 新增数据
@@ -132,6 +128,24 @@ class Field extends ApiCommon
132 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 149
             if ($v['field_id']) {
136 150
                 if (isset($v['is_deleted']) && $v['is_deleted'] == '1') {
137 151
                     # 删除
@@ -160,26 +174,14 @@ class Field extends ApiCommon
160 174
         foreach ($deleteIds AS $key => $value) {
161 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 179
         if (!empty($saveParam)) {
179 180
             if (!$data = $fieldModel->createData($types, $saveParam)) {
180 181
                 $errorMessage[] = $fieldModel->getError();
181
-            }            
182
+            }
182 183
         }
184
+        
183 185
         # 编辑
184 186
         if (!empty($updateParam)) {
185 187
             if (!$data = $fieldModel->updateDataById($updateParam, $types)) {
@@ -215,10 +217,10 @@ class Field extends ApiCommon
215 217
                 'oa_log'          => '办公日志',
216 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 225
             SystemActionLog($userInfo['id'], $types,$systemModules, 1,  'update', $recordModules[$types], '','','编辑了自定义字段:'.$recordModules[$types]);
224 226
             return resultArray(['data' => '修改成功']);
@@ -242,6 +244,7 @@ class Field extends ApiCommon
242 244
         $controller = trim($param['controller']);
243 245
         $action = trim($param['action']);
244 246
         $system = !empty($param['system']) ? $param['system'] : 0;
247
+        $format = !empty($param['format']) ? $param['format'] : 1; // 设置返回数据的格式类型:1 还是之前的二维数组格式,兼容移动端、 2 三维数组,新版自定义字段的分组排序。
245 248
         unset($param['system']);
246 249
         
247 250
         if (!$module || !$controller || !$action) {
@@ -260,11 +263,6 @@ class Field extends ApiCommon
260 263
                     case 'crm_customer' : 
261 264
                         $customerModel = new \app\crm\model\Customer();
262 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 267
                         $auth_user_ids = $userModel->getUserByPer('crm', 'customer', $param['action']);
270 268
                         //读写权限
@@ -327,6 +325,13 @@ class Field extends ApiCommon
327 325
                     case 'crm_product' : 
328 326
                         $productModel = new \app\crm\model\Product();
329 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 335
                         break;
331 336
                     case 'crm_receivables' : 
332 337
                         $receivablesModel = new \app\crm\model\Receivables();
@@ -368,7 +373,23 @@ class Field extends ApiCommon
368 373
                         //读写权限
369 374
                         $roPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'read');
370 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 393
                             header('Content-Type:application/json; charset=utf-8');
373 394
                             exit(json_encode(['code'=>102,'error'=>'无权操作']));
374 395
                         }
@@ -380,6 +401,11 @@ class Field extends ApiCommon
380 401
         $action_id = $param['action_id'] ? : '';
381 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 410
         if ($param['types'] == 'crm_visit') {
385 411
             foreach ($data AS $key => $value) {
@@ -446,6 +472,18 @@ class Field extends ApiCommon
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 489
         if ($param['types'] == 'crm_receivables_plan') {
@@ -490,10 +528,10 @@ class Field extends ApiCommon
490 528
                 case 'crm_customer' :
491 529
                     $customerModel = new Customer();
492 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 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 536
                         $data[] = [
499 537
                             'field'     => $key,
@@ -606,11 +644,23 @@ class Field extends ApiCommon
606 644
                         ];
607 645
                     }
608 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 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 664
         return resultArray(['data' => array_values($data)]);
615 665
     }
616 666
 
@@ -623,11 +673,7 @@ class Field extends ApiCommon
623 673
     {
624 674
         $param = $this->param;
625 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 677
         if (!$res) {
632 678
             return resultArray(['error' => $fieldModel->getError()]);
633 679
         }
@@ -725,4 +771,58 @@ class Field extends ApiCommon
725 771
     {
726 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 查看文件

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

+ 4
- 1
application/admin/controller/Index.php 查看文件

@@ -62,7 +62,10 @@ class Index extends ApiCommon
62 62
             if ($value['field'] == 'check_status') $field_arr[$key]['form_type'] = 'check_status';
63 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 69
         return resultArray(['data' => $field_arr]);
67 70
     }
68 71
 

+ 15
- 5
application/admin/controller/Install.php 查看文件

@@ -47,7 +47,7 @@ class Install extends Controller
47 47
      */    
48 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 52
         if (strpos(request()->url(), "index.php") === false) {
53 53
             $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
@@ -70,7 +70,7 @@ class Install extends Controller
70 70
     public function step1()
71 71
     {
72 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 74
             $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
75 75
             header("Location:" . $url);
76 76
         }
@@ -97,7 +97,7 @@ class Install extends Controller
97 97
             die(); 
98 98
         }
99 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 101
             $url =  $protocol. "://" .$_SERVER["HTTP_HOST"] . "/index.php" . request()->url();
102 102
             header("Location:" . $url);
103 103
         }
@@ -375,8 +375,12 @@ INFO;
375 375
             'php'     => ['PHP版本', PHP_VERSION, '7.3 ( <em style="color: #888; font-size: 12px;">>= 7.0</em> )', 'ok','性能更佳'],
376 376
             'gd'      => ['gd', '开启', '开启', 'ok'],
377 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 384
         session('install_error','');
381 385
         if (substr($items['php'][1],0,3) < '7.0') {
382 386
             $items['php'][3] = 'error';
@@ -388,6 +392,7 @@ INFO;
388 392
             $items['gd'][3] = 'error';
389 393
             session('install_error', true);
390 394
         }
395
+
391 396
         if (!extension_loaded('openssl')) {
392 397
             $items['openssl'][1] = '未开启';
393 398
             $items['openssl'][3] = 'error';
@@ -398,7 +403,12 @@ INFO;
398 403
             $items['pdo'][3] = 'error';
399 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 412
         return $items;
403 413
     }
404 414
     

+ 131
- 1
application/admin/controller/Rules.php 查看文件

@@ -9,6 +9,7 @@ namespace app\admin\controller;
9 9
 
10 10
 use think\Hook;
11 11
 use think\Request;
12
+use think\Db;
12 13
 
13 14
 class Rules extends ApiCommon
14 15
 {
@@ -22,7 +23,7 @@ class Rules extends ApiCommon
22 23
     {
23 24
         $action = [
24 25
             'permission'=>[''],
25
-            'allow'=>['index']            
26
+            'allow'=>['index','groupauth','upgroupauth','getgroupauth','groupauthid']            
26 27
         ];
27 28
         Hook::listen('check_auth',$action);
28 29
         $request = Request::instance();
@@ -75,5 +76,134 @@ class Rules extends ApiCommon
75 76
         } 
76 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 查看文件

@@ -19,7 +19,7 @@ class Setting extends ApiCommon
19 19
      * @permission 无限制
20 20
      * @allow 登录用户可访问
21 21
      * @other 其他根据系统设置
22
-    **/    
22
+    **/
23 23
     public function _initialize()
24 24
     {
25 25
         $action = [
@@ -28,7 +28,7 @@ class Setting extends ApiCommon
28 28
         ];
29 29
         Hook::listen('check_auth',$action);
30 30
         $request = Request::instance();
31
-        $a = strtolower($request->action());        
31
+        $a = strtolower($request->action());
32 32
         if (!in_array($a, $action['permission'])) {
33 33
             parent::_initialize();
34 34
         }
@@ -39,7 +39,7 @@ class Setting extends ApiCommon
39 39
         if (!in_array(2,$adminTypes) && !in_array(1,$adminTypes) && !in_array($a, $unAction)) {
40 40
             header('Content-Type:application/json; charset=utf-8');
41 41
             exit(json_encode(['code'=>102,'error'=>'无权操作']));
42
-        }           
42
+        }
43 43
     }
44 44
 
45 45
     /**
@@ -176,4 +176,20 @@ class Setting extends ApiCommon
176 176
 
177 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 查看文件

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

+ 28
- 25
application/admin/controller/System.php 查看文件

@@ -16,47 +16,50 @@ class System extends ApiCommon
16 16
     public function _initialize()
17 17
     {
18 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 23
         $request = Request::instance();
24
-        $a = strtolower($request->action());        
24
+        $a = strtolower($request->action());
25 25
         if (!in_array($a, $action['permission'])) {
26 26
             parent::_initialize();
27
-        }            
28
-    }        
29
-
27
+        }
28
+    }
29
+    
30 30
     //信息列表
31 31
     public function index()
32
-    {   
32
+    {
33 33
         $systemModel = model('System');
34 34
         $data = $systemModel->getDataList();
35 35
         return resultArray(['data' => $data]);
36 36
     }
37
-	
37
+    
38 38
     //编辑保存
39
-	public function save()
40
-	{
39
+    public function save()
40
+    {
41 41
         $param = $this->param;
42
-        $userInfo=$this->userInfo;
43
-        $field_name='';
44
-        $dataInfo=[];
42
+        $userInfo = $this->userInfo;
43
+        $field_name = '';
44
+        $dataInfo = [];
45 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 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 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 62
         return resultArray(['data' => '操作成功!']);
60
-	}
63
+    }
61 64
 }
62 65
  

+ 115
- 9
application/admin/controller/UpdateSql.php 查看文件

@@ -21,10 +21,10 @@ class UpdateSql
21 21
      */
22 22
     static public function addPoolDefaultData()
23 23
     {
24
-        # 员工ID
24
+        // 员工ID
25 25
         $userIds = db('admin_user')->column('id');
26 26
 
27
-        # 公海主数据
27
+        // 公海主数据
28 28
         $poolData = [
29 29
             'pool_name'         => '系统默认公海',
30 30
             'admin_user_ids'    => ',1,',
@@ -42,7 +42,7 @@ class UpdateSql
42 42
             'create_time'       => time()
43 43
         ];
44 44
 
45
-        # 公海规则数据
45
+        // 公海规则数据
46 46
         $poolRuleData = [
47 47
             'pool_id'         => 0,
48 48
             'type'            => 1,
@@ -53,7 +53,7 @@ class UpdateSql
53 53
             'limit_day'       => 0
54 54
         ];
55 55
 
56
-        # 公海字段数据
56
+        // 公海字段数据
57 57
         $poolFieldData = [];
58 58
         $fields = db('admin_field')->field(['field', 'name', 'form_type', 'is_hidden'])->where(['types' => 'crm_customer'])->select();
59 59
         foreach ($fields AS $key => $value) {
@@ -76,14 +76,14 @@ class UpdateSql
76 76
 
77 77
         Db::startTrans();
78 78
         try {
79
-            # 添加公海主数据
79
+            // 添加公海主数据
80 80
             $poolId = Db::name('crm_customer_pool')->insert($poolData, false, true);
81 81
 
82
-            # 添加公海规则数据
82
+            // 添加公海规则数据
83 83
             $poolRuleData['pool_id'] = $poolId;
84 84
             Db::name('crm_customer_pool_rule')->insert($poolRuleData);
85 85
 
86
-            # 添加公海字段数据
86
+            // 添加公海字段数据
87 87
             array_walk($poolFieldData, function (&$val) use ($poolId) {
88 88
                 $val['pool_id'] = $poolId;
89 89
             });
@@ -107,10 +107,10 @@ class UpdateSql
107 107
      */
108 108
     static public function addFollowRuleData()
109 109
     {
110
-        # 删除旧版的跟进记录权限规则数据
110
+        // 删除旧版的跟进记录权限规则数据
111 111
         db('admin_rule')->where(['types' => 2, 'title' => '跟进记录管理', 'name' => 'record', 'level' => 2, 'pid' => 1])->delete();
112 112
 
113
-        # 新版跟进记录权限规则增加导入导出
113
+        // 新版跟进记录权限规则增加导入导出
114 114
         $activityPid = db('admin_rule')->where(['types' => 2, 'title' => '跟进记录', 'name' => 'activity', 'level' => 2])->value('id');
115 115
         if (!db('admin_rule')->where(['types' => 2, 'pid' => $activityPid, 'name' => 'excelImport'])->value('id')) {
116 116
             db('admin_rule')->insert(['types' => 2, 'title' => '导入', 'name' => 'excelImport', 'level' => 3, 'pid' => $activityPid, 'status' => 1]);
@@ -119,4 +119,110 @@ class UpdateSql
119 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 查看文件

@@ -98,8 +98,71 @@ class Users extends ApiCommon
98 98
         }
99 99
         $serverUserInfo = $this->queryLoginUser();
100 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 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,6 +174,7 @@ class Users extends ApiCommon
111 174
         $userModel = model('User');
112 175
         $param = $this->param;
113 176
         $userInfo = $this->userInfo;
177
+        $param['userId']=$userInfo['id'];
114 178
         $data = $userModel->createData($param);
115 179
         if (!$data) {
116 180
             return resultArray(['error' => $userModel->getError()]);
@@ -138,6 +202,7 @@ class Users extends ApiCommon
138 202
                 header('Content-Type:application/json; charset=utf-8');
139 203
                 exit(json_encode(['code' => 102, 'error' => '无权操作']));
140 204
             }
205
+            $param['userId']=$userInfo['id'];
141 206
         }
142 207
         unset($param['username']);
143 208
         $data = $userModel->updateDataById($param, $param['id']);
@@ -158,6 +223,8 @@ class Users extends ApiCommon
158 223
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
159 224
         }
160 225
         $param = $this->param;
226
+        $userInfo=$this->userInfo;
227
+        $param['user_id']=$userInfo['id'];
161 228
         if ($param['password'] && is_array($param['id'])) {
162 229
             $userModel = model('User');
163 230
             $ret = $userModel->updatePwdById($param);
@@ -322,7 +389,7 @@ class Users extends ApiCommon
322 389
         $param = $this->param;
323 390
         $userInfo = $this->userInfo;
324 391
         $userModel = model('User');
325
-        
392
+        $userId=$userInfo['id'];
326 393
         if (empty($param['new_pwd']) || empty($param['old_pwd'])) return resultArray(['error' => '密码不能为空!']);
327 394
         
328 395
         if ($param['id'] && (int)$param['id'] !== $userInfo['id']) {
@@ -359,7 +426,7 @@ class Users extends ApiCommon
359 426
             $userModel = model('User');
360 427
             $old_pwd = $param['old_pwd'];
361 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 430
             if (!$data) {
364 431
                 return resultArray(['error' => $userModel->getError()]);
365 432
             }
@@ -721,7 +788,8 @@ class Users extends ApiCommon
721 788
         if (empty($param['group_id'])) return resultArray(['error' => '请选择角色!']);
722 789
         
723 790
         $userModel = new User();
724
-        
791
+        $userInfo=$this->userInfo;
792
+        $param['userId']=$userInfo['id'];
725 793
         if (!$userModel->copyRole($param)) return resultArray(['error' => '操作失败!']);
726 794
         
727 795
         return resultArray(['data' => '操作成功!']);

+ 6
- 5
application/admin/controller/Work.php 查看文件

@@ -125,10 +125,11 @@ class Work extends ApiCommon
125 125
     {
126 126
         if (empty($this->param['id']))    return resultArray(['error' => '请选择要编辑的权限角色!']);
127 127
         if (empty($this->param['title'])) return resultArray(['error' => '请填写权限名称!']);
128
+        $userInfo=$this->userInfo;
129
+        $this->param['user_id']=$userInfo['id'];
128 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,8 +143,8 @@ class Work extends ApiCommon
142 143
     public function deleteRole(WorkLogic $workLogic)
143 144
     {
144 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 149
         if (empty($result['status'])) return resultArray(['error' => $result['error']]);
149 150
 

+ 55
- 1
application/admin/logic/FieldGrantLogic.php 查看文件

@@ -46,7 +46,10 @@ class FieldGrantLogic
46 46
         'visit' => [
47 47
             'number', 'visit_time', 'owner_user_id', 'shape', 'customer_id', 'contacts_id', 'contract_id', 'satisfaction',
48 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,6 +93,8 @@ class FieldGrantLogic
90 93
      */
91 94
     public function createCrmFieldGrant($roleId)
92 95
     {
96
+        # 防止重复,先删除一下
97
+        $this->deleteCrmFieldGrant($roleId);
93 98
         # 添加线索字段授权数据
94 99
         $this->createLeadsFieldGrant($roleId);
95 100
         # 添加客户字段授权数据
@@ -106,6 +111,8 @@ class FieldGrantLogic
106 111
         $this->createProductFieldGrant($roleId);
107 112
         # 添加回访字段授权信息
108 113
         $this->createVisitFieldGrant($roleId);
114
+        # 添加发票字段授权信息
115
+        $this->createInvoiceFieldGrant($roleId);
109 116
     }
110 117
 
111 118
     /**
@@ -678,4 +685,51 @@ class FieldGrantLogic
678 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 查看文件

@@ -440,6 +440,25 @@ class InitializeLogic
440 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 462
             # ------ 设置跟进记录常用语 START ------ #
444 463
             $phrase = ['电话无人接听', '客户无意向', '客户意向度适中,后续继续跟进', '客户意向度较强,成交几率较大'];
445 464
             $phraseId = db('crm_config')->where('name', 'activity_phrase')->value('id');
@@ -515,44 +534,6 @@ class InitializeLogic
515 534
         # 启动事务
516 535
         Db::startTrans();
517 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 537
             # ------ 清除审批数据 START ------ #
557 538
 
558 539
             # 获取审批下关联的附件ID
@@ -595,6 +576,11 @@ class InitializeLogic
595 576
             # ------ 清除审批数据 END ------ #
596 577
 
597 578
 
579
+            # ------ 重置扩展数据 START ------ #
580
+            Db::query("TRUNCATE TABLE ".$prefix."oa_examine_data");
581
+            # ------ 重置扩展数据 END ------ #
582
+
583
+
598 584
             # ------ 清除活动中有关审批的数据 START ------ #
599 585
 
600 586
             # 获取有关审批的活动ID

+ 2
- 2
application/admin/logic/LogLogic.php 查看文件

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

+ 2
- 2
application/admin/logic/MessageLogic.php 查看文件

@@ -245,7 +245,7 @@ class MessageLogic
245 245
         $where['is_delete'] = ['eq', 1];
246 246
         
247 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 249
         $where['type'] = $this->label(1);
250 250
         $taskCount = db('admin_message')->where($where)->count();
251 251
         $where['type'] = $this->label(2);
@@ -255,7 +255,7 @@ class MessageLogic
255 255
         $where['type'] = 9;
256 256
         $announceCount = db('admin_message')->where($where)->count();
257 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 259
         $where['type'] = $this->label(6);
260 260
         $crmCount = db('admin_message')->where($where)->count();
261 261
         

+ 38
- 15
application/admin/logic/PoolConfigLogic.php 查看文件

@@ -273,6 +273,9 @@ class PoolConfigLogic
273 273
             # 删除用户保存的公海字段数据
274 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 280
             Db::name('crm_customer_pool')->where('pool_id', $poolId)->delete();
278 281
 
@@ -361,63 +364,81 @@ class PoolConfigLogic
361 364
     public function getPoolFieldList($param)
362 365
     {
363 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 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 371
             $address = [
369 372
                 'field'     => 'address',
370 373
                 'name'      => '省、市、区/县',
371 374
                 'form_type' => 'customer_address',
372
-                'is_hidden' => 0
375
+                'is_hidden' => 0,
376
+                'is_null'   => 0,
377
+                'is_unique' => 0,
373 378
             ];
374 379
             $detailAddress = [
375 380
                 'field'     => 'detail_address',
376 381
                 'name'      => '详细地址',
377 382
                 'form_type' => 'text',
378
-                'is_hidden' => 0
383
+                'is_hidden' => 0,
384
+                'is_null'   => 0,
385
+                'is_unique' => 0,
379 386
             ];
380 387
             $lastRecord = [
381 388
                 'field'     => 'last_record',
382 389
                 'name'      => '最后跟进记录',
383 390
                 'form_type' => 'text',
384
-                'is_hidden' => 0
391
+                'is_hidden' => 0,
392
+                'is_null'   => 0,
393
+                'is_unique' => 0,
385 394
             ];
386 395
             $lastTime = [
387 396
                 'field'     => 'last_time',
388 397
                 'name'      => '最后跟进时间',
389 398
                 'form_type' => 'datetime',
390
-                'is_hidden' => 0
399
+                'is_hidden' => 0,
400
+                'is_null'   => 0,
401
+                'is_unique' => 0,
391 402
             ];
392 403
             $beforeOwnerUser = [
393 404
                 'field'     => 'before_owner_user_id',
394 405
                 'name'      => '前负责人',
395 406
                 'form_type' => 'user',
396
-                'is_hidden' => 0
407
+                'is_hidden' => 0,
408
+                'is_null'   => 0,
409
+                'is_unique' => 0,
397 410
             ];
398 411
             $intoPoolTime = [
399 412
                 'field'     => 'into_pool_time',
400 413
                 'name'      => '进入公海时间',
401 414
                 'form_type' => 'datetime',
402
-                'is_hidden' => 0
415
+                'is_hidden' => 0,
416
+                'is_null'   => 0,
417
+                'is_unique' => 0,
403 418
             ];
404 419
             $createTime = [
405 420
                 'field'     => 'create_time',
406 421
                 'name'      => '创建时间',
407 422
                 'form_type' => 'datetime',
408
-                'is_hidden' => 0
423
+                'is_hidden' => 0,
424
+                'is_null'   => 0,
425
+                'is_unique' => 0,
409 426
             ];
410 427
             $updateTime = [
411 428
                 'field'     => 'update_time',
412 429
                 'name'      => '更新时间',
413 430
                 'form_type' => 'datetime',
414
-                'is_hidden' => 0
431
+                'is_hidden' => 0,
432
+                'is_null'   => 0,
433
+                'is_unique' => 0,
415 434
             ];
416 435
             $createUser = [
417 436
                 'field'     => 'create_user_id',
418 437
                 'name'      => '创建人',
419 438
                 'form_type' => 'user',
420
-                'is_hidden' => 0
439
+                'is_hidden' => 0,
440
+                'is_null'   => 0,
441
+                'is_unique' => 0,
421 442
             ];
422 443
             array_push($data, $address, $detailAddress, $lastRecord, $lastTime, $createTime, $updateTime, $createUser, $beforeOwnerUser, $intoPoolTime);
423 444
 
@@ -468,11 +489,13 @@ class PoolConfigLogic
468 489
 
469 490
         foreach ($fields AS $key => $value) {
470 491
             $result[] = [
471
-                'pool_id' => $poolId,
472
-                'name' => $value['name'],
492
+                'pool_id'    => $poolId,
493
+                'name'       => $value['name'],
473 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 查看文件

@@ -92,14 +92,14 @@ class WorkLogic
92 92
     public function updateRole($param)
93 93
     {
94 94
         $res=Db::name('admin_group')->where('id',$param['id'])->find();
95
+        $userInd=$param['user_id'];
96
+        unset($param['user_id']);
95 97
         if(!$res){
96 98
             return false;
97 99
         }else{
98 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 103
             return $data;
104 104
         }
105 105
        
@@ -113,7 +113,7 @@ class WorkLogic
113 113
      * @throws \think\Exception
114 114
      * @throws \think\exception\PDOException
115 115
      */
116
-    public function deleteRole($id)
116
+    public function deleteRole($id,$userId)
117 117
     {
118 118
         $system = Db::name('admin_group')->where('id', $id)->find();
119 119
 
@@ -128,9 +128,7 @@ class WorkLogic
128 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 132
         return ['status' => true];
135 133
     }
136 134
 }

+ 1
- 1
application/admin/model/ActionRecord.php 查看文件

@@ -43,7 +43,7 @@ class ActionRecord extends Common
43 43
 		}
44 44
 		$userModel = model('User');
45 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 47
 			$dataList[$k]['content'] = explode('.|.', $v['content']);
48 48
 		}
49 49
 		return $dataList;

+ 310
- 306
application/admin/model/Common.php 查看文件

@@ -10,333 +10,337 @@ namespace app\admin\model;
10 10
 use think\Model;
11 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 41
         $pageType = $request['pageType'] ? 'all' : ''; //all全部(不分页)
42 42
         $page = 1;
43
-        if (isset($request['page']) && is_numeric($request['page']) ) {
43
+        if (isset($request['page']) && is_numeric($request['page'])) {
44 44
             $page = $request['page'];
45 45
             unset($request['page']);
46 46
         }
47 47
         $limit = 15;
48
-        if (isset($request['limit']) && is_numeric($request['limit']) ) {
48
+        if (isset($request['limit']) && is_numeric($request['limit'])) {
49 49
             $limit = $request['limit'];
50 50
             unset($request['limit']);
51
-		}
52
-		$offset = $length = null;
51
+        }
52
+        $offset = $length = null;
53 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 80
         $ret = [
81 81
             'page' => $page,
82 82
             'limit' => $limit,
83
-			'map' => $request,
84
-			'offset' => $offset,
85
-			'length' => $length,
86
-		];
83
+            'map' => $request,
84
+            'offset' => $offset,
85
+            'length' => $length,
86
+        ];
87 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 311
 //						$temp = array_map(function ($val) { return $val->toarray(); }, $val[$field['field'] . '_name']);
312 312
 //						$val[$field['field']] = implode(',', array_column($temp, 'name'));
313 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 333
 //								$val[$field['field']] = $val[$field['field'] . '_info'];
333 334
                             case 'check_status' :
334 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 查看文件

@@ -14,6 +14,7 @@ use com\PseudoQueue as Queue;
14 14
 use think\Cache;
15 15
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
16 16
 use think\cache\driver\Redis;
17
+
17 18
 class Excel extends Common
18 19
 {
19 20
     /**
@@ -26,6 +27,8 @@ class Excel extends Common
26 27
         'crm_customer',
27 28
         'crm_contacts',
28 29
         'crm_product',
30
+        'crm_contract',
31
+        'crm_business',
29 32
         'admin_user',
30 33
         'task'
31 34
     ];
@@ -72,7 +75,7 @@ class Excel extends Common
72 75
     public function excelImportDownload($field_list, $types, $save_path = '')
73 76
     {
74 77
         $fieldModel = new \app\admin\model\Field();
75
-    
78
+        
76 79
         //实例化主文件
77 80
         $objPHPExcel = new Spreadsheet();
78 81
         $objProps = $objPHPExcel->getProperties(); // 设置excel文档的属性
@@ -86,7 +89,7 @@ class Excel extends Common
86 89
         $objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet
87 90
         $objActSheet = $objPHPExcel->getActiveSheet();
88 91
         $objActSheet->setTitle('导入模板' . date('Y-m-d', time())); //设置sheet的标题
89
-    
92
+        
90 93
         //存储Excel数据源到其他工作薄
91 94
         $objPHPExcel->createSheet();
92 95
         $subObject = $objPHPExcel->getSheet(1);
@@ -111,6 +114,7 @@ class Excel extends Common
111 114
         } else {
112 115
             $k = 0;
113 116
         }
117
+        $objActSheet->getColumnDimension('A1')->setWidth(70);
114 118
         foreach ($field_list as $field) {
115 119
             if ($field['form_type'] == 'map_address' && $types == 'crm_customer') {
116 120
                 for ($a = 0; $a <= 3; $a++) {
@@ -121,13 +125,13 @@ class Excel extends Common
121 125
                 }
122 126
             } else {
123 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 130
                     if ($field['form_type'] == 'category' && $field['types'] == 'crm_product') {
127 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 133
                         $setting = db('admin_user')->order('id asc')->column('realname');
130
-                    }else{
134
+                    } else {
131 135
                         $setting = $field['setting'] ?: [];
132 136
                     }
133 137
                     $select_value = implode(',', $setting);
@@ -146,6 +150,7 @@ class Excel extends Common
146 150
                             $endcell = $c;
147 151
                         }
148 152
                         for ($j = 3; $j <= 70; $j++) {
153
+                            $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getFont()->setName("宋体")->setSize(11)->getColor()->setARGB('#00000000');
149 154
                             $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
150 155
                             //数据有效性   start
151 156
                             $objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation();
@@ -164,6 +169,7 @@ class Excel extends Common
164 169
                     } else {
165 170
                         if ($select_value) {
166 171
                             for ($j = 3; $j <= 70; $j++) {
172
+                                $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getFont()->setName("宋体")->setSize(11)->getColor()->setARGB('#00000000');
167 173
                                 $objActSheet->getStyle($this->stringFromColumnIndex($k) . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
168 174
                                 //数据有效性   start
169 175
                                 $objValidation = $objActSheet->getCell($this->stringFromColumnIndex($k) . $j)->getDataValidation();
@@ -182,10 +188,14 @@ class Excel extends Common
182 188
                         }
183 189
                     }
184 190
                 }
191
+                
185 192
                 $objActSheet->getStyle($this->stringFromColumnIndex($k))->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);//设置单元格格式 (文本)
186 193
                 //检查该字段若必填,加上"*"
187 194
                 $field['name'] = sign_required($field['is_null'], $field['name']);
188 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 199
                 $k++;
190 200
             }
191 201
         }
@@ -193,19 +203,17 @@ class Excel extends Common
193 203
         $mark_row = $this->stringFromColumnIndex($k);
194 204
         
195 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 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 217
         switch ($types) {
210 218
             case 'crm_leads' :
211 219
                 $types_name = '线索信息';
@@ -243,13 +251,34 @@ class Excel extends Common
243 251
                 $types_name = '任务信息';
244 252
                 $type_name = 'task';
245 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 262
             default :
247 263
                 $types_name = '悟空软件';
248 264
                 $type_name = 'WuKong';
249 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 279
         $objActSheet->setCellValue('A1', $content);
280
+        //设置A1单元格内容为
281
+        $objActSheet->getStyle('A1')->getAlignment()->setWrapText(true);//合并单元格换行
253 282
         $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xls');
254 283
         ob_end_clean();
255 284
         if ($save_path) {
@@ -432,11 +461,13 @@ class Excel extends Common
432 461
                 foreach ($field_list as $rule) {
433 462
                     if ($rule['form_type'] == 'customer_address') {
434 463
                         $address_arr = explode(chr(10), $val['address']);
435
-                        
436 464
                         $rows[] = $address_arr[0] ?: '';
437 465
                         $rows[] = $address_arr[1] ?: '';
438 466
                         $rows[] = $address_arr[2] ?: '';
439 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 471
                         $rows[] = $fieldModel->getValueByFormtype($val[$rule['field']], $rule['form_type']);
441 472
                     }
442 473
                 }
@@ -488,8 +519,11 @@ class Excel extends Common
488 519
             $queue->dequeue();
489 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 528
         $queue = new Queue(self::IMPORT_QUEUE, 50000000);
495 529
         $import_queue_index = input('import_queue_index');
@@ -556,16 +590,16 @@ class Excel extends Common
556 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 604
             vendor("phpexcel.PHPExcel");
571 605
             vendor("phpexcel.PHPExcel.Writer.Excel5");
@@ -649,15 +683,43 @@ class Excel extends Common
649 683
                     break;
650 684
             }
651 685
             // 字段
652
-    
686
+            # 下次升级
653 687
             $fieldModel = new \app\admin\model\Field();
654 688
             $fieldParam['types'] = $types;
655 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 724
             $field_list = array_map(function ($val) {
663 725
                 if (method_exists($val, 'toArray')) {
@@ -667,40 +729,6 @@ class Excel extends Common
667 729
                 }
668 730
             }, $field_list);
669 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 733
             $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
706 734
             $objRender->setReadDataOnly(true);
@@ -717,12 +745,12 @@ class Excel extends Common
717 745
             // 检测导入文件是否使用最新模板
718 746
             $header = $sheet->rangeToArray("A2:{$max_col}2")[0];
719 747
             $temp = 0;
720
-           
721 748
             for ($i = 0; $i < count($field_list); $i++) {
722 749
                 if (
723 750
                     $header[$i] == $field_list[$i]['name']
724 751
                     || $header[$i] == '*' . $field_list[$i]['name']
725 752
                 ) {
753
+                    $res[] = $header[$i];
726 754
                     $temp++;
727 755
                     // 字段为地址时,占四列
728 756
                 } elseif ($field_list[$i]['form_type'] == 'map_address') {
@@ -732,12 +760,11 @@ class Excel extends Common
732 760
                         && $header[$i + 2] == $this->map_address[2]
733 761
                         && $header[$i + 3] == $this->map_address[3]
734 762
                     ) {
763
+                        $ress[] = $header[$i];
735 764
                         $temp++;
736 765
                     }
737 766
                 }
738 767
             }
739
-            
740
-            
741 768
             // 每次导入条数
742 769
             $page_size = 100;
743 770
             
@@ -768,31 +795,28 @@ class Excel extends Common
768 795
             // 数据重复时的处理方式 0跳过  1覆盖
769 796
             $config = $param['config'] ?: 0;
770 797
             // 默认数据
771
-            if(!empty($param['pool_id'])){
798
+            if (!empty($param['pool_id'])) {
772 799
                 //公海导入
773 800
                 $default_data = [
774 801
                     'create_user_id' => $param['create_user_id'],
775 802
                     'create_time' => time(),
776 803
                     'update_time' => time(),
777 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 806
                     'pool_id' => $param['pool_id'],
781 807
                 ];
782
-            }else{
808
+            } else {
783 809
                 $default_data = [
784 810
                     'create_user_id' => $param['create_user_id'],
785
-                    'owner_user_id' => $param['owner_user_id'],
786 811
                     'create_time' => time(),
787 812
                     'update_time' => time(),
788 813
                 ];
789 814
             }
790 815
             if ($temp !== count($field_list)) {
791
-//                $this->error = '请使用最新导入模板';
792 816
                 @unlink($save_path);
793 817
                 $queue->dequeue();
794 818
                 foreach ($dataList as $val) {
795
-                    $error_data_func($val, '请使用最新导入模板1');
819
+                    $error_data_func($val, '请使用最新导入模板');
796 820
                 }
797 821
                 $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
798 822
                 $objWriter->save($error_path);
@@ -871,7 +895,7 @@ class Excel extends Common
871 895
                         }
872 896
                         $fk++;
873 897
                     }
874
-                    if (!empty($not_null_field)) {
898
+                    if (!empty($not_null_field) && empty($param['pool_id'])) {
875 899
                         $error_data_func($val, implode(', ', $not_null_field) . '不能为空');
876 900
                         continue;
877 901
                     }
@@ -887,15 +911,19 @@ class Excel extends Common
887 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 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 927
                         if ($config) {
900 928
                             $data = array_merge($data, $default_data);
901 929
                             $data['create_user_id'] = $param['create_user_id'];
@@ -904,21 +932,32 @@ class Excel extends Common
904 932
                             try {
905 933
                                 $up_success_count = 0;
906 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 938
                                             $error_data_func($val, $temp_error);
911 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 962
                                     $up_success_count++;
924 963
                                 }
@@ -944,16 +983,23 @@ class Excel extends Common
944 983
                             $unique_field = array_unique($unique_field);
945 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 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 999
                             $data = array_merge($data, $default_data);
1000
+                            if ($types != 'admin_user') {
1001
+                                $data['excel'] = 1;
1002
+                            }
957 1003
                             if (!$resData = $dataModel->createData($data)) {
958 1004
                                 $error_data_func($val, $dataModel->getError());
959 1005
                             }
@@ -1001,7 +1047,7 @@ class Excel extends Common
1001 1047
                     'error' => $error
1002 1048
                 ]);
1003 1049
                 // 执行完成
1004
-                $redis= new Redis();
1050
+                $redis = new Redis();
1005 1051
                 if ($done >= $total) {
1006 1052
                     // 出队
1007 1053
                     $queue->dequeue();
@@ -1024,7 +1070,7 @@ class Excel extends Common
1024 1070
                         'user_id' => $user_id,
1025 1071
                         'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
1026 1072
                     ]);
1027
-                  
1073
+                    
1028 1074
                     Cache::rm('item');
1029 1075
                     Cache::rm('excel_item');
1030 1076
                     Cache::set('item', 1, config('import_cache_time'));
@@ -2154,8 +2200,8 @@ class Excel extends Common
2154 2200
         $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(18);//所有单元格(列)默认宽度
2155 2201
         $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
2156 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 2205
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFont()->getColor()->setARGB('FF000000');
2160 2206
         $objActSheet->getStyle('A1:' . $cellKey[count($field_list) - 1] . '1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('##00BFFF');
2161 2207
         
@@ -2168,7 +2214,7 @@ class Excel extends Common
2168 2214
             $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getFont()->setBold(true);//设置是否加粗
2169 2215
             $objPHPExcel->getActiveSheet()->getStyle($cellKey[$k] . $topNumber)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//垂直居中
2170 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 2218
             if ($v[3] > 0)//大于0表示需要设置宽度
2173 2219
             {
2174 2220
                 $objPHPExcel->getActiveSheet()->getColumnDimension($cellKey[$k])->setWidth($v[3]);//设置列宽度
@@ -2176,17 +2222,18 @@ class Excel extends Common
2176 2222
         }
2177 2223
         $objActSheet->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getFont()->getColor()->setARGB('FF000000');
2178 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 2234
         foreach ($callback as $k => $item) {
2188 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 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 2238
                 $objPHPExcel->getActiveSheet()->setCellValue($cellKey[$key] . ($k + 1 + $topNumber), $item[$rule['field']]);
2192 2239
             }
@@ -2249,7 +2296,7 @@ class Excel extends Common
2249 2296
             $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
2250 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 2300
             $objPHPExcel->getActiveSheet()->getStyle('A2:' . $cellKey[count($field_list) - 1] . '2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
2254 2301
             
2255 2302
             if ($v[3] > 0)//大于0表示需要设置宽度
@@ -2394,16 +2441,18 @@ class Excel extends Common
2394 2441
         $excelData = Cache::pull('excel');
2395 2442
         $base = $excelData['base'];
2396 2443
         if ($param == 0) {
2397
-            if($base=='batchTaskImportData'){
2444
+            if ($base == 'batchTaskImportData') {
2398 2445
                 $this->batchTaskImportData('', $excelData);
2399
-            }else{
2446
+            } elseif ($base == 'ActivityImport') {
2447
+                $this->ActivityImport('', $excelData);
2448
+            } else {
2400 2449
                 $this->batchImportData('', $excelData);
2401 2450
             }
2402 2451
             $data = 0;
2403 2452
         } elseif ($param == 1) {
2404 2453
             $data = '';
2405 2454
         }
2406
-    
2455
+        
2407 2456
         return $data;
2408 2457
     }
2409 2458
     
@@ -2454,7 +2503,7 @@ class Excel extends Common
2454 2503
         } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
2455 2504
             $data['firstPage'] = false;
2456 2505
             $data['lastPage'] = false;
2457
-        } else if ($param['page'] == 1) {
2506
+        } else if ($param['page'] == 1  && (int)($param['page'] * $param['limit']) < $dataCount) {
2458 2507
             $data['firstPage'] = true;
2459 2508
             $data['lastPage'] = false;
2460 2509
         }
@@ -2471,7 +2520,7 @@ class Excel extends Common
2471 2520
      * @version     1.0 版本号
2472 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 2526
         $types = $param['types'];
@@ -2480,11 +2529,11 @@ class Excel extends Common
2480 2529
             $queue->dequeue();
2481 2530
             return false;
2482 2531
         }
2483
-       
2532
+        $user_id = $param['user_id'];
2484 2533
         // 采用伪队列  允许三人同时导入数据
2485 2534
         $queue = new Queue(self::IMPORT_QUEUE, 30000);
2486 2535
         $import_queue_index = input('import_queue_index');
2487
-     
2536
+        
2488 2537
         // 队列任务ID
2489 2538
         if (!$import_queue_index) {
2490 2539
             if (!$import_queue_index = $queue->makeTaskId()) {
@@ -2501,27 +2550,28 @@ class Excel extends Common
2501 2550
         }
2502 2551
         // 取消导入
2503 2552
         if ($param['page'] == -1) {
2504
-           
2553
+            
2505 2554
             @unlink(UPLOAD_PATH . $param['temp_file']);
2506 2555
             $this->error = [
2507 2556
                 'msg' => '导入已取消',
2508 2557
                 'page' => -1
2509 2558
             ];
2510
-           
2559
+            
2511 2560
             if ($param['error']) {
2512 2561
                 $this->error['error_file_path'] = 'temp/' . $param['error_file'];
2513 2562
             } else {
2514
-               
2563
+                
2515 2564
                 @unlink(TEMP_DIR . $param['error_file']);
2516 2565
             }
2517 2566
             $temp = $queue->cache('last_import_cache');
2518
-           
2567
+            
2519 2568
             (new ImportRecord())->createData([
2520 2569
                 'type' => $types,
2521 2570
                 'total' => $temp['total'],
2522 2571
                 'done' => $temp['done'],
2523 2572
                 'cover' => $temp['cover'],
2524 2573
                 'error' => $temp['error'],
2574
+                'user_id' => $user_id,
2525 2575
                 'error_data_file_path' => $temp['error'] ? 'temp/' . $error_data_file_name : ''
2526 2576
             ]);
2527 2577
             $queue->dequeue();
@@ -2559,7 +2609,7 @@ class Excel extends Common
2559 2609
             vendor("phpexcel.PHPExcel.Writer.Excel5");
2560 2610
             vendor("phpexcel.PHPExcel.Writer.Excel2007");
2561 2611
             vendor("phpexcel.PHPExcel.IOFactory");
2562
-           
2612
+            
2563 2613
             // 错误数据临时文件路径  错误数据开始行数
2564 2614
             if ($param['error_file']) {
2565 2615
                 $error_path = TEMP_DIR . $param['error_file'];
@@ -2578,7 +2628,7 @@ class Excel extends Common
2578 2628
             // 加载错误数据文件
2579 2629
             
2580 2630
             $err_PHPExcel = \PHPExcel_IOFactory::load($error_path);
2581
-           
2631
+            
2582 2632
             $error_sheet = $err_PHPExcel->setActiveSheetIndex(0);
2583 2633
             /**
2584 2634
              * 添加错误数据到临时文件
@@ -2605,7 +2655,7 @@ class Excel extends Common
2605 2655
             $objRender = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
2606 2656
             $objRender->setReadDataOnly(true);
2607 2657
             $ExcelObj = $objRender->load($save_path);
2608
-          
2658
+            
2609 2659
             // 指定工作表
2610 2660
             $sheet = $ExcelObj->getSheet(0);
2611 2661
             // 总行数
@@ -2642,42 +2692,44 @@ class Excel extends Common
2642 2692
             }
2643 2693
             // 读取数据
2644 2694
             $dataList = $sheet->rangeToArray("A{$start_row}:{$max_col}{$end_row}");
2645
-            // 默认数据
2646
-            $default_data = [
2647
-            ];
2648
-            switch ($types){
2695
+            switch ($types) {
2649 2696
                 case 'crm_business':
2650 2697
                     $dataModel = new \app\crm\model\Business();
2651 2698
                     $db = db('crm_business');
2652 2699
                     $db_id = 'business_id';
2653
-                    $activity_type=5;
2700
+                    $activity_type = 5;
2701
+                    $activity_name='所属商机';
2654 2702
                     break;
2655 2703
                 case 'crm_contract':
2656 2704
                     $db = db('crm_contract');
2657 2705
                     $db_id = 'contract_id';
2658
-                    $activity_type=6;
2706
+                    $activity_type = 6;
2707
+                    $activity_name='所属合同';
2659 2708
                     break;
2660 2709
                 case 'crm_leads' :
2661 2710
                     $dataModel = new \app\crm\model\Leads();
2662 2711
                     $db = db('crm_leads');
2663 2712
                     $db_id = 'leads_id';
2664
-                    $activity_type=1;
2713
+                    $activity_type = 1;
2714
+                    $activity_name='所属线索';
2665 2715
                     break;
2666 2716
                 case 'crm_customer' :
2667 2717
                     $dataModel = new \app\crm\model\Customer();
2668 2718
                     $db = db('crm_customer');
2669 2719
                     $db_id = 'customer_id';
2670 2720
                     $fieldParam['form_type'] = ['not in', ['file', 'form', 'user', 'structure']];
2671
-                    $activity_type=2;
2721
+                    $activity_type = 2;
2722
+                    $activity_name='所属客户';
2672 2723
                     break;
2673 2724
                 case 'crm_contacts' :
2674 2725
                     $dataModel = new \app\crm\model\Contacts();
2675 2726
                     $db = db('crm_contacts');
2676 2727
                     $db_id = 'contacts_id';
2677
-                    $activity_type=3;
2728
+                    $activity_type = 3;
2729
+                    $activity_name='所属联系人';
2678 2730
                     break;
2679 2731
             }
2680
-         
2732
+            
2681 2733
             // 开始导入数据
2682 2734
             foreach ($dataList as $val) {
2683 2735
                 $fk = 0;
@@ -2704,45 +2756,47 @@ class Excel extends Common
2704 2756
                     continue;
2705 2757
                 }
2706 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 2763
                 if (empty($customerData)) {
2711
-                    $error_data_func($val, '所属客户'.$val[2].'不存在');
2764
+                    $error_data_func($val, $activity_name . $val[2] . '不存在');
2712 2765
                     continue;
2713 2766
                 }
2714 2767
                 if (empty($userData)) {
2715
-                    $error_data_func($val, '管理员'.$val[1].'不存在');
2768
+                    $error_data_func($val, '管理员' . $val[1] . '不存在');
2716 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 2791
                     $data['activity_type_id'] = $customerData;
2740 2792
                     $data['activity_type'] = $activity_type;
2793
+                    $data['excel'] = 1;
2794
+                    $data['create_user_id'] = $user_id;
2741 2795
                     unset($data['create_user_id']);
2742 2796
                     if (!$resData = $activityLogic->save($data)) {
2743 2797
                         $error_data_func($val, $dataModel->getError());
2744 2798
                     }
2745
-                }
2799
+
2746 2800
             }
2747 2801
             // 完成数(已导入数)
2748 2802
             $done = ($page - 1) * $page_size + count($dataList);
@@ -2755,7 +2809,7 @@ class Excel extends Common
2755 2809
             // 错误数据文件保存
2756 2810
             $objWriter = \PHPExcel_IOFactory::createWriter($err_PHPExcel, 'Excel5');
2757 2811
             $objWriter->save($error_path);
2758
-           
2812
+            
2759 2813
             $this->error = [
2760 2814
                 // 数据导入文件临时路径
2761 2815
                 'temp_file' => $save_name,
@@ -2774,7 +2828,7 @@ class Excel extends Common
2774 2828
                 // 导入任务ID
2775 2829
                 'import_queue_index' => $import_queue_index
2776 2830
             ];
2777
-           
2831
+            
2778 2832
             $queue->cache('last_import_cache', [
2779 2833
                 'total' => $total,
2780 2834
                 'done' => $done,
@@ -2800,6 +2854,7 @@ class Excel extends Common
2800 2854
                     'done' => $done,
2801 2855
                     'cover' => $cover,
2802 2856
                     'error' => $error,
2857
+                    'user_id' => $user_id,
2803 2858
                     'error_data_file_path' => $error ? 'temp/' . $error_data_file_name : ''
2804 2859
                 ]);
2805 2860
                 Cache::set('item', 1, config('import_cache_time'));
@@ -2826,101 +2881,4 @@ class Excel extends Common
2826 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
文件差異過大導致無法顯示
查看文件


+ 5
- 7
application/admin/model/Group.php 查看文件

@@ -100,12 +100,14 @@ class Group extends Common
100 100
 	//编辑角色
101 101
 	public function updateDataById($param,$group_id)
102 102
 	{
103
+	    $userId = $param['user_id'];
103 104
 		$dataInfo = $this->get($group_id);
104 105
 		if(!$dataInfo){
105 106
 			$this->error = '该角色不存在或已删除';
106 107
 			return false;
107 108
 		}
108 109
 		unset($param['types']);
110
+		unset($param['user_id']);
109 111
 
110 112
 		# 处理编辑时,前端可能不传父id的问题(admin_rule表level为1的主键)
111 113
         if (!empty($param['rules'])) {
@@ -125,9 +127,7 @@ class Group extends Common
125 127
         }
126 128
 		$flag = $this->where('id = '.$group_id)->update($param);
127 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 131
             return true;
132 132
 		} else {
133 133
 			$this->error = '操作失败';
@@ -136,7 +136,7 @@ class Group extends Common
136 136
 	}
137 137
 	
138 138
 	//删除角色
139
-	public function delGroupById($group_id = '')
139
+	public function delGroupById($group_id = '',$userId)
140 140
 	{
141 141
 		$dataInfo = $this->get($group_id);
142 142
 		if(!$dataInfo){
@@ -150,9 +150,7 @@ class Group extends Common
150 150
 		$flag = $this->where('id = '.$group_id)->delete();
151 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 154
             return true;
157 155
 		} else {
158 156
 			$this->error = '删除失败';

+ 7
- 1
application/admin/model/Message.php 查看文件

@@ -165,7 +165,10 @@ class Message extends Common
165 165
      * 移除团队成员
166 166
      */
167 167
     const TEAM_END = 31;
168
-
168
+    /**
169
+     * 移除队成员
170
+     */
171
+    const TEAM_LEADS = 32;
169 172
     /**
170 173
      * 消息类型
171 174
      *
@@ -273,6 +276,9 @@ class Message extends Common
273 276
         31 => [
274 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 查看文件

@@ -150,7 +150,6 @@ class Scene extends Common
150 150
 	{
151 151
 		$where = [];
152 152
 		$where['scene_id'] = $id;
153
-		// $where['user_id'] = [['=',$user_id],['=',0],'or'];
154 153
 		$data = db('admin_scene')->where($where)->find();
155 154
 		if (!$types) {
156 155
 			$types = $data['types'] ? : '';
@@ -407,7 +406,7 @@ class Scene extends Common
407 406
 		$where['types'] = $types;
408 407
 		$where['user_id'] = $user_id;
409 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 410
 			$resData['bydata'] = 'all';
412 411
 		} else {
413 412
 			$resData = db('admin_scene')->where(['scene_id' => $scene_id])->find();
@@ -417,7 +416,7 @@ class Scene extends Common
417 416
 		} else {
418 417
 			//处理data
419 418
 			$data = $resData ? json_decode($resData,true) : [];			
420
-		}		
419
+		}
421 420
 		return $data;				
422 421
 	}
423 422
 
@@ -429,10 +428,6 @@ class Scene extends Common
429 428
      */	
430 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 431
     	$map           = [];
437 432
     	$auth_user_ids = [];
438 433
     	$part_user_ids = [];
@@ -448,7 +443,7 @@ class Scene extends Common
448 443
     		    break;
449 444
     		case 'sub' :
450 445
                 # 下属负责的
451
-    		    $auth_user_ids = getSubUserId(false) ? : ['-1'];
446
+    		    $auth_user_ids = getSubUserId(false, 0, $user_id) ? : ['-1'];
452 447
     		    break;
453 448
     		case 'all' :
454 449
                 # 全部
@@ -456,7 +451,7 @@ class Scene extends Common
456 451
     		    break;
457 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 455
     		    break;
461 456
     		case 'pool' :
462 457
     		    # 今日进入公海的客户
@@ -465,16 +460,28 @@ class Scene extends Common
465 460
     			break;
466 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 464
                 break;
470 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 468
                 break;
474 469
             case 'star' :
475 470
                 $where = $this->getStarParam($types, $user_id);
476 471
                 if (!empty($where)) $map = $where;
477 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 485
     		default :
479 486
                 # 全部
480 487
     		    $auth_user_ids = '';
@@ -483,12 +490,12 @@ class Scene extends Common
483 490
     	$auth_user_ids = $auth_user_ids ? : [];
484 491
 
485 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 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 501
     	return $map;
@@ -505,17 +512,11 @@ class Scene extends Common
505 512
      */
506 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 521
         return $where;
521 522
     }

+ 2
- 4
application/admin/model/Structure.php 查看文件

@@ -64,7 +64,7 @@ class Structure extends Common
64 64
 		return $det;
65 65
 	}
66 66
 
67
-	public function delStrById($id)
67
+	public function delStrById($id,$userId)
68 68
 	{
69 69
 		if (!$id) {
70 70
 			$this->error = '删除失败';
@@ -90,11 +90,9 @@ class Structure extends Common
90 90
 			$this->error = '删除失败';
91 91
 			return false;
92 92
 		} else {
93
-            $apiCommon = new ApiCommon();
94
-            $userInfo = $apiCommon->userInfo;
95 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 96
             return true;
99 97
 		}	
100 98
 	}

+ 1028
- 988
application/admin/model/User.php
文件差異過大導致無法顯示
查看文件


+ 262
- 0
application/admin/traits/FieldVerificationTrait.php 查看文件

@@ -0,0 +1,262 @@
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 查看文件

@@ -42,46 +42,8 @@
42 42
         <h1 style="text-align:center;padding-top: 20px;">安装悟空CRM数据库超时,请手动导入SQL文件!</h1>
43 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 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 47
         </div>
86 48
     </div>
87 49
 </div>

+ 1
- 0
application/command.php 查看文件

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

+ 867
- 284
application/common.php
文件差異過大導致無法顯示
查看文件


+ 102
- 100
application/common/command/PoolCommand.php 查看文件

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

+ 153
- 0
application/common/command/Team.php 查看文件

@@ -0,0 +1,153 @@
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 查看文件

@@ -1,12 +1,11 @@
1 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 5
 use think\Db;
6 6
 
7 7
 /**
8 8
  * 处理相关团队
9
- * @author
10 9
  * @param types 类型
11 10
  * @param types 类型ID
12 11
  * @param type  权限 1只读2读写
@@ -14,53 +13,63 @@ use think\Db;
14 13
  * @param is_del 1 移除操作, 2编辑操作, 3添加操作
15 14
  * @param owner_user_id 操作人
16 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 20
     $userModel = new \app\admin\model\User();
21 21
     $authIds = [];
22
-	switch ($types) {
23
-        case 'crm_leads' : 
22
+    switch ($types) {
23
+        case 'crm_leads' :
24 24
             $data_name = 'leads_id';
25 25
             $authIds = $userModel->getUserByPer('crm', 'leads', 'teamsave');
26 26
             break;
27
-        case 'crm_customer' : 
28
-            $data_name = 'customer_id'; 
27
+        case 'crm_customer' :
28
+            $data_name = 'customer_id';
29 29
             $authIds = $userModel->getUserByPer('crm', 'customer', 'teamsave');
30 30
             break;
31
-        case 'crm_contacts' : 
31
+        case 'crm_contacts' :
32 32
             $data_name = 'contacts_id';
33
-            $authIds = $userModel->getUserByPer('crm', 'contacts', 'teamsave'); 
33
+            $authIds = $userModel->getUserByPer('crm', 'contacts', 'teamsave');
34 34
             break;
35
-        case 'crm_business' : 
36
-            $data_name = 'business_id'; 
35
+        case 'crm_business' :
36
+            $data_name = 'business_id';
37 37
             $authIds = $userModel->getUserByPer('crm', 'business', 'teamsave');
38 38
             break;
39
-        case 'crm_contract' : 
40
-            $data_name = 'contract_id'; 
39
+        case 'crm_contract' :
40
+            $data_name = 'contract_id';
41 41
             $authIds = $userModel->getUserByPer('crm', 'contract', 'teamsave');
42 42
             break;
43
+        case 'crm_receivables' :
44
+            $data_name = 'receivables_id';
45
+            $authIds = $userModel->getUserByPer('crm', 'receivables', 'teamsave');
46
+            break;
43 47
     }
44 48
     if (!is_array($types_id) && $types_id) {
45 49
         $types_id = [$types_id];
46 50
     }
47 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 61
             continue;
53
-        }  
54
-        $type = $type ? : 1;
62
+        }
63
+        $type = $type ?: 1;
55 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 69
         if ($is_del == 1) {
61 70
             $all_rw_user_id = $old_rw_user_id ? array_diff($old_rw_user_id, $user_id) : ''; // 差集
62 71
             $data['rw_user_id'] = $all_rw_user_id ? arrayToString($all_rw_user_id) : ''; //去空
63
-
72
+            
64 73
             $all_ro_user_id = $old_ro_user_id ? array_diff($old_ro_user_id, $user_id) : ''; // 差集
65 74
             $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空           
66 75
         } elseif ($is_del == 2) {
@@ -76,13 +85,13 @@ function teamUserId($types, $types_id, $type, $user_id, $is_del, $owner_user_id,
76 85
         } else {
77 86
             $del_ro_user_id = []; //需要删除的只读
78 87
             $del_rw_user_id = []; //需要删除的读写
79
-            foreach ($user_id as $key=>$val) {
88
+            foreach ($user_id as $key => $val) {
80 89
                 if (in_array($val, $old_ro_user_id) && !in_array($val, $old_rw_user_id) && $type == 2) {
81 90
                     $del_ro_user_id[] = $val;
82 91
                 }
83 92
                 if (in_array($val, $old_rw_user_id) && !in_array($val, $old_ro_user_id) && $type == 1) {
84 93
                     $del_rw_user_id[] = $val;
85
-                }                
94
+                }
86 95
             }
87 96
             if ($type == 2) {
88 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,22 +99,40 @@ function teamUserId($types, $types_id, $type, $user_id, $is_del, $owner_user_id,
90 99
                 $data['rw_user_id'] = $all_rw_user_id ? arrayToString($all_rw_user_id) : ''; //去空 
91 100
                 if ($del_ro_user_id) {
92 101
                     $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空         
93
-                }                
102
+                }
94 103
             } else {
95 104
                 $all_rw_user_id = $old_rw_user_id ? array_diff($old_rw_user_id, $del_rw_user_id) : $user_id; // 合并
96 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 106
                 $data['ro_user_id'] = $all_ro_user_id ? arrayToString($all_ro_user_id) : ''; //去空 
98 107
                 if ($del_rw_user_id) {
99 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 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,7 +141,7 @@ function getYearByTime($start_time, $end_time)
114 141
     $yearArr = [];
115 142
     $monthArr = monthList($start_time, $end_time);
116 143
     foreach ($monthArr as $v) {
117
-        $yearArr[date('Y',$v)] = date('Y',$v);
144
+        $yearArr[date('Y', $v)] = date('Y', $v);
118 145
     }
119 146
     return $yearArr;
120 147
 }
@@ -125,7 +152,60 @@ function getmonthByTime($start_time, $end_time)
125 152
     $monthList = [];
126 153
     $monthArr = monthList($start_time, $end_time);
127 154
     foreach ($monthArr as $v) {
128
-        $monthList[date('Y',$v)][] = date('m',$v);
155
+        $monthList[date('Y', $v)][] = date('m', $v);
129 156
     }
130 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 查看文件

@@ -5,6 +5,7 @@
5 5
  * @author qifan
6 6
  * @date 2020-12-09
7 7
  */
8
+
8 9
 namespace app\crm\controller;
9 10
 
10 11
 use app\admin\controller\ApiCommon;
@@ -23,17 +24,17 @@ class Activity extends ApiCommon
23 24
     public function _initialize()
24 25
     {
25 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 31
         $request = Request::instance();
31 32
         $a = strtolower($request->action());
32 33
         if (!in_array($a, $action['permission'])) {
33 34
             parent::_initialize();
34 35
         }
35 36
     }
36
-
37
+    
37 38
     /**
38 39
      * 活动列表
39 40
      *
@@ -47,12 +48,12 @@ class Activity extends ApiCommon
47 48
     {
48 49
         $param = $this->param;
49 50
         $param['user_id'] = $this->userInfo['id'];
50
-
51
+        
51 52
         $data = $activityLogic->index($param);
52
-
53
+        
53 54
         return resultArray(['data' => $data]);
54 55
     }
55
-
56
+    
56 57
     /**
57 58
      * 创建活动【跟进记录】
58 59
      *
@@ -66,20 +67,20 @@ class Activity extends ApiCommon
66 67
         if (!checkPerByAction('crm', 'activity', 'save')) {
67 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 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 73
         if (!empty($this->param['next_time']) && strtotime($this->param['next_time']) < time()) {
73 74
             return resultArray(['error' => '下次联系时间不能在当前时间之前!']);
74 75
         }
75
-
76
+        
76 77
         $param = $this->param;
77 78
         $param['user_id'] = $this->userInfo['id'];
78
-
79
+        
79 80
         if (!$activityLogic->save($param)) return resultArray(['error' => '操作失败!']);
80 81
         return resultArray(['data' => '操作成功!']);
81 82
     }
82
-
83
+    
83 84
     /**
84 85
      * 活动详情
85 86
      *
@@ -95,12 +96,12 @@ class Activity extends ApiCommon
95 96
             return resultArray(['error' => '你没有查看跟进记录的权限!']);
96 97
         }
97 98
         if (empty($this->param['activity_id'])) return resultArray(['error' => '请选择跟进记录!']);
98
-
99
+        
99 100
         $data = $activityLogic->read($this->param['activity_id']);
100
-
101
+        
101 102
         return resultArray(['data' => $data]);
102 103
     }
103
-
104
+    
104 105
     /**
105 106
      * 编辑活动【跟进记录】
106 107
      *
@@ -114,21 +115,21 @@ class Activity extends ApiCommon
114 115
         if (!checkPerByAction('crm', 'activity', 'update')) {
115 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 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 124
         $userId = $this->userInfo['id'];
124
-
125
+        
125 126
         if (!$activityLogic->update($param)) return resultArray(['error' => '操作失败!']);
126
-
127
+        
127 128
         $data = $activityLogic->getFollowData($param['activity_id'], $userId);
128
-
129
+        
129 130
         return resultArray(['data' => $data]);
130 131
     }
131
-
132
+    
132 133
     /**
133 134
      * 删除活动【跟进记录】
134 135
      *
@@ -137,15 +138,16 @@ class Activity extends ApiCommon
137 138
      */
138 139
     public function delete(ActivityLogic $activityLogic)
139 140
     {
141
+        $userInfo = $this->userInfo;
140 142
         if (!checkPerByAction('crm', 'activity', 'delete')) {
141 143
             return resultArray(['error' => '你没有删除跟进记录的权限!']);
142 144
         }
143 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 148
         return resultArray(['data' => '操作成功!']);
147 149
     }
148
-
150
+    
149 151
     /**
150 152
      * 获取常用语
151 153
      *
@@ -155,10 +157,10 @@ class Activity extends ApiCommon
155 157
     public function getPhrase(ActivityLogic $activityLogic)
156 158
     {
157 159
         $data = $activityLogic->getPhrase();
158
-
160
+        
159 161
         return resultArray(['data' => $data]);
160 162
     }
161
-
163
+    
162 164
     /**
163 165
      * 设置常用语
164 166
      *
@@ -169,14 +171,14 @@ class Activity extends ApiCommon
169 171
      */
170 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 175
         if (!is_array($this->param['phrase'])) return resultArray(['error' => '参数格式错误!']);
174
-
176
+        
175 177
         if (!$activityLogic->setPhrase($this->param['phrase'])) return resultArray(['error' => '操作失败!']);
176
-
178
+        
177 179
         return resultArray(['data' => '操作成功!']);
178 180
     }
179
-
181
+    
180 182
     /**
181 183
      * 跟进记录权限
182 184
      *
@@ -185,27 +187,29 @@ class Activity extends ApiCommon
185 187
     public function getRecordAuth()
186 188
     {
187 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 193
             'update' => checkPerByAction('crm', 'activity', 'update'),
192 194
             'delete' => checkPerByAction('crm', 'activity', 'delete'),
193 195
         ];
194
-
196
+        
195 197
         return resultArray(['data' => $data]);
196 198
     }
199
+    
197 200
     /**
198 201
      * 导入模板下载
199 202
      * @author      alvin guogaobo
200 203
      * @version     1.0 版本号
201 204
      * @since       2021/4/10 0010 16:01
202 205
      */
203
-    public function excelDownload($save_path = ''){
206
+    public function excelDownload($save_path = '')
207
+    {
204 208
         $param = $this->param;
205 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,157 +220,139 @@ class Activity extends ApiCommon
216 220
      * @version     1.0 版本号
217 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 227
             case 1 :
222 228
                 $field = [
223 229
                     '2' => [
224 230
                         'name' => '所属线索',
225 231
                         'field' => 'activity_type_id',
226
-                        'types' => 'log',
227
-                        'form_type' => 'datetime',
232
+                        'form_type' => 'leads_id',
228 233
                         'is_null' => 1,
229 234
                     ]
230 235
                 ];
236
+                $name = '所属线索';
231 237
                 break;
232 238
             case 3:
233 239
                 $field = [
234 240
                     '2' => [
235 241
                         'name' => '所属联系人',
236 242
                         'field' => 'activity_type_id',
237
-                        'types' => 'log',
238
-                        'form_type' => 'datetime',
243
+                        'form_type' => 'contacts_id',
239 244
                         'is_null' => 1,
240 245
                     ],
241 246
                 ];
247
+                $name = '所属联系人';
242 248
                 break;
243 249
             case 5:
244 250
                 $field = [
245 251
                     '2' => [
246 252
                         'name' => '所属商机',
247 253
                         'field' => 'activity_type_id',
248
-                        'types' => 'log',
249
-                        'form_type' => 'text',
254
+                        'form_type' => 'business_id',
250 255
                         'is_null' => 1,
251
-                    ]
256
+                    ],
252 257
                 ];
258
+                $name = '所属商机';
253 259
                 break;
254 260
             case 6:
255 261
                 $field = [
256 262
                     '2' => [
257 263
                         'name' => '所属合同',
258 264
                         'field' => 'activity_type_id',
259
-                        'types' => 'log',
260
-                        'form_type' => 'text',
265
+                        'form_type' => 'contract_id',
261 266
                         'is_null' => 1,
262 267
                     ],
263 268
                 ];
269
+                $name = '所属合同';
264 270
                 break;
265 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 273
                     '2' => [
282 274
                         'name' => '所属客户',
283 275
                         'field' => 'activity_type_id',
284
-                        'types' => 'log',
285
-                        'form_type' => 'text',
276
+                        'form_type' => 'customer_id',
286 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 281
                 break;
314 282
         }
315 283
         $fields = [
316 284
             '0' => [
317 285
                 'name' => '跟进内容',
318 286
                 'field' => 'content',
319
-                'types' => 'log',
320 287
                 'form_type' => 'text',
321 288
                 'is_null' => 1,
322 289
             ],
323 290
             '1' => [
324 291
                 'name' => '创建人',
325 292
                 'field' => 'create_user_id',
326
-                'types' => 'log',
327 293
                 'form_type' => 'user',
328 294
                 'is_null' => 1,
329 295
             ],
330 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 297
                 'name' => '跟进时间-例:2020-2-1',
339 298
                 'field' => 'next_time',
340
-                'types' => 'log',
341 299
                 'form_type' => 'datetime',
342 300
             ],
343
-            '4' => [
301
+            '3' => [
344 302
                 'name' => '跟进方式',
345 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 320
                 '1' => ['name' => '跟进内容', 'field' => 'content'],
355 321
                 '2' => ['name' => '创建人', 'field' => 'create_user_name'],
356 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 353
         return $field_list;
369 354
     }
355
+    
370 356
     /**
371 357
      * 导入数据
372 358
      *
@@ -374,34 +360,37 @@ class Activity extends ApiCommon
374 360
      * @version     1.0 版本号
375 361
      * @since       2021/4/10 0010 16:27
376 362
      */
377
-    public function excelImport(){
363
+    public function excelImport()
364
+    {
378 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 369
         $excelModel = new \app\admin\model\Excel();
381 370
         $file = request()->file('file');
382
-        switch ($param['label']){
371
+        switch ($param['crmType']) {
383 372
             case 1 :
384
-                $param['types']='crm_leads';
385
-                $param['activity_type']=1;
373
+                $param['types'] = 'crm_leads';
374
+                $param['activity_type'] = 1;
386 375
                 break;
387 376
             case 3:
388
-                $param['types']='crm_contacts';
389
-                $param['activity_type']=3;
377
+                $param['types'] = 'crm_contacts';
378
+                $param['activity_type'] = 3;
390 379
                 break;
391 380
             case 5:
392
-                $param['types']='crm_business';
393
-                $param['activity_type']=5;
381
+                $param['types'] = 'crm_business';
382
+                $param['activity_type'] = 5;
394 383
                 break;
395 384
             case 6:
396
-                $param['types']='crm_contract';
397
-                $param['activity_type']=6;
385
+                $param['types'] = 'crm_contract';
386
+                $param['activity_type'] = 6;
398 387
                 break;
399 388
             case 2:
400
-                $param['types']='crm_customer';
401
-                $param['activity_type']=2;
389
+                $param['types'] = 'crm_customer';
390
+                $param['activity_type'] = 2;
402 391
                 break;
403 392
         }
404
-        $res = $excelModel->ActivityImport($file,$field_list, $param,$this);
393
+        $res = $excelModel->ActivityImport($file, $field_list, $param, $this);
405 394
         if (!$res) {
406 395
             return resultArray(['error' => $excelModel->getError()]);
407 396
         }
@@ -417,16 +406,19 @@ class Activity extends ApiCommon
417 406
      * @version     1.0 版本号
418 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 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 422
         return $data;
431 423
     }
432 424
 }

+ 6
- 1
application/crm/controller/Business.php 查看文件

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

+ 4
- 2
application/crm/controller/BusinessStatus.php 查看文件

@@ -105,7 +105,7 @@ class BusinessStatus extends ApiCommon
105 105
         $businessStatusModel = model('BusinessStatus');
106 106
         $param = $this->param;
107 107
         $userInfo = $this->userInfo;
108
-
108
+        $param['user_id']=$userInfo['id'];
109 109
         $res = $businessStatusModel->updateDataById($param, $param['type_id']);
110 110
         if ($res) {
111 111
             $key = 'BI_queryCache_StatusList_Data';
@@ -156,7 +156,9 @@ class BusinessStatus extends ApiCommon
156 156
     {
157 157
         $businessStatusModel = model('BusinessStatus');
158 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 162
         if (!$data) {
161 163
             return resultArray(['error' => $businessStatusModel->getError()]);
162 164
         } 

+ 34
- 35
application/crm/controller/Contacts.php 查看文件

@@ -175,11 +175,14 @@ class Contacts extends ApiCommon
175 175
                 $delIds[] = $v;
176 176
             }           
177 177
         }
178
+        $dataInfo = $contactsModel->getDataById($v);
178 179
         if ($delIds) {
179 180
             $data = $contactsModel->delDatas($delIds);
180 181
             if (!$data) {
181 182
                 return resultArray(['error' => $contactsModel->getError()]);
182 183
             }
184
+            // 删除联系人扩展数据
185
+            db('crm_contacts_data')->whereIn('contacts_id', $delIds)->delete();
183 186
             //删除跟进记录
184 187
             $recordModel->delDataByTypes(3,$delIds);
185 188
             //删除关联附件
@@ -188,8 +191,8 @@ class Contacts extends ApiCommon
188 191
             $actionRecordModel->delDataById(['types'=>'crm_contacts','action_id'=>$delIds]);
189 192
             $userInfo = $this->userInfo;
190 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 198
         if ($errorMessage) {
@@ -270,44 +273,32 @@ class Contacts extends ApiCommon
270 273
      */ 
271 274
     public function excelDownload($save_path = '') 
272 275
     {
276
+        # 下次升级
273 277
         $param = $this->param;
274 278
         $userInfo = $this->userInfo;
275 279
         $excelModel = new \app\admin\model\Excel();
276
-    
280
+
277 281
         // 导出的字段列表
278 282
         $fieldModel = new \app\admin\model\Field();
279 283
         $fieldParam['types'] = 'crm_contacts';
280 284
         $fieldParam['action'] = 'excel';
281 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,7 +322,7 @@ class Contacts extends ApiCommon
331 322
         $excelModel = new \app\admin\model\Excel();
332 323
         // 导出的字段列表
333 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 327
         $file_name = '5kcrm_contacts_'.date('Ymd');
337 328
 
@@ -533,7 +524,14 @@ class Contacts extends ApiCommon
533 524
         $contactsId = $this->param['contacts_id'];
534 525
 
535 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 536
         $businessIds = Db::name('crm_contacts_business')->where('contacts_id', $contactsId)->column('business_id');
539 537
 
@@ -548,7 +546,8 @@ class Contacts extends ApiCommon
548 546
 
549 547
         $data = [
550 548
             'businessCount' => $businessCount,
551
-            'fileCount'     => $fileCount
549
+            'fileCount'     => $fileCount,
550
+            'memberCount'      => count($teamCount),
552 551
         ];
553 552
 
554 553
         return resultArray(['data' => $data]);

+ 3
- 1
application/crm/controller/Contract.php 查看文件

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

+ 31
- 38
application/crm/controller/Customer.php 查看文件

@@ -82,6 +82,7 @@ class Customer extends ApiCommon
82 82
         $customerModel = model('Customer');
83 83
         $param = $this->param;
84 84
         $userInfo = $this->userInfo;
85
+        $param['user_id'] = $userInfo['id'];
85 86
         $param['create_user_id'] = $userInfo['id'];
86 87
         $param['owner_user_id'] = $userInfo['id'];
87 88
         if ($res = $customerModel->createData($param)) {
@@ -235,11 +236,13 @@ class Customer extends ApiCommon
235 236
             if (!$delRes) {
236 237
                 return resultArray(['error' => $customerModel->getError()]);
237 238
             }
238
-            //删除跟进记录
239
+            // 删除客户扩展数据
240
+            db('crm_customer_data')->whereIn('customer_id', $delIds)->delete();
241
+            // 删除跟进记录
239 242
             $recordModel->delDataByTypes(2, $delIds);
240
-            //删除关联附件
243
+            // 删除关联附件
241 244
             $fileModel->delRFileByModule('crm_customer', $delIds);
242
-            //删除关联操作记录
245
+            // 删除关联操作记录
243 246
             $actionRecordModel->delDataById(['types' => 'crm_customer', 'action_id' => $delIds]);
244 247
             foreach ($dataInfo as $k => $v) {
245 248
                 RecordActionLog($userInfo['id'], 'crm_customer', 'delete', $v['name'], '', '', '删除了客户:' . $v['name']);
@@ -404,7 +407,7 @@ class Customer extends ApiCommon
404 407
         $userId = $userInfo['id'];
405 408
         $customerIds = $this->param['customer_id'];
406 409
         $poolId = $this->param['pool_id'];
407
-
410
+        $customerModel=new \app\crm\model\Customer();
408 411
         # 消息数据
409 412
         $message = [];
410 413
 
@@ -429,7 +432,10 @@ class Customer extends ApiCommon
429 432
 
430 433
                 continue;
431 434
             }
432
-
435
+            if (!$customerModel->checkData($value)) {
436
+                $message[] = '"' . $customerData[$value]['name'] . '"放入公海失败,错误原因:无权限';
437
+                continue;
438
+            }
433 439
             if (isset($customerData[$value]['owner_user_id']) && empty($customerData[$value]['owner_user_id'])) {
434 440
                 $message[] = '将客户《' . $customerData[$value]['name'] . '》放入公海失败,错误原因:已经处于公海!';
435 441
                 unset($customerIds[(int)$key]);
@@ -482,16 +488,16 @@ class Customer extends ApiCommon
482 488
                 'owner_user_id' => 0,
483 489
                 'into_pool_time' => time()
484 490
             ]);
485
-
491
+          
486 492
             # 删除联系人的负责人
487 493
             Db::name('crm_contacts')->whereIn('customer_id', $customerIds)->update(['owner_user_id' => 0]);
488
-
494
+           
489 495
             # 将客户放入公海
490 496
             Db::name('crm_customer_pool_relation')->insertAll($poolRelationData);
491
-
497
+            
492 498
             # 公海操作记录
493 499
             Db::name('crm_customer_pool_record')->insertAll($poolRecordData);
494
-
500
+           
495 501
             # 字段操作记录
496 502
             Db::name('admin_action_record')->insertAll($fieldRecordData);
497 503
 
@@ -767,7 +773,7 @@ class Customer extends ApiCommon
767 773
         $excelModel = new \app\admin\model\Excel();
768 774
         // 导出的字段列表
769 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 778
         $file_name = '5kcrm_customer_' . date('Ymd');
773 779
         
@@ -796,43 +802,30 @@ class Customer extends ApiCommon
796 802
      */
797 803
     public function excelDownload($save_path = '')
798 804
     {
805
+        # 下次升级
799 806
         $param = $this->param;
800 807
         $userInfo = $this->userInfo;
801 808
         $excelModel = new \app\admin\model\Excel();
802
-    
803 809
         // 导入的字段列表
804 810
         $fieldModel = new \app\admin\model\Field();
805 811
         $fieldParam['types'] = 'crm_customer';
806 812
         $fieldParam['action'] = 'excel';
807 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 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 查看文件

@@ -44,213 +44,200 @@ class CustomerPool extends ApiCommon
44 44
                 'export'
45 45
             ]
46 46
         ];
47
-        Hook::listen('check_auth',$action);
47
+        Hook::listen('check_auth', $action);
48 48
         $request = Request::instance();
49 49
         $a = strtolower($request->action());
50 50
         if (!in_array($a, $action['permission'])) {
51 51
             parent::_initialize();
52 52
         }
53 53
     }
54
-
54
+    
55 55
     /**
56 56
      * 公海列表
57 57
      *
58
-     * @author fanqi
59
-     * @since 2021-04-14
60 58
      * @return Json
59
+     * @since 2021-04-14
60
+     * @author fanqi
61 61
      */
62 62
     public function index()
63 63
     {
64 64
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID']);
65
-
65
+        
66 66
         $data = (new CustomerPoolLogic())->getPoolList($this->param);
67
-
67
+        
68 68
         return resultArray(['data' => $data]);
69 69
     }
70
-
70
+    
71 71
     /**
72 72
      * 详情
73 73
      *
74
-     * @author fanqi
75
-     * @since 2021-04-14
76 74
      * @return Json
75
+     * @since 2021-04-14
76
+     * @author fanqi
77 77
      */
78 78
     public function read()
79 79
     {
80 80
         if (empty($this->param['pool_id']) || empty($this->param['customer_id'])) return resultArray(['error' => '参数错误!']);
81
-
81
+        
82 82
         $userInfo = $this->userInfo;
83 83
         $param = $this->param;
84 84
         $param['user_id'] = $userInfo['id'];
85
-
85
+        
86 86
         $data = (new CustomerPoolLogic())->getPoolData($param);
87
-
87
+        
88 88
         return resultArray(['data' => $data]);
89 89
     }
90
-
90
+    
91 91
     /**
92 92
      * 删除公海客户
93 93
      *
94
-     * @author fanqi
95
-     * @since 2021-04-15
96 94
      * @return Json
95
+     * @since 2021-04-15
96
+     * @author fanqi
97 97
      */
98 98
     public function delete()
99 99
     {
100 100
         if (empty($this->param['id'])) return resultArray(['error' => '请选择要删除的客户!']);
101
-
101
+        
102 102
         $this->param['user_id'] = $this->userInfo['id'];
103
-
103
+        
104 104
         $result = (new CustomerPoolLogic())->deletePoolCustomer($this->param);
105
-
105
+        
106 106
         if (!empty($result)) return resultArray(['error' => $result]);
107
-
107
+        
108 108
         return resultArray(['data' => '删除成功!']);
109 109
     }
110
-
110
+    
111 111
     /**
112 112
      * 公海池列表
113 113
      *
114
-     * @author fanqi
115
-     * @since 2021-04-13
116 114
      * @return Json
115
+     * @since 2021-04-13
116
+     * @author fanqi
117 117
      */
118 118
     public function pondList()
119 119
     {
120 120
         $data = (new CustomerPoolLogic())->getPondList(['user_id' => $this->userInfo['id'], 'structure_id' => $this->userInfo['structure_id']]);
121
-
121
+        
122 122
         return resultArray(['data' => $data]);
123 123
     }
124
-
124
+    
125 125
     /**
126 126
      * 公海字段
127 127
      *
128
-     * @author fanqi
129
-     * @since 2021-04-13
130 128
      * @return Json
129
+     * @since 2021-04-13
130
+     * @author fanqi
131 131
      */
132 132
     public function field()
133 133
     {
134 134
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
135
-
135
+        
136 136
         $userInfo = $this->userInfo;
137 137
         $param = $this->param;
138 138
         $param['user_id'] = $userInfo['id'];
139
-
139
+        
140 140
         $data = (new CustomerPoolLogic())->getFieldList($param);
141
-
141
+        
142 142
         return resultArray(['data' => $data]);
143 143
     }
144
-
144
+    
145 145
     /**
146 146
      * 高级筛选字段列表
147 147
      *
148
-     * @author fanqi
149
-     * @since 2021-04-14
150 148
      * @return Json
149
+     * @since 2021-04-14
150
+     * @author fanqi
151 151
      */
152 152
     public function advanced()
153 153
     {
154 154
         if (empty($this->param['types'])) return resultArray(['error' => '缺少模块类型!']);
155
-
155
+        
156 156
         $data = (new CustomerPoolLogic())->getAdvancedFilterFieldList($this->param);
157
-
157
+        
158 158
         return resultArray(['data' => $data]);
159 159
     }
160
-
160
+    
161 161
     /**
162 162
      * 领取公海池客户
163 163
      *
164
-     * @author fanqi
165
-     * @since 2021-04-15
166 164
      * @return Json
165
+     * @since 2021-04-15
166
+     * @author fanqi
167 167
      */
168 168
     public function receive()
169 169
     {
170 170
         if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要领取的公海客户!']);
171
-
171
+        
172 172
         $param = $this->param;
173 173
         $param['user_id'] = $this->userInfo['id'];
174
-
174
+        
175 175
         $result = (new CustomerPoolLogic())->receiveCustomers($param);
176
-
176
+        
177 177
         if (!empty($result)) return resultArray(['error' => $result]);
178
-
178
+        
179 179
         return resultArray(['data' => '领取成功!']);
180 180
     }
181
-
181
+    
182 182
     /**
183 183
      * 分配公海客户
184 184
      *
185
-     * @author fanqi
186
-     * @since 2021-04-15
187 185
      * @return Json
186
+     * @since 2021-04-15
187
+     * @author fanqi
188 188
      */
189 189
     public function distribute()
190 190
     {
191 191
         if (empty($this->param['customer_id'])) return resultArray(['error' => '请选择要分配的公海客户!']);
192 192
         if (empty($this->param['user_id'])) return resultArray(['error' => '请选择要分配的员工!']);
193
-
193
+        
194 194
         $result = (new CustomerPoolLogic())->distributeCustomer($this->param);
195
-
195
+        
196 196
         if (!empty($result)) return resultArray(['error' => $result]);
197
-
197
+        
198 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 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 211
     public function import()
212 212
     {
213
+        
213 214
         $param = $this->param;
214 215
         $userInfo = $this->userInfo;
215 216
         $excelModel = new \app\admin\model\Excel();
216 217
         $param['create_user_id'] = $userInfo['id'];
217
-        $param['owner_user_id'] = $userInfo['id'];
218 218
         $param['deal_time'] = time();
219 219
         $param['types'] = 'crm_customer';
220
+        $param['deal_status'] = '未成交';
220 221
         $file = request()->file('file');
221 222
         // $res = $excelModel->importExcel($file, $param, $this);
222 223
         $res = $excelModel->batchImportData($file, $param, $this);
223
-        RecordActionLog($userInfo['id'],'crm_customer','excel','导入公海客户','','','导入公海客户');
224
+        RecordActionLog($userInfo['id'], 'crm_customer', 'excel', '导入公海客户', '', '', '导入公海客户');
224 225
         return resultArray(['data' => $excelModel->getError()]);
225 226
     }
226
-
227
+    
227 228
     // 导出
228 229
     public function export()
229 230
     {
230 231
         $param = $this->param;
231 232
         $userInfo = $this->userInfo;
232
-        $action_name='导出全部';
233
+        $action_name = '导出全部';
233 234
         if ($param['customer_id']) {
234
-            $action_name='导出选中';
235
+            $action_name = '导出选中';
235 236
         }
236 237
         $param['is_excel'] = 1;
237 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 242
         $file_name = '5kcrm_customer_' . date('Ymd');
256 243
         $model = model('Customer');
@@ -259,7 +246,7 @@ class CustomerPool extends ApiCommon
259 246
         $page = $param['page'] ?: 1;
260 247
         unset($param['page']);
261 248
         unset($param['export_queue_index']);
262
-      
249
+//        p($field_list);
263 250
         return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function ($page, $limit) use ($model, $param, $field_list) {
264 251
             $param['page'] = $page;
265 252
             $param['limit'] = $limit;
@@ -267,98 +254,146 @@ class CustomerPool extends ApiCommon
267 254
             $data['list'] = $model->exportHandle($data['list'], $field_list, 'customer');
268 255
             return $data;
269 256
         });
270
-        RecordActionLog($userInfo['id'],'crm_customer','excelexport',$action_name,'','','导出客户');
257
+        RecordActionLog($userInfo['id'], 'crm_customer', 'excelexport', $action_name, '', '', '导出客户');
271 258
         return resultArray(['error' => 'error']);
272 259
     }
273
-
260
+    
274 261
     /**
275 262
      * 公海权限
276 263
      *
277
-     * @author fanqi
278
-     * @since 2021-04-14
279 264
      * @return Json
265
+     * @since 2021-04-14
266
+     * @author fanqi
280 267
      */
281 268
     public function authority()
282 269
     {
283 270
         $param = $this->param;
284 271
         $param['user_id'] = $this->userInfo['id'];
285 272
         $param['structure_id'] = $this->userInfo['structure_id'];
286
-
273
+        
287 274
         $data = (new CustomerPoolLogic())->getAuthorityData($param);
288
-
275
+        
289 276
         return resultArray(['data' => $data]);
290 277
     }
291
-
278
+    
292 279
     /**
293 280
      * 公海字段样式
294 281
      *
295
-     * @author fanqi
296
-     * @since 2021-04-22
297 282
      * @return Json
283
+     * @since 2021-04-22
284
+     * @author fanqi
298 285
      */
299 286
     public function fieldConfig()
300 287
     {
301 288
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
302
-
289
+        
303 290
         $param = $this->param;
304 291
         $userInfo = $this->userInfo;
305 292
         $param['user_id'] = $userInfo['id'];
306
-
293
+        
307 294
         $data = (new CustomerPoolLogic())->getFieldConfigIndex($param);
308
-
295
+        
309 296
         return resultArray(['data' => $data]);
310 297
     }
311
-
298
+    
312 299
     /**
313 300
      * 设置公海字段宽度
314 301
      *
315
-     * @author fanqi
316
-     * @since 2021-04-22
317 302
      * @return Json
303
+     * @since 2021-04-22
304
+     * @author fanqi
318 305
      */
319 306
     public function setFieldWidth()
320 307
     {
321 308
         if (empty($this->param['pool_id'])) return resultArray(['error' => '缺少公海ID!']);
322 309
         if (empty($this->param['field'])) return resultArray(['error' => '缺少字段名称!']);
323 310
         if (empty($this->param['width'])) return resultArray(['error' => '缺少宽度值!']);
324
-
311
+        
325 312
         $param = $this->param;
326 313
         $userInfo = $this->userInfo;
327 314
         $param['user_id'] = $userInfo['id'];
328
-
315
+        
329 316
         (new CustomerPoolLogic())->setFieldWidth($param);
330
-
317
+        
331 318
         return resultArray(['data' => '操作成功!']);
332 319
     }
333
-
320
+    
334 321
     /**
335 322
      * 设置公海字段样式
336 323
      *
337
-     * @author fanqi
338
-     * @since 2021-04-22
339 324
      * @return Json
325
+     * @since 2021-04-22
326
+     * @author fanqi
340 327
      */
341 328
     public function setFieldConfig()
342 329
     {
343 330
         if (empty($this->param['pool_id'])) return resultArray(['缺少公海ID!']);
344 331
         if (empty($this->param['value']) && empty($this->param['hide_value'])) return resultArray(['error' => '字段参数错误!']);
345
-
332
+        
346 333
         $param = $this->param;
347 334
         $userInfo = $this->userInfo;
348 335
         $param['user_id'] = $userInfo['id'];
349
-
336
+        
350 337
         (new CustomerPoolLogic())->setFieldConfig($param);
351
-
338
+        
352 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 359
         $fieldParam['types'] = 'crm_customer';
358 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 查看文件

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

+ 430
- 147
application/crm/controller/Invoice.php 查看文件

@@ -11,6 +11,7 @@ namespace app\crm\controller;
11 11
 use app\admin\controller\ApiCommon;
12 12
 use app\admin\model\Message;
13 13
 use app\admin\model\User;
14
+use app\admin\traits\FieldVerificationTrait;
14 15
 use app\crm\logic\InvoiceLogic;
15 16
 use app\crm\model\NumberSequence;
16 17
 use app\crm\traits\AutoNumberTrait;
@@ -20,8 +21,8 @@ use think\Request;
20 21
 
21 22
 class Invoice extends ApiCommon
22 23
 {
23
-    use AutoNumberTrait;
24
-
24
+    use AutoNumberTrait, FieldVerificationTrait;
25
+    
25 26
     /**
26 27
      * 用于判断权限
27 28
      * @permission 无限制
@@ -32,16 +33,16 @@ class Invoice extends ApiCommon
32 33
     {
33 34
         $action = [
34 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 39
         $request = Request::instance();
39 40
         $a = strtolower($request->action());
40 41
         if (!in_array($a, $action['permission'])) {
41 42
             parent::_initialize();
42 43
         }
43 44
     }
44
-
45
+    
45 46
     /**
46 47
      * 列表
47 48
      *
@@ -53,12 +54,12 @@ class Invoice extends ApiCommon
53 54
     {
54 55
         $param = $this->param;
55 56
         $param['user_id'] = $this->userInfo['id'];
56
-
57
-        $data = $invoiceLogic->index($param, true);
58
-
57
+        
58
+        $data = $invoiceLogic->index($param);
59
+        
59 60
         return resultArray(['data' => $data]);
60 61
     }
61
-
62
+    
62 63
     /**
63 64
      * 创建
64 65
      *
@@ -70,14 +71,14 @@ class Invoice extends ApiCommon
70 71
      */
71 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 83
         $examineStatus = $param['examineStatus'];
83 84
         # 删除无用参数
@@ -87,11 +88,11 @@ class Invoice extends ApiCommon
87 88
         unset($param['contract_number']);
88 89
         # 设置创建人负责人ID
89 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 97
         $numberInfo = [];
97 98
         if (empty($param['invoice_apple_number'])) {
@@ -103,7 +104,7 @@ class Invoice extends ApiCommon
103 104
         if ($invoiceLogic->getInvoiceId(['invoice_apple_number' => $param['invoice_apple_number']])) {
104 105
             return resultArray(['error' => '发票编号重复!']);
105 106
         }
106
-
107
+        
107 108
         if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) {
108 109
             $examineStepModel = new \app\admin\model\ExamineStep();
109 110
             # 审核判断(是否有符合条件的审批流)
@@ -121,22 +122,120 @@ class Invoice extends ApiCommon
121 122
             if ($examineFlowData['config'] == 1) {
122 123
                 # 固定审批流
123 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 127
                 $param['order_id'] = 1;
127 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 132
             if (!$check_user_id) {
132 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 136
         } else {
136 137
             # 审批流停用,将状态改为审核通过
137 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 239
         if (!$invoice_id = $invoiceLogic->save($param)) {
141 240
             return resultArray(['error' => '创建失败!']);
142 241
         }
@@ -144,7 +243,7 @@ class Invoice extends ApiCommon
144 243
         (new Message())->send(
145 244
             Message::INVOICE_TO_DO,
146 245
             [
147
-                'title'     => $param['invoice_apple_number'],
246
+                'title' => $param['invoice_apple_number'],
148 247
                 'action_id' => $invoice_id
149 248
             ],
150 249
             $send_user_id
@@ -152,24 +251,30 @@ class Invoice extends ApiCommon
152 251
         # 更新crm_number_sequence表中的last_date、create_time字段
153 252
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
154 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 257
         $checkUserIds = db('crm_invoice')->where('invoice_id', $invoice_id)->value('check_user_id');
159 258
         $checkUserIdArray = stringToArray($checkUserIds);
160 259
         $dealtData = [];
161
-        foreach ($checkUserIdArray AS $kk => $vv) {
260
+        foreach ($checkUserIdArray as $kk => $vv) {
162 261
             $dealtData[] = [
163
-                'types'    => 'crm_invoice',
262
+                'types' => 'crm_invoice',
164 263
                 'types_id' => $invoice_id,
165
-                'user_id'  => $vv
264
+                'user_id' => $vv
166 265
             ];
167 266
         }
168 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 275
         return resultArray(['data' => '创建成功!']);
171 276
     }
172
-
277
+    
173 278
     /**
174 279
      * 详情
175 280
      *
@@ -183,33 +288,33 @@ class Invoice extends ApiCommon
183 288
     public function read(InvoiceLogic $invoiceLogic)
184 289
     {
185 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 294
         $data = $invoiceLogic->read($invoiceId, $isUpdate);
190 295
         $readStatus = false;
191
-
296
+        
192 297
         # 角色权限
193 298
         $authArray = db('admin_access')->alias('access')
194 299
             ->join('__ADMIN_GROUP__ group', 'group.id = access.group_id', 'left')
195 300
             ->where('access.user_id', $userInfo['id'])->column('group.rules');
196
-
301
+        
197 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 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 307
             if (!empty($value) && in_array($invoiceReadAuthId, stringToArray($value))) $readStatus = true;
203 308
         }
204
-
309
+        
205 310
         if (!isSuperAdministrators($userInfo['id']) && $readStatus === false) {
206 311
             $authData['dataAuth'] = (int)0;
207 312
             return resultArray(['data' => $authData]);
208 313
         }
209
-
314
+        
210 315
         return resultArray(['data' => $data]);
211 316
     }
212
-
317
+    
213 318
     /**
214 319
      * 编辑
215 320
      *
@@ -222,11 +327,11 @@ class Invoice extends ApiCommon
222 327
     public function update(InvoiceLogic $invoiceLogic)
223 328
     {
224 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 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 336
         $examineStatus = $param['examineStatus'];
232 337
         # 删除无用参数
@@ -236,17 +341,17 @@ class Invoice extends ApiCommon
236 341
         unset($param['contract_number']);
237 342
         # 设置负责人ID
238 343
         $param['update_time'] = time();
239
-
344
+        
240 345
         # 已进行审批,不能编辑
241 346
         // $dataInfo = $invoiceLogic->read($param['invoice_id'], '');
242 347
         // if (!$dataInfo) {
243 348
         //     $this->error = '数据不存在或已删除';
244 349
         //     return false;
245 350
         // }            
246
-     
351
+        
247 352
         $checkStatus = $invoiceLogic->getExamineStatus($param['invoice_id']);
248 353
         if (!in_array($checkStatus, ['3', '4', '5', '6'])) return resultArray(['error' => '当前状态为审批中或已审批通过,不可编辑']);
249
-
354
+        
250 355
         # 自动设置发票编号
251 356
         $numberInfo = [];
252 357
         if (empty($param['invoice_apple_number'])) {
@@ -254,16 +359,16 @@ class Invoice extends ApiCommon
254 359
             if (empty($numberInfo['number'])) return resultArray(['error' => '请填写发票编号!']);
255 360
             $param['invoice_apple_number'] = $numberInfo['number'];
256 361
         }
257
-
362
+        
258 363
         # 检查发票编号是否重复
259 364
         $invoiceWhere['invoice_apple_number'] = $param['invoice_apple_number'];
260 365
         $invoiceWhere['invoice_id'] = ['neq', $this->param['invoice_id']];
261 366
         if ($invoiceLogic->getInvoiceId($invoiceWhere)) return resultArray(['error' => '发票编号重复!']);
262
-
367
+        
263 368
         if ($param['is_draft'] || (!empty($param['check_status']) && $param['check_status'] == 5)) {
264 369
             //保存为草稿
265 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 372
         } else {
268 373
             # 将合同审批状态至为待审核,提交后重新进行审批
269 374
             if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) {
@@ -283,59 +388,164 @@ class Invoice extends ApiCommon
283 388
                 if ($examineFlowData['config'] == 1) {
284 389
                     # 固定审批流
285 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 393
                     $param['order_id'] = 1;
289 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 398
                 if ($param['is_draft']) {
294 399
                     //保存为草稿
295 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 402
                 } else {
298 403
                     if (!$check_user_id) {
299 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 407
                     $param['check_status'] = 0;
303 408
                 }
304 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 510
         if (!$invoiceLogic->update($param)) {
309 511
             return resultArray(['error' => '编辑失败!']);
310 512
         }
311
-
513
+        
312 514
         //将审批记录至为无效
313 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 518
         # 更新crm_number_sequence表中的last_date、create_time字段
317 519
         if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
318 520
         //修改记录
319 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 524
         db('crm_dealt_relation')->where(['types' => ['eq', 'crm_invoice'], 'types_id' => ['eq', $param['invoice_id']]])->delete();
323 525
         # 创建待办事项的关联数据
324 526
         $checkUserIds = db('crm_invoice')->where('invoice_id', $param['invoice_id'])->value('check_user_id');
325 527
         $checkUserIdArray = stringToArray($checkUserIds);
326 528
         $dealtData = [];
327
-        foreach ($checkUserIdArray AS $kk => $vv) {
529
+        foreach ($checkUserIdArray as $kk => $vv) {
328 530
             $dealtData[] = [
329
-                'types'    => 'crm_invoice',
531
+                'types' => 'crm_invoice',
330 532
                 'types_id' => $param['invoice_id'],
331
-                'user_id'  => $vv
533
+                'user_id' => $vv
332 534
             ];
333 535
         }
334 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 546
         return resultArray(['data' => '编辑成功!']);
337 547
     }
338
-
548
+    
339 549
     /**
340 550
      * 删除
341 551
      *
@@ -349,39 +559,39 @@ class Invoice extends ApiCommon
349 559
     {
350 560
         $actionRecordModel = new \app\admin\model\ActionRecord();
351 561
         $fileModel = new \app\admin\model\File();
352
-        $idArray  = $this->param['id'];
562
+        $idArray = $this->param['id'];
353 563
         $userinfo = $this->userInfo['id'];
354
-
564
+        
355 565
         if (!is_array($idArray)) return resultArray(['error' => '发票ID类型错误!']);
356
-
566
+        
357 567
         $idString = implode(',', $idArray);
358
-        $status   = true;
359
-
568
+        $status = true;
569
+        
360 570
         if (!isSuperAdministrators($userinfo['id'])) {
361 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 574
                     $status = false;
365 575
                     break;
366 576
                 }
367 577
             }
368 578
         }
369
-
579
+        
370 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 582
         if (!$invoiceLogic->delete($idArray)) return resultArray(['error' => '删除失败!']);
373
-
583
+        
374 584
         # 删除附件
375 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 588
         $userInfo = $this->userInfo;
379 589
         foreach ($dataInfo as $k => $v) {
380 590
             RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['invoice_apple_number'], '', '', '删除了回款:' . $v['invoice_apple_number']);
381 591
         }
382 592
         return resultArray(['data' => '删除成功!']);
383 593
     }
384
-
594
+    
385 595
     /**
386 596
      * 转移(变更负责人)
387 597
      *
@@ -391,23 +601,23 @@ class Invoice extends ApiCommon
391 601
     public function transfer(InvoiceLogic $invoiceLogic)
392 602
     {
393 603
         $ownerUserId = $this->param['owner_user_id'];
394
-        $invoiceIds  = $this->param['invoice_id'];
604
+        $invoiceIds = $this->param['invoice_id'];
395 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 609
         if (!is_array($invoiceIds)) return resultArray(['error' => '发票ID类型错误!']);
400
-
610
+        
401 611
         if ($invoiceLogic->transfer($invoiceIds, $ownerUserId) === false) return resultArray(['error' => '操作失败!']);
402 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 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 618
         return resultArray(['data' => '操作成功!']);
409 619
     }
410
-
620
+    
411 621
     /**
412 622
      * 设置开票
413 623
      *
@@ -416,22 +626,22 @@ class Invoice extends ApiCommon
416 626
      */
417 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 630
 //        if (empty($this->param['invoice_number']))    return resultArray(['error' => '请填写发票号码!']);
421 631
 //        if (empty($this->param['logistics_number']))  return resultArray(['error' => '请填写物流单号!']);
422 632
 //        if (empty($this->param['real_invoice_date'])) return resultArray(['error' => '请选择开票日期!']);
423
-
633
+        
424 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 637
         $this->param['invoice_status'] = 1;
428
-
638
+        
429 639
         # 设置开票信息
430 640
         if (!$invoiceLogic->setInvoice($this->param)) return resultArray(['error' => '操作失败!']);
431
-
641
+        
432 642
         return resultArray(['data' => '操作成功!']);
433 643
     }
434
-
644
+    
435 645
     /**
436 646
      * 审核
437 647
      *
@@ -443,54 +653,54 @@ class Invoice extends ApiCommon
443 653
      */
444 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 660
         $examineRecordModel = new \app\admin\model\ExamineRecord();
451
-        $examineFlowModel   = new \app\admin\model\ExamineFlow();
452
-
661
+        $examineFlowModel = new \app\admin\model\ExamineFlow();
662
+        
453 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 666
         $invoiceData['check_status'] = 1;
457 667
         # 权限判断
458 668
         if (!$examineStepModel->checkExamine($user_id, 'crm_invoice', $param['id'])) {
459 669
             return resultArray(['error' => $examineStepModel->getError()]);
460 670
         }
461
-
671
+        
462 672
         # 审批主体详情
463 673
         $dataInfo = $invoiceLogic->getExamineInfo($param['id']);
464 674
         $flowInfo = $examineFlowModel->getDataById($dataInfo['flow_id']);
465
-
675
+        
466 676
         # 1审批结束
467 677
         $is_end = 0;
468
-
678
+        
469 679
         # 1通过,0驳回
470 680
         $status = !empty($param['status']) && $param['status'] == 1 ? 1 : 0;
471
-
681
+        
472 682
         # 审批记录
473
-        $checkData                  = [];
683
+        $checkData = [];
474 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 693
         if ($status == 1) {
484 694
             if ($flowInfo['config'] == 1) {
485 695
                 # 固定流程
486 696
                 # 获取下一审批信息
487 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 700
                 if (!$next_user_ids) {
491 701
                     $is_end = 1;
492 702
                     # 审批结束
493
-                    $checkData['check_status']    = !empty($status) ? 2 : 3;
703
+                    $checkData['check_status'] = !empty($status) ? 2 : 3;
494 704
                     $invoiceData['check_user_id'] = '';
495 705
                 } else {
496 706
                     # 修改主体相关审批信息
@@ -498,17 +708,17 @@ class Invoice extends ApiCommon
498 708
                 }
499 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 713
                 if ($is_end !== 1 && empty($check_user_id)) {
504 714
                     return resultArray(['error' => '请选择下一审批人']);
505 715
                 }
506 716
                 $invoiceData['check_user_id'] = arrayToString($param['check_user_id']);
507 717
             }
508 718
             if ($is_end == 1) {
509
-                $checkData['check_status']    = !empty($status) ? 2 : 3;
719
+                $checkData['check_status'] = !empty($status) ? 2 : 3;
510 720
                 $invoiceData['check_user_id'] = '';
511
-                $invoiceData['check_status']  = 2;
721
+                $invoiceData['check_status'] = 2;
512 722
             }
513 723
         } else {
514 724
             # 审批驳回
@@ -516,19 +726,19 @@ class Invoice extends ApiCommon
516 726
             $invoiceData['check_status'] = 3;
517 727
         }
518 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 730
         $resContract = $invoiceLogic->setExamineInfo($invoiceData);
521 731
         if ($resContract) {
522 732
             # 审批记录
523 733
             $examineRecordModel->createData($checkData);
524
-
734
+            
525 735
             # 发送站内信
526 736
             if ($is_end == 1 && !empty($status)) {
527 737
                 # 审批流程结束,将审批通过消息告知负责人
528 738
                 (new Message())->send(
529 739
                     Message::INVOICE_PASS,
530 740
                     [
531
-                        'title'     => $dataInfo['invoice_apple_number'],
741
+                        'title' => $dataInfo['invoice_apple_number'],
532 742
                         'action_id' => $param['id']
533 743
                     ],
534 744
                     stringToArray($dataInfo['owner_user_id'])
@@ -540,7 +750,7 @@ class Invoice extends ApiCommon
540 750
                         Message::INVOICE_TO_DO,
541 751
                         [
542 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 754
                             'action_id' => $param['id']
545 755
                         ],
546 756
                         stringToArray($invoiceData['check_user_id'])
@@ -550,20 +760,20 @@ class Invoice extends ApiCommon
550 760
                     (new Message())->send(
551 761
                         Message::INVOICE_REJECT,
552 762
                         [
553
-                            'title'     => $dataInfo['invoice_apple_number'],
763
+                            'title' => $dataInfo['invoice_apple_number'],
554 764
                             'action_id' => $param['id']
555 765
                         ],
556 766
                         stringToArray($dataInfo['owner_user_id'])
557 767
                     );
558 768
                 }
559 769
             }
560
-
770
+            
561 771
             return resultArray(['data' => '审批成功']);
562 772
         } else {
563 773
             return resultArray(['error' => '审批失败,请重试!']);
564 774
         }
565 775
     }
566
-
776
+    
567 777
     /**
568 778
      * 撤销审核
569 779
      *
@@ -576,15 +786,15 @@ class Invoice extends ApiCommon
576 786
     public function revokeCheck(InvoiceLogic $invoiceLogic)
577 787
     {
578 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 794
         if (empty($invoiceId)) return resultArray(['error' => '请选择要撤回审核的发票!']);
585
-
795
+        
586 796
         $examineInfo = $invoiceLogic->getExamineInfo($invoiceId);
587
-
797
+        
588 798
         if ($examineInfo['check_status'] == 2) {
589 799
             return resultArray(['error' => '已审批结束,不能撤销']);
590 800
         }
@@ -596,18 +806,18 @@ class Invoice extends ApiCommon
596 806
         if ($examineInfo['owner_user_id'] !== $user_id && !in_array($user_id, $admin_user_ids)) {
597 807
             return resultArray(['error' => '没有权限']);
598 808
         }
599
-
809
+        
600 810
         # 修改发票审核状态
601 811
         if (!$invoiceLogic->update(['invoice_id' => $invoiceId, 'check_status' => 4, 'check_user_id' => '', 'flow_user_id' => ''])) {
602 812
             return resultArray(['error' => '操作失败!']);
603 813
         }
604
-
814
+        
605 815
         # 添加撤销审核的记录
606 816
         $invoiceLogic->createExamineRecord($invoiceId, $examineInfo, $realname, $content, $user_id);
607
-
817
+        
608 818
         return resultArray(['data' => '操作成功!']);
609 819
     }
610
-
820
+    
611 821
     /**
612 822
      * table栏数量统计
613 823
      *
@@ -617,13 +827,13 @@ class Invoice extends ApiCommon
617 827
     public function count()
618 828
     {
619 829
         if (empty($this->param['invoice_id'])) return resultArray(['error' => '参数错误!']);
620
-
830
+        
621 831
         # 附件
622 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 834
         return resultArray(['data' => ['fileCount' => $fileCount]]);
625 835
     }
626
-
836
+    
627 837
     /**
628 838
      * 重置开票信息
629 839
      *
@@ -635,13 +845,86 @@ class Invoice extends ApiCommon
635 845
         if (empty($this->param['invoice_id'])) resultArray(['error' => '参数错误!']);
636 846
         $userInfo = $this->userInfo;
637 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 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 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 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 查看文件

@@ -181,6 +181,8 @@ class Leads extends ApiCommon
181 181
             if (!$data) {
182 182
                 return resultArray(['error' => $leadsModel->getError()]);
183 183
             }
184
+            // 删除线索扩展数据
185
+            db('crm_leads_data')->whereIn('leads_id', $delIds)->delete();
184 186
             //删除跟进记录
185 187
             $recordModel->delDataByTypes(1, $delIds);
186 188
             //删除关联附件
@@ -346,7 +348,7 @@ class Leads extends ApiCommon
346 348
      */
347 349
     public function excelDownload($save_path = '')
348 350
     {
349
-    
351
+        # 下次升级使用
350 352
         $param = $this->param;
351 353
         $userInfo = $this->userInfo;
352 354
         $excelModel = new \app\admin\model\Excel();
@@ -355,37 +357,21 @@ class Leads extends ApiCommon
355 357
         $fieldParam['types'] = 'crm_leads';
356 358
         $fieldParam['action'] = 'excel';
357 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,7 +395,7 @@ class Leads extends ApiCommon
409 395
         $excelModel = new \app\admin\model\Excel();
410 396
         // 导出的字段列表
411 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 400
         $file_name = '5kcrm_leads_' . date('Ymd');
415 401
 

+ 137
- 273
application/crm/controller/Message.php 查看文件

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

+ 19
- 29
application/crm/controller/Product.php 查看文件

@@ -187,43 +187,31 @@ class Product extends ApiCommon
187 187
      */ 
188 188
     public function excelDownload($save_path = '') 
189 189
     {
190
+        # 下次升级
190 191
         $param = $this->param;
191 192
         $userInfo = $this->userInfo;
192 193
         $excelModel = new \app\admin\model\Excel();
193
-    
194
+
194 195
         // 导出的字段列表
195 196
         $fieldModel = new \app\admin\model\Field();
196 197
         $fieldParam['types'] = 'crm_product';
197 198
         $fieldParam['action'] = 'excel';
198 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 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,7 +234,7 @@ class Product extends ApiCommon
246 234
         $excelModel = new \app\admin\model\Excel();
247 235
         // 导出的字段列表
248 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 239
         $file_name = '5kcrm_product_'.date('Ymd');
252 240
         
@@ -337,6 +325,8 @@ class Product extends ApiCommon
337 325
             if ($res == count($delIds)) {
338 326
                 // 事务提交
339 327
                 ProductModel::commit();
328
+                // 删除客户扩展数据
329
+                db('crm_product_data')->whereIn('product_id', $delIds)->delete();
340 330
                 // 删除关联附件
341 331
                 (new FileModel)->delRFileByModule('crm_product', $delIds);
342 332
                 // 操作记录

+ 4
- 2
application/crm/controller/ProductCategory.php 查看文件

@@ -86,7 +86,7 @@ class ProductCategory extends ApiCommon
86 86
         $categoryModel = model('ProductCategory');
87 87
         $param = $this->param;
88 88
         $userInfo = $this->userInfo;
89
-
89
+        $param['user_id']=$userInfo['id'];
90 90
         $res = $categoryModel->updateDataById($param, $param['id']); 
91 91
         if ($res) {
92 92
             return resultArray(['data' => '编辑成功']);
@@ -105,7 +105,9 @@ class ProductCategory extends ApiCommon
105 105
     {
106 106
         $categoryModel = model('ProductCategory');
107 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 111
         if (!$data) {
110 112
             return resultArray(['error' => $categoryModel->getError()]);
111 113
         } 

+ 12
- 2
application/crm/controller/Receivables.php 查看文件

@@ -348,6 +348,8 @@ class Receivables extends ApiCommon
348 348
             if (!$data) {
349 349
                 return resultArray(['error' => $receivablesModel->getError()]);
350 350
             }
351
+            // 删除回款扩展数据
352
+            db('crm_receivables_data')->whereIn('receivables_id', $delIds)->delete();
351 353
             //删除跟进记录
352 354
             $recordModel->delDataByTypes(7,$delIds);
353 355
             # 删除附件
@@ -642,10 +644,18 @@ class Receivables extends ApiCommon
642 644
     public function count()
643 645
     {
644 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 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 查看文件

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

+ 150
- 54
application/crm/controller/Setting.php 查看文件

@@ -38,7 +38,7 @@ class Setting extends ApiCommon
38 38
             parent::_initialize();
39 39
         }
40 40
     }
41
-
41
+    
42 42
     /**
43 43
      * 客户相关配置
44 44
      *
@@ -63,7 +63,7 @@ class Setting extends ApiCommon
63 63
             return resultArray(['error' => $configModel->getError()]);
64 64
         }
65 65
     }
66
-
66
+    
67 67
     /**
68 68
      * 客户相关配置(详情)
69 69
      *
@@ -75,7 +75,7 @@ class Setting extends ApiCommon
75 75
         $data = $configModel->getData();
76 76
         return resultArray(['data' => $data]);
77 77
     }
78
-
78
+    
79 79
     /**
80 80
      * 相关团队列表
81 81
      *
@@ -107,15 +107,18 @@ class Setting extends ApiCommon
107 107
             case 'crm_contract' :
108 108
                 $dataModel = new \app\crm\model\Contract();
109 109
                 break;
110
+            case 'crm_receivables' :
111
+                $dataModel = new \app\crm\model\Receivables();
112
+                break;
110 113
         }
111 114
         $resData = $dataModel->getDataById($param['types_id']);
112 115
         $ro_user_ids = $resData['ro_user_id'] ? array_filter(explode(',', $resData['ro_user_id'])) : []; //只读权限
113 116
         $rw_user_ids = $resData['rw_user_id'] ? array_filter(explode(',', $resData['rw_user_id'])) : []; //读写权限
114
-
117
+        
115 118
         $ro_user_arr = [];
116 119
         $rw_user_arr = [];
117 120
         $owner_user_arr = ['1' => ['user_id' => $resData['owner_user_id'], 'type' => 0, 'group_name' => '负责人', 'authority' => '负责人权限']]; //负责人
118
-
121
+        
119 122
         //转换为二维数组
120 123
         foreach ($ro_user_ids as $k => $v) {
121 124
             $ro_user_arr[$k]['user_id'] = $v;
@@ -123,16 +126,17 @@ class Setting extends ApiCommon
123 126
             $ro_user_arr[$k]['group_name'] = '普通成员';
124 127
             $ro_user_arr[$k]['authority'] = '只读';
125 128
         }
126
-
129
+        
127 130
         foreach ($rw_user_ids as $k => $v) {
128 131
             $rw_user_arr[$k]['user_id'] = $v;
129 132
             $rw_user_arr[$k]['type'] = 2;
130 133
             $rw_user_arr[$k]['group_name'] = '普通成员';
131 134
             $rw_user_arr[$k]['authority'] = '读写';
132 135
         }
133
-
136
+        
134 137
         $user_list = array_merge($owner_user_arr, $rw_user_arr, $ro_user_arr);
135 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 140
         foreach ($user_list as $k => $v) {
137 141
             if ($v['user_id']) {
138 142
                 $userInfo = [];
@@ -140,12 +144,13 @@ class Setting extends ApiCommon
140 144
                 $userInfo['group_name'] = $v['group_name'];
141 145
                 $userInfo['authority'] = $v['authority'];
142 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 148
                 $new_user_list[] = $userInfo;
144 149
             }
145 150
         }
146 151
         return resultArray(['data' => $new_user_list]);
147 152
     }
148
-
153
+    
149 154
     /**
150 155
      * 退出团队
151 156
      *
@@ -162,21 +167,21 @@ class Setting extends ApiCommon
162 167
         if (!in_array($this->param['types'], ['crm_customer', 'crm_contacts', 'crm_business', 'crm_contract'])) {
163 168
             return resultArray(['error' => '参数错误']);
164 169
         }
165
-
170
+        
166 171
         $userId = $this->userInfo['id'];
167
-
172
+        
168 173
         $primaryKey = ['crm_customer' => 'customer_id', 'crm_contacts' => 'contacts_id', 'crm_business' => 'business_id', 'crm_contract' => 'contract_id'];
169
-
174
+        
170 175
         $data = Db::name($this->param['types'])->field([$primaryKey[$this->param['types']], 'ro_user_id', 'rw_user_id', 'owner_user_id,name'])
171 176
             ->where($primaryKey[$this->param['types']], $this->param['types_id'])->find();
172
-
177
+        
173 178
         if ($data['owner_user_id'] == $userId) return resultArray(['error' => '负责人不能退出团队!']);
174
-
175
-
179
+        
180
+        
176 181
         $data[$primaryKey[$this->param['types']]] = $this->param['types_id'];
177 182
         $data['ro_user_id'] = str_replace(',' . $userId, '', $data['ro_user_id']);
178 183
         $data['rw_user_id'] = str_replace(',' . $userId, '', $data['rw_user_id']);
179
-
184
+        
180 185
         if (!Db::name($this->param['types'])->update($data)) {
181 186
             return resultArray(['error' => '操作失败!']);
182 187
         }
@@ -191,7 +196,7 @@ class Setting extends ApiCommon
191 196
             case 'crm_contract':
192 197
                 $type = Message::CONTRACT_END;
193 198
                 break;
194
-
199
+            
195 200
         }
196 201
         //站内信
197 202
         $send_user_id = stringToArray($userId);
@@ -207,7 +212,7 @@ class Setting extends ApiCommon
207 212
         }
208 213
         return resultArray(['data' => '操作成功!']);
209 214
     }
210
-
215
+    
211 216
     /**
212 217
      * 相关团队创建
213 218
      *
@@ -286,13 +291,62 @@ class Setting extends ApiCommon
286 291
                     }
287 292
                     $message_type = Message::TEAM_CONTRACT;
288 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 343
             if ($error !== true) {
291 344
                 $param['type_id'] = $v;
292 345
                 $param['type'] = $param['type'] ?: 1;
293 346
                 $param['is_del'] = $param['is_del'] ?: 3;
294 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 350
                     $res = $settingModel->createTeamData($param);
297 351
                     if (!$res) {
298 352
                         $errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
@@ -305,14 +359,15 @@ class Setting extends ApiCommon
305 359
                             ],
306 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 366
                 } else {
312 367
                     $res = $settingModel->createTeamData($param);
313 368
                     if (!$res) {
314 369
                         $errorMessage = $typesName . $dataInfo['name'] . "'操作失败,错误原因:修改失败";
315
-                    }else{
370
+                    } else {
316 371
                         (new Message())->send(
317 372
                             Message::TEAM_END,
318 373
                             [
@@ -322,10 +377,10 @@ class Setting extends ApiCommon
322 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 386
         if ($errorMessage) {
@@ -334,7 +389,7 @@ class Setting extends ApiCommon
334 389
             return resultArray(['data' => '保存成功']);
335 390
         }
336 391
     }
337
-
392
+    
338 393
     /**
339 394
      * 合同到期提醒天数
340 395
      *
@@ -350,17 +405,17 @@ class Setting extends ApiCommon
350 405
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
351 406
         }
352 407
         $param = $this->param;
353
-        $userInfo=$this->userInfo;
408
+        $userInfo = $this->userInfo;
354 409
         $data = [];
355 410
         $contract_day = $param['contract_day'] ? intval($param['contract_day']) : 0;
356 411
         $contract_config = $param['contract_config'] ? intval($param['contract_config']) : 0;
357 412
         $res = db('crm_config')->where(['name' => 'contract_config'])->update(['value' => $contract_config]);
358 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 416
         return resultArray(['data' => '设置成功']);
362 417
     }
363
-
418
+    
364 419
     /**
365 420
      * 记录类型编辑
366 421
      *
@@ -374,7 +429,7 @@ class Setting extends ApiCommon
374 429
     public function recordEdit()
375 430
     {
376 431
         $param = $this->param;
377
-        $userInfo=$this->userInfo;
432
+        $userInfo = $this->userInfo;
378 433
         //权限判断
379 434
         if (!checkPerByAction('admin', 'crm', 'setting')) {
380 435
             header('Content-Type:application/json; charset=utf-8');
@@ -385,18 +440,18 @@ class Setting extends ApiCommon
385 440
             $record_type = db('crm_config')->where(['name' => 'record_type'])->find();
386 441
             if ($record_type) {
387 442
                 $res = db('crm_config')->where(['name' => 'record_type'])->update(['value' => $array]);
388
-                $id=$record_type['id'];
443
+                $id = $record_type['id'];
389 444
             } else {
390 445
                 $data = array();
391 446
                 $data['name'] = 'record_type';
392 447
                 $data['value'] = $array;
393 448
                 $data['description'] = '跟进记录类型';
394 449
                 $res = db('crm_config')->insertGetId($data);
395
-                $id=$res;
396
-                $record_type['description']='跟进记录类型';
450
+                $id = $res;
451
+                $record_type['description'] = '跟进记录类型';
397 452
             }
398 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 455
                 return resultArray(['data' => '设置成功']);
401 456
             } else {
402 457
                 return resultArray(['error' => '设置失败,请重试!']);
@@ -407,7 +462,7 @@ class Setting extends ApiCommon
407 462
             return resultArray(['data' => $record_type]);
408 463
         }
409 464
     }
410
-
465
+    
411 466
     /**
412 467
      * 跟进记录 记录方式展示
413 468
      *
@@ -426,7 +481,7 @@ class Setting extends ApiCommon
426 481
             return resultArray(['data' => array()]);
427 482
         }
428 483
     }
429
-
484
+    
430 485
     /**
431 486
      * 拥有、锁定客户数限制列表
432 487
      *
@@ -444,7 +499,7 @@ class Setting extends ApiCommon
444 499
         $data = $customerConfigModel->getDataList($param);
445 500
         return resultArray(['data' => $data]);
446 501
     }
447
-
502
+    
448 503
     /**
449 504
      * 拥有、锁定客户数限制 创建/编辑 todo 创建和编辑走一个接口,前端非要这么搞
450 505
      *
@@ -460,15 +515,16 @@ class Setting extends ApiCommon
460 515
             header('Content-Type:application/json; charset=utf-8');
461 516
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
462 517
         }
463
-
518
+        $userInfo = $this->userInfo;
519
+        $this->param['user_id'] = $userInfo['id'];
464 520
         $customerConfigModel = new \app\crm\model\CustomerConfig();
465 521
         if (!$customerConfigModel->createData($this->param)) {
466 522
             return resultArray(['error' => $customerConfigModel->getError()]);
467 523
         }
468
-
524
+        
469 525
         return resultArray(['data' => empty($param['id']) ? '创建成功!' : '编辑成功!']);
470 526
     }
471
-
527
+    
472 528
     /**
473 529
      * 拥有、锁定客户数限制 编辑 todo 编辑不走这个接口,前端非要走创建接口
474 530
      *
@@ -481,7 +537,7 @@ class Setting extends ApiCommon
481 537
             header('Content-Type:application/json; charset=utf-8');
482 538
             exit(json_encode(['code' => 102, 'error' => '无权操作']));
483 539
         }
484
-
540
+        
485 541
         $param = $this->param;
486 542
         $customerConfigModel = new \app\crm\model\CustomerConfig();
487 543
         $res = $customerConfigModel->updateDataById($param, $param['id']);
@@ -490,7 +546,7 @@ class Setting extends ApiCommon
490 546
         }
491 547
         return resultArray(['data' => '编辑成功']);
492 548
     }
493
-
549
+    
494 550
     /**
495 551
      * 拥有、锁定客户数限制 删除
496 552
      *
@@ -511,7 +567,7 @@ class Setting extends ApiCommon
511 567
         }
512 568
         return resultArray(['data' => '删除成功']);
513 569
     }
514
-
570
+    
515 571
     /**
516 572
      * 编号列表
517 573
      *
@@ -527,7 +583,7 @@ class Setting extends ApiCommon
527 583
         $data = $numberSequenceModel->getDataList($param);
528 584
         return resultArray(['data' => $data]);
529 585
     }
530
-
586
+    
531 587
     /**
532 588
      * 编号修改
533 589
      *
@@ -548,7 +604,7 @@ class Setting extends ApiCommon
548 604
         }
549 605
         return resultArray(['data' => '编辑成功']);
550 606
     }
551
-
607
+    
552 608
     /**
553 609
      * 编号删除
554 610
      *
@@ -569,7 +625,7 @@ class Setting extends ApiCommon
569 625
         }
570 626
         return resultArray(['data' => '删除成功']);
571 627
     }
572
-
628
+    
573 629
     /**
574 630
      * 设置回访提醒
575 631
      *
@@ -580,12 +636,12 @@ class Setting extends ApiCommon
580 636
     public function setVisitDay()
581 637
     {
582 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 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 645
         return resultArray(['data' => '操作成功!']);
590 646
     }
591 647
     
@@ -602,6 +658,7 @@ class Setting extends ApiCommon
602 658
         
603 659
         return resultArray(['data' => $data]);
604 660
     }
661
+    
605 662
     /**
606 663
      * 设置自动编号
607 664
      *
@@ -610,11 +667,50 @@ class Setting extends ApiCommon
610 667
     public function setNumber()
611 668
     {
612 669
         if (empty($this->param) || !is_array($this->param)) return resultArray(['error' => '参数错误!']);
613
-
670
+        $userInfo = $this->userInfo;
614 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 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 查看文件

@@ -444,7 +444,11 @@ class ActivityLogic
444 444
         $param['business_ids']   = !empty($param['business_ids']) ? arrayToString($param['business_ids']) : '';
445 445
         $param['create_time']    = time();
446 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 452
         $activityJson = Activity::create($param);
449 453
         if (empty($activityJson)) return false;
450 454
 
@@ -549,7 +553,7 @@ class ActivityLogic
549 553
      * @param $activityId
550 554
      * @return Activity
551 555
      */
552
-    public function delete($activityId)
556
+    public function delete($activityId,$userId)
553 557
     {
554 558
         $activityInfo = Db::name('crm_activity')->where(['activity_id' => $activityId])->find();
555 559
         if (Activity::update(['activity_id' => $activityId, 'status' => 0])) {
@@ -563,9 +567,7 @@ class ActivityLogic
563 567
             if ($activityInfo['activity_type'] == 3) db('crm_contacts_file')->whereIn('file_id', $fileIds)->delete();
564 568
             if ($activityInfo['activity_type'] == 5) db('crm_business_file')->whereIn('file_id', $fileIds)->delete();
565 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 571
             return true;
570 572
         } else {
571 573
             return false;

+ 106
- 47
application/crm/logic/CommonLogic.php 查看文件

@@ -10,16 +10,19 @@ namespace app\crm\logic;
10 10
 
11 11
 use app\admin\controller\ApiCommon;
12 12
 use app\admin\model\User;
13
+use app\admin\traits\FieldVerificationTrait;
13 14
 use app\crm\model\Customer;
14 15
 use think\Db;
15 16
 use think\Validate;
16 17
 
17 18
 class CommonLogic
18 19
 {
20
+    use FieldVerificationTrait;
21
+
19 22
     public $error = '操作失败!';
20 23
     
21 24
     /**
22
-     * 快捷编辑【线索、客户、联系人、商机、合同、回款、回访、产品】
25
+     * 快捷编辑【线索、客户、联系人、商机、合同、回款、发票、回访、产品】
23 26
      *
24 27
      * @param $param
25 28
      * @return false|int|string
@@ -48,51 +51,46 @@ class CommonLogic
48 51
         $model = db($types);
49 52
         
50 53
         # 主键
51
-        $primaryKey = '';
52
-       // author      guogaobo $item模块
54
+        $primaryKey = getPrimaryKeyName($types);
55
+
53 56
         $info='';
54 57
         switch ($types) {
55 58
             case 'crm_leads' :
56
-                $primaryKey = 'leads_id';
57 59
                 $dataModel=new \app\crm\model\Leads();
58 60
                 $info=$dataModel->getDataById($actionId);
59 61
                 break;
60 62
             case 'crm_customer' :
61
-                $primaryKey = 'customer_id';
62 63
                 $info=db('crm_customer')->where('customer_id',$actionId)->find();
63 64
                 break;
64 65
             case 'crm_contacts' :
65
-                $primaryKey = 'contacts_id';
66 66
                 $dataModel=new \app\crm\model\Contacts();
67 67
                 $info=$dataModel->getDataById($actionId);
68 68
                 break;
69 69
             case 'crm_business' :
70
-                $primaryKey = 'business_id';
71 70
                 $dataModel=new \app\crm\model\Business();
72 71
                 $info=$dataModel->getDataById($actionId);
73 72
                 break;
74 73
             case 'crm_contract' :
75
-                $primaryKey = 'contract_id';
76 74
                 $info=db('crm_contract')->where('customer_id',$actionId)->find();
77 75
                 break;
78 76
             case 'crm_receivables' :
79
-                $primaryKey = 'receivables_id';
80 77
                 $info=db('crm_receivables')->where('customer_id',$actionId)->find();
81 78
                 break;
79
+            case 'crm_invoice' :
80
+                $info = $model->where($primaryKey, $actionId)->find();
81
+                break;
82 82
             case 'crm_visit' :
83
-                $primaryKey = 'visit_id';
84 83
                 $dataModel=new \app\crm\logic\VisitLogic();
85 84
                 $info=$dataModel->getDataById($actionId);
86 85
                 break;
87 86
             case 'crm_product' :
88
-                $primaryKey = 'product_id';
89 87
                 $dataModel=new \app\crm\model\Product();
90 88
                 $info=$dataModel->getDataById($actionId);
91 89
                 break;
92 90
         }
93 91
         $apiCommon = new ApiCommon();
94 92
         $userModel = new User();
95
-
93
+        $userInfo = $apiCommon->userInfo;
96 94
 
97 95
         if (in_array($types, ['crm_contract', 'crm_receivables'])) {
98 96
             $checkStatus = $model->where($primaryKey, $actionId)->value('check_status');
@@ -101,6 +99,22 @@ class CommonLogic
101 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 119
         if($types == 'crm_product'){
106 120
             foreach ($param['list'] as $val){
@@ -164,41 +178,27 @@ class CommonLogic
164 178
         $userField = $fieldModel->getFieldByFormType($types, 'user');
165 179
         # 部门类型
166 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 193
         $data = [];
194
+        $extraData = [];
195
+        $deleteExtraWhere = [];
196 196
         if (!empty($param['list'])) {
197 197
             foreach ($param['list'] as $key => $value) {
198 198
                 foreach ($value as $k => $v) {
199 199
                     if ($k == 'next_time' || in_array($k, $datetimeField)) {
200 200
                         # 处理下次联系时间格式、datetime类型数据
201
-                        $data[$k] = !empty($v) ? strtotime($v) : '';
201
+                        $data[$k] = !empty($v) && $v == strtotime($v) ? strtotime($v) : $v;
202 202
                     } elseif ($types == 'crm_product' && $k == 'category_id') {
203 203
                         # 处理产品类别
204 204
                         $categorys = explode(',', $v);
@@ -209,25 +209,84 @@ class CommonLogic
209 209
                     } elseif ($types == 'crm_visit' && $k == 'contract_id') {
210 210
                         # 处理回访提交过来的合同编号
211 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 269
                     } else {
213 270
                         $data[$k] = $v;
214 271
                     }
215
-                    $item[$k]=$v;
216 272
                 }
217 273
             }
218 274
             $data[$primaryKey]   = $actionId;
219 275
             $data['update_time'] = time();
220 276
         }
277
+
221 278
         $res = $model->update($data);
222 279
         unset($data[$primaryKey]);
223 280
         unset($data['update_time']);
224
-        //详细信息修改新增操作记录
281
+        // 详细信息修改新增操作记录、处理扩展数据
225 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 291
         return $res;
233 292
     }

+ 99
- 53
application/crm/logic/CustomerPoolLogic.php 查看文件

@@ -38,11 +38,11 @@ class CustomerPoolLogic extends Common
38 38
         $poolId = $param['pool_id'];
39 39
         $orderField = $param['order_field'];
40 40
         $orderType = $param['order_type'];
41
-      
42
-        # 基础条件
41
+
42
+        // 基础条件
43 43
         $where['relation.pool_id'] = $poolId;
44 44
 
45
-        # 普通搜索
45
+        // 普通搜索
46 46
         $searchMap = [];
47 47
         if ($param['search'] == '0' || !empty($param['search'])) {
48 48
             $search = $param['search'];
@@ -52,38 +52,39 @@ class CustomerPoolLogic extends Common
52 52
                     ->whereOr('customer.telephone',array('like','%'.$search.'%'));
53 53
             };
54 54
         }
55
-      
56
-        # 处理排序参数
55
+
56
+        // 处理排序参数
57 57
         if (!empty($orderField)) {
58 58
             if ($orderField == 'create_user_id_name') $orderField = 'create_user_id';
59 59
             if ($orderField == 'before_owner_user_name') $orderField = 'before_owner_user_id';
60 60
         }
61
-        # 公海条件
61
+        // 公海条件
62 62
         if ($param['is_excel'] == 1 && !empty($param['customer_id'])) {
63 63
             $authMap['customer.customer_id'] = ['in', trim(arrayToString($param['customer_id']),',')];
64 64
         }
65
-        # 排序
65
+        // 排序
66 66
         if (!empty($orderField) && !empty($orderType)) {
67 67
             $order = $fieldModel->getOrderByFormtype('crm_customer','customer', $orderField, $orderType);
68 68
         } else {
69 69
             $order = 'customer.update_time desc';
70 70
         }
71
-        # 删除参数
71
+        // 删除参数
72 72
         unset($param['pool_id']);
73 73
         unset($param['search']);
74 74
         unset($param['order_field']);
75 75
         unset($param['order_type']);
76 76
         unset($param['is_excel']);
77 77
         unset($param['customer_id']);
78
-        # 格式化参数
78
+        // 格式化参数
79 79
         $request = $this->fmtRequest( $param );
80 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 86
         $customerFieldString = $this->getPoolQueryField($poolId);
86
-        # 公海数据
87
+        // 公海数据
87 88
         $customerPoolCount = db('crm_customer_pool_relation')->alias('relation')
88 89
             ->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT')
89 90
             ->where($where)->where($searchMap)->where($map)->where($authMap)->count();
@@ -93,18 +94,31 @@ class CustomerPoolLogic extends Common
93 94
             ->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = relation.customer_id', 'LEFT')
94 95
             ->limit($request['offset'], $request['length'])->where($where)->where($searchMap)->where($map)->where($authMap)->orderRaw($order)->select();
95 96
 
96
-        # 员工列表
97
+        // 员工列表
97 98
         $userData = $this->getUserList();
98 99
 
99
-        # 部门列表
100
+        // 部门列表
100 101
         $structureData = $this->getStructureList();
101 102
 
102
-        # 特殊字段
103
+        // 特殊字段
103 104
         $userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); # 人员类型
104 105
         $structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); # 部门类型
105 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 122
         foreach ($customerPoolList AS $key => $value) {
109 123
             $customerPoolList[$key]['create_user_name'] = !empty($userData[$value['create_user_id']]) ? $userData[$value['create_user_id']] : '';
110 124
             $customerPoolList[$key]['before_owner_user_name'] = !empty($userData[$value['before_owner_user_id']]) ? $userData[$value['before_owner_user_id']] : '';
@@ -115,23 +129,40 @@ class CustomerPoolLogic extends Common
115 129
             $customerPoolList[$key]['last_time'] = !empty($value['last_time']) ? date('Y-m-d H:i:s', $value['last_time']) : null;
116 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 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 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 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,12 +338,14 @@ class CustomerPoolLogic extends Common
307 338
      */
308 339
     public function getPondList($param)
309 340
     {
341
+        $adminTypes = adminGroupTypes($param['user_id']);
342
+
310 343
         return db('crm_customer_pool')->field(['pool_id', 'pool_name'])
311 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 349
             })->select();
317 350
     }
318 351
 
@@ -329,7 +362,12 @@ class CustomerPoolLogic extends Common
329 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 373
         foreach ($list AS $key => $value) {
@@ -346,9 +384,6 @@ class CustomerPoolLogic extends Common
346 384
                 default :
347 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 388
             if (in_array($value['field_name'], ['last_record', 'create_user_id', 'create_time', 'update_time', 'last_time', 'deal_status'])) {
354 389
                 $list[$key]['system'] = 1;
@@ -395,7 +430,7 @@ class CustomerPoolLogic extends Common
395 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 434
         $list = array_merge($list, $base);
400 435
 
401 436
         # 整理数据
@@ -416,6 +451,7 @@ class CustomerPoolLogic extends Common
416 451
      */
417 452
     public function receiveCustomers($param)
418 453
     {
454
+        
419 455
         if (empty($param['user_id'])) return ['缺少员工ID'];
420 456
 
421 457
         # 查询参数
@@ -453,15 +489,15 @@ class CustomerPoolLogic extends Common
453 489
                 $message[] = '客户《' . $customerData[$value]['name'] . '》领取失败,失败原因:持有客户数达到上限!';
454 490
             }
455 491
         }
456
-
457 492
         # 可以领取的客户ID,取差集
458 493
         $addCustomerId = count($customerId) == 1 ? $customerId : array_diff($customerId, $failCustomer);
459
-
494
+      
460 495
         # 检查是否还有要领取的客户
461 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 502
         # 前负责人N天内不能领取客户
467 503
         if (!empty($poolConfig['before_owner_conf'])) {
@@ -483,7 +519,7 @@ class CustomerPoolLogic extends Common
483 519
 
484 520
         # 检查每天领取的个数限制
485 521
         $countWhere['type'] = 1;
486
-        $countWhere['pool_id'] = $param['pool_id'];
522
+        $countWhere['pool_id'] = $poolId;
487 523
         $countWhere['user_id'] = $userId;
488 524
         $countWhere['create_time'] = ['between', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))]];
489 525
         $receiveCount = db('crm_customer_pool_record')->where($countWhere)->count();
@@ -527,7 +563,7 @@ class CustomerPoolLogic extends Common
527 563
             $addReceiveData[] = [
528 564
                 'customer_id' => $value,
529 565
                 'user_id'     => $userId,
530
-                'pool_id'     => $param['pool_id'],
566
+                'pool_id'     => $poolId,
531 567
                 'type'        => 1,
532 568
                 'create_time' => time()
533 569
             ];
@@ -537,22 +573,22 @@ class CustomerPoolLogic extends Common
537 573
         try {
538 574
             # 领取客户
539 575
             Db::name('crm_customer')->whereIn('customer_id', $addCustomerId)->update($addCustomerData);
540
-
576
+            
541 577
             # 设置客户的联系人数据
542 578
             Db::name('crm_contacts')->whereIn('customer_id', $addCustomerId)->update(['owner_user_id' => $userId]);
543
-
579
+           
544 580
             # 删除公海与客户关联数据
545 581
             Db::name('crm_customer_pool_relation')->whereIn('customer_id', $addCustomerId)->delete();
546
-
582
+            
547 583
             # 字段操作日志
548 584
             Db::name('admin_action_record')->insertAll($addActionRecordData);
549
-
585
+           
550 586
             # 数据操作日志
551 587
             Db::name('admin_operation_log')->insertAll($addOperationLogData);
552
-
588
+            
553 589
             # 记录领取的客户
554 590
             Db::name('crm_customer_pool_record')->insertAll($addReceiveData);
555
-
591
+           
556 592
             Db::commit();
557 593
         } catch (\Exception $e) {
558 594
             Db::rollback();
@@ -615,7 +651,8 @@ class CustomerPoolLogic extends Common
615 651
 
616 652
         # 检查是否还有要领取的客户
617 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 657
         $addCustomerData = [
621 658
             'owner_user_id'        => $userId,
@@ -653,7 +690,7 @@ class CustomerPoolLogic extends Common
653 690
             $addReceiveData[] = [
654 691
                 'customer_id' => $value,
655 692
                 'user_id'     => $userId,
656
-                'pool_id'     => $param['pool_id'],
693
+                'pool_id'     => $poolId,
657 694
                 'type'        => 3,
658 695
                 'create_time' => time()
659 696
             ];
@@ -755,7 +792,11 @@ class CustomerPoolLogic extends Common
755 792
         $data = !empty($data) ? json_decode($data, true) :[];
756 793
 
757 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 797
             foreach ($data AS $key => $value) {
798
+                if (in_array($value['field'], $exceptFields)) continue;
799
+
759 800
                 if (!empty($value['is_hidden'])) {
760 801
                     $hideList[] = $value;
761 802
                 } else {
@@ -764,7 +805,12 @@ class CustomerPoolLogic extends Common
764 805
             }
765 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 814
             foreach ($poolField AS $key => $value) {
769 815
                 if (empty($value['is_hidden'])) {
770 816
                     $showList[] = [

+ 89
- 100
application/crm/logic/IndexLogic.php 查看文件

@@ -37,17 +37,16 @@ class IndexLogic extends Common
37 37
         $contractModel = new \app\crm\model\Contract();
38 38
         $receivablesModel = new \app\crm\model\Receivables();
39 39
         $activityModel = new \app\crm\model\Activity();
40
+        $last_between_time = ByDateTime($param['type']);
40 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 45
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
45
-        $lastArr = $adminModel->getWhere($param, 1, '', true); //统计条件
46
+//        $lastArr = $adminModel->getWhere($param, 1, '', true); //统计条件
46 47
         $userIds = $whereArr['userIds'];
47 48
         $between_time = $whereArr['between_time'];
48
-        $last_between_time = $lastArr['between_time'];
49
-        
50
-        
49
+   
51 50
         $customerNum = 0; //新增客户
52 51
         $customerLastNum = 0; //上期对比
53 52
         $contactsNum = 0; //新增联系人
@@ -89,11 +88,10 @@ class IndexLogic extends Common
89 88
                 'record_auth_user_ids' => array_intersect($userIds, $record_auth_user_ids) ? :[-1],
90 89
             ])
91 90
         );
92
-        
93 91
         $resLastCount = queryCache(
94 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 95
                 'customer_auth_user_ids' => array_intersect($userIds, $customer_auth_user_ids) ? : [-1],
98 96
                 'contacts_auth_user_ids' => array_intersect($userIds, $contacts_auth_user_ids) ? : [-1],
99 97
                 'business_auth_user_ids' => array_intersect($userIds, $business_auth_user_ids) ? : [-1],
@@ -120,7 +118,6 @@ class IndexLogic extends Common
120 118
         $contractLastMoneyNum = $resLastCount[3]['count2'] ?: 0;
121 119
         $receivablesLastMoneyNum = $resLastCount[4]['count'] ?: 0;
122 120
         $recordLastNum = (int)$resLastCount[5]['count'] ?: 0;
123
-        
124 121
         $data = [];
125 122
         $data['data']['customerNum'] = $customerNum;
126 123
         $data['prev']['customerNum'] = $this->getProportion($customerNum, $customerLastNum);
@@ -145,19 +142,12 @@ class IndexLogic extends Common
145 142
         
146 143
         $data['data']['receivablesMoneyNum'] = $receivablesMoneyNum;
147 144
         $data['prev']['receivablesMoneyNum'] = $this->getProportion($receivablesMoneyNum, $receivablesLastMoneyNum);
145
+        
148 146
         return $data;
149 147
     }
150 148
     
151 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 151
         $countSql = "SELECT
162 152
         count(1) count1,
163 153
         0 count2
@@ -210,15 +200,14 @@ class IndexLogic extends Common
210 200
     ///计算涨幅
211 201
     public function getProportion($now, $last)
212 202
     {
213
-        $res = 0;
214 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 209
         } else {
219
-            if ($now && $now != 0.00) {
220
-                $res = 1;
221
-            }
210
+                $res = 0;
222 211
         }
223 212
         return $res;
224 213
     }
@@ -363,10 +352,6 @@ class IndexLogic extends Common
363 352
                     ->field([
364 353
                         'SUM(CASE WHEN check_status = 2 THEN money ELSE 0 END) as money',
365 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 356
                     ->where([
372 357
                         'contract.owner_user_id' => ['in', $auth_user_ids],
@@ -388,10 +373,6 @@ class IndexLogic extends Common
388 373
                     ->field([
389 374
                         'SUM(CASE WHEN receivables.check_status = 2 THEN receivables.money ELSE 0 END) as money',
390 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 377
                     ->where([
397 378
                         'receivables.owner_user_id' => ['in', $auth_user_ids],
@@ -414,10 +395,6 @@ class IndexLogic extends Common
414 395
                     ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
415 396
                     ->field([
416 397
                         'count(contract.contract_id) as count',
417
-                        'user.realname as realname',
418
-                        'user.id',
419
-                        'user.thumb_img',
420
-                        'structure.name',
421 398
                         'contract.owner_user_id as owner_user_id'])
422 399
                     ->where([
423 400
                         'contract.owner_user_id' => ['in', $auth_user_ids],
@@ -440,10 +417,6 @@ class IndexLogic extends Common
440 417
                     ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
441 418
                     ->field([
442 419
                         'count(customer.customer_id) as count',
443
-                        'user.realname as realname',
444
-                        'user.id',
445
-                        'user.thumb_img',
446
-                        'structure.name',
447 420
                         'customer.owner_user_id as owner_user_id'])
448 421
                     ->where(
449 422
                         'customer.owner_user_id' ,['in', $auth_user_ids]
@@ -462,10 +435,6 @@ class IndexLogic extends Common
462 435
                     ->join('__ADMIN_STRUCTURE__ structure', 'user.structure_id=structure.id')
463 436
                     ->field([
464 437
                         'count(contacts.contacts_id) as count',
465
-                        'user.realname as realname',
466
-                        'user.id',
467
-                        'user.thumb_img',
468
-                        'structure.name',
469 438
                         'contacts.contacts_id',
470 439
                         'contacts.owner_user_id as owner_user_id'])
471 440
                     ->where([
@@ -484,9 +453,6 @@ class IndexLogic extends Common
484 453
                     ->join('__ADMIN_USER__ user', 'activity.create_user_id=user.id')
485 454
                     ->field([
486 455
                         'count(activity.activity_id) as count',
487
-                        'user.realname as realname',
488
-                        'user.id',
489
-                        'user.thumb_img',
490 456
                         'activity.create_user_id as create_user_id'])
491 457
                     ->where([
492 458
                         'activity.create_user_id' => ['in', $auth_user_ids],
@@ -500,7 +466,15 @@ class IndexLogic extends Common
500 466
                     ->select();
501 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 479
         $between_time = getTimeByType($param['type']);
506 480
         $start_time = $between_time[0];
@@ -587,10 +561,10 @@ class IndexLogic extends Common
587 561
         $business_auth_user_ids = $userModel->getUserByPer('crm', 'business', 'index');
588 562
         $contract_auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'index');
589 563
         $receivables_auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index');
564
+        $receivablesPlan_auth_user_ids = $userModel->getUserByPer('crm', 'receivables_plan', 'index');
590 565
         $record_auth_user_ids = $userModel->getUserByPer('crm', 'activity', 'index');
591
-        
592 566
         $resDataArr = [];
593
-        for ($i = 1; $i <= 5; $i++) {
567
+        for ($i = 1; $i <= 6; $i++) {
594 568
             $resData = queryCache(
595 569
                 $this->getQueryDataSql([
596 570
                     'type' => $i,
@@ -602,6 +576,7 @@ class IndexLogic extends Common
602 576
                     'contract_auth_user_ids' => array_intersect($userIds, $contract_auth_user_ids) ? : [-1],
603 577
                     'receivables_auth_user_ids' => array_intersect($userIds, $receivables_auth_user_ids) ? : [-1],
604 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 582
             $resDataArr = array_merge($resDataArr, $resData[0]);
@@ -661,51 +636,59 @@ class IndexLogic extends Common
661 636
                 SUM( CASE WHEN check_status = 2 THEN money ELSE 0 END) AS contractMoney
662 637
                 FROM 5kcrm_crm_contract
663 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 640
                 break;
666 641
             case 5 :
642
+                $start_time=date('Y-m-d',$param['start_time']);
643
+                $end_time=date('Y-m-d',$param['end_time']);
667 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 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 658
                 break;
675 659
         }
676
-        
677 660
         return $countSql;
678 661
     }
679 662
     
680 663
     /**
681
-     * 赢单输单查看
664
+     * 销售漏斗查看
682 665
      */
683 666
     public function businessList($param)
684 667
     {
685
-        $userModel = new \app\admin\model\User();
686 668
         $adminModel = new \app\admin\model\Admin();
687 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 673
         $whereArr = $adminModel->getWhere($param, 1, ''); //统计条件
692
-        $user_id = $param['user_id'] ?: [-1];
693 674
         $userIds = $whereArr['userIds'];
694 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 692
         return $data;
710 693
     }
711 694
     
@@ -792,10 +775,10 @@ class IndexLogic extends Common
792 775
         $auth_customer_user_ids = $auth_customer_user_ids ? array_intersect($userIds, $auth_customer_user_ids) : []; //取交集
793 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 779
         $where_activity['t.type'] = 1;
797 780
         $where_activity['t.status'] = 1;
798
-        if ($param['label'] == 2) {
781
+        if ($param['label'] != 1) {
799 782
             if ($param['search']) {
800 783
                 $type['t.content'] = array('like', '%' . $param['search'] . '%');
801 784
             }
@@ -822,14 +805,15 @@ class IndexLogic extends Common
822 805
                 $type['t.type'] = $param['queryType'];
823 806
             }
824 807
             if ($param['user_id'] == '') {
825
-                if ($param['subUser'] == '0') {
808
+               
809
+                if ($param['subUser'] === "0" || $param['subUser']===0) {
826 810
                     $type['t.create_user_id'] = $param['id'];
827 811
                     //下属创建
828 812
                 } elseif ($param['subUser'] == '1') {
829 813
                     $subList = getSubUserId(false, 0, $param['id']);
830 814
                     $subStr = $subList ? implode(',', $subList) : '-1';
831 815
                     $type['t.create_user_id'] = array('in', $subStr);
832
-                } elseif ($param['subUser'] == '') {
816
+                } else {
833 817
                     $userIds = getSubUserId(true, 0, $param['id']);
834 818
                     $subStr = $userIds ? implode(',', $userIds) : '-1';
835 819
                     $type['t.create_user_id'] = array('in', $subStr);
@@ -846,6 +830,15 @@ class IndexLogic extends Common
846 830
                 ->page($param['page'], $param['limit'])
847 831
                 ->order('t.create_time desc')
848 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 842
             $dataCount = db('crm_activity')
850 843
                 ->alias('t')
851 844
                 ->join('__ADMIN_USER__ user', 'user.id = t.create_user_id', 'LEFT')
@@ -864,7 +857,8 @@ class IndexLogic extends Common
864 857
                     $activity_contacts = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->select();
865 858
                     $list[$k]['business_list'] = $activity_business ?: [];
866 859
                     $list[$k]['contacts_list'] = $activity_contacts ?: [];
867
-                }
860
+                  
861
+                   }
868 862
                 
869 863
                 if ($v['activity_type'] == 3) {
870 864
                     $activity_name = Db::name('crm_contacts')->where('contacts_id', $v['activity_type_id'])->find();
@@ -901,21 +895,18 @@ class IndexLogic extends Common
901 895
                             $imgList[] = $val;
902 896
                         }
903 897
                     }
904
-                }
898
+                };
905 899
                 $list[$k]['fileList'] = $fileList ?: [];
906 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 908
                 $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
912 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 911
         } else {
921 912
             $list = db('crm_activity')
@@ -981,14 +972,12 @@ class IndexLogic extends Common
981 972
                 }
982 973
                 $list[$k]['fileList'] = $fileList ?: [];
983 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 979
                 $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
989 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,7 +991,7 @@ class IndexLogic extends Common
1002 991
         } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
1003 992
             $data['firstPage'] = false;
1004 993
             $data['lastPage'] = false;
1005
-        } else if ($param['page'] == 1) {
994
+        } else if ($param['page'] == 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
1006 995
             $data['firstPage'] = true;
1007 996
             $data['lastPage'] = false;
1008 997
         }

+ 244
- 137
application/crm/logic/InvoiceLogic.php 查看文件

@@ -16,7 +16,8 @@ use think\Db;
16 16
 class InvoiceLogic
17 17
 {
18 18
     private $invoiceType = ['增值税专用发票', '增值税普通发票', '国税通用机打发票', '地税通用机打发票', '收据'];
19
-
19
+    private $check_status = ['待审核', '审核中', '审核通过', '审核未通过', '撤回'];
20
+    
20 21
     /**
21 22
      * 列表
22 23
      *
@@ -25,103 +26,209 @@ class InvoiceLogic
25 26
      * @return array
26 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 37
         $getCount = $param['getCount'];
49
-        $userId   = $param['user_id'];
38
+        $userId = $param['user_id'];
50 39
         $invoiceIdArray = $param['invoiceIdArray']; // 待办事项提醒参数
51 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 49
         unset($param['getCount']);
54
-        unset($param['limit']);
55
-        unset($param['page']);
50
+//        unset($param['limit']); 导出使用 暂未发现为何去掉分页参数
51
+//        unset($param['page']);
56 52
         unset($param['user_id']);
57 53
         unset($param['invoiceIdArray']);
58 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 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 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 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 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 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,7 +239,7 @@ class InvoiceLogic
132 239
     {
133 240
         return db('crm_invoice')->insert($param, false, true);
134 241
     }
135
-
242
+    
136 243
     /**
137 244
      * 详情
138 245
      *
@@ -146,71 +253,71 @@ class InvoiceLogic
146 253
     public function read($invoiceId, $isUpdate)
147 254
     {
148 255
         $apiCommon = new ApiCommon();
149
-
150
-        $userId     = $apiCommon->userInfo['id'];
151
-        $result     = [];
256
+        
257
+        $userId = $apiCommon->userInfo['id'];
258
+        $result = [];
152 259
         $dataObject = Invoice::with(['toCustomer', 'toContract'])->where('invoice_id', $invoiceId)->find();
153
-
260
+        
154 261
         if (empty($dataObject)) return $result;
155
-
262
+        
156 263
         $dataArray = $dataObject->toArray();
157
-
264
+        
158 265
         if (!empty($isUpdate)) return $dataArray;
159
-
266
+        
160 267
         # 主键ID
161 268
         $result['invoice_id'] = $dataArray['invoice_id'];
162
-
269
+        
163 270
         # 是否显示撤回按钮
164 271
         $result['isShowRecall'] = 0;
165 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 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 281
         $result['essential'] = [
175 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 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 306
             'deposit_account' => $dataArray['deposit_account'],
200 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 315
             'contacts_address' => $dataArray['contacts_address']
209 316
         ];
210
-
317
+        
211 318
         return $result;
212 319
     }
213
-
320
+    
214 321
     /**
215 322
      * 编辑
216 323
      *
@@ -221,7 +328,7 @@ class InvoiceLogic
221 328
     {
222 329
         return Invoice::update($param);
223 330
     }
224
-
331
+    
225 332
     /**
226 333
      * 删除
227 334
      *
@@ -232,7 +339,7 @@ class InvoiceLogic
232 339
     {
233 340
         return Invoice::destroy($where);
234 341
     }
235
-
342
+    
236 343
     /**
237 344
      * 获取审批状态
238 345
      *
@@ -249,11 +356,11 @@ class InvoiceLogic
249 356
         if ($isDelete) {
250 357
             return Invoice::field(['check_status'])->whereIn('invoice_id', $invoiceId)->select();
251 358
         }
252
-
359
+        
253 360
         # 编辑
254 361
         return Invoice::where('invoice_id', $invoiceId)->value('check_status');
255 362
     }
256
-
363
+    
257 364
     /**
258 365
      * 转移(变更负责人)
259 366
      *
@@ -265,10 +372,10 @@ class InvoiceLogic
265 372
     {
266 373
         return Invoice::whereIn('invoice_id', $invoiceIds)->update(['owner_user_id' => $ownerUserId]);
267 374
     }
268
-
375
+    
269 376
     /**
270 377
      * 设置开票
271
-     * 
378
+     *
272 379
      * @param $param
273 380
      * @return Invoice
274 381
      */
@@ -276,7 +383,7 @@ class InvoiceLogic
276 383
     {
277 384
         return Invoice::update($param);
278 385
     }
279
-
386
+    
280 387
     /**
281 388
      * 获取发票审核信息
282 389
      *
@@ -289,10 +396,10 @@ class InvoiceLogic
289 396
     public function getExamineInfo($invoiceId)
290 397
     {
291 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 400
         return Invoice::field($field)->where('invoice_id', $invoiceId)->find();
294 401
     }
295
-
402
+    
296 403
     /**
297 404
      * 设置审批信息
298 405
      *
@@ -303,7 +410,7 @@ class InvoiceLogic
303 410
     {
304 411
         return Invoice::update($data);
305 412
     }
306
-
413
+    
307 414
     /**
308 415
      * 添加撤销审核记录
309 416
      *
@@ -316,19 +423,19 @@ class InvoiceLogic
316 423
     public function createExamineRecord($invoiceId, $examineInfo, $realname, $content, $userId)
317 424
     {
318 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 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 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 查看文件

@@ -0,0 +1,272 @@
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 查看文件

@@ -328,6 +328,9 @@ class PrintingLogic
328 328
         $contactsData = Db::name('crm_contacts')->where('contacts_id', $contractData['contacts_id'])->find();
329 329
         # 查询产品数据
330 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 334
         $productIdArray = [];
332 335
         foreach ($businessProduct AS $key => $value) {
333 336
             $productIdArray[] = $value['product_id'];
@@ -525,8 +528,8 @@ class PrintingLogic
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 534
         return $content;
532 535
     }

+ 208
- 20
application/crm/logic/VisitLogic.php 查看文件

@@ -4,12 +4,14 @@ namespace app\crm\logic;
4 4
 
5 5
 use app\admin\controller\ApiCommon;
6 6
 use app\admin\model\Common;
7
+use app\admin\traits\FieldVerificationTrait;
7 8
 use app\crm\model\Visit;
8 9
 use think\Db;
9
-use think\Validate;
10 10
 
11 11
 class VisitLogic extends Common
12 12
 {
13
+    use FieldVerificationTrait;
14
+
13 15
     /**
14 16
      * 获取回访列表
15 17
      * @param $param
@@ -54,7 +56,7 @@ class VisitLogic extends Common
54 56
         }
55 57
 
56 58
         //高级筛选
57
-        $map = where_arr($map, 'crm', 'visit', 'index');
59
+        $map = advancedQuery($map, 'crm', 'visit', 'index');
58 60
 
59 61
         $authMap = [];
60 62
         if (!$partMap) {
@@ -93,6 +95,11 @@ class VisitLogic extends Common
93 95
         $userField = $fieldModel->getFieldByFormType('crm_visit', 'user'); //人员类型
94 96
         $structureField = $fieldModel->getFieldByFormType('crm_visit', 'structure');  //部门类型
95 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 103
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
97 104
         $temporaryField = str_replace('_name', '', $order_field);
98 105
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@@ -133,7 +140,13 @@ class VisitLogic extends Common
133 140
             ->join('__CRM_CONTRACT__ contract', 'visit.contract_id=contract.contract_id', 'LEFT')
134 141
             ->join('__CRM_CONTACTS__ contacts', 'visit.contacts_id=contacts.contacts_id', 'LEFT')
135 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 150
         foreach ($list as $k => $v) {
138 151
             $list[$k]['contract_num'] = $v['contract_number'];
139 152
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
@@ -151,6 +164,26 @@ class VisitLogic extends Common
151 164
             foreach ($datetimeField as $key => $val) {
152 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 187
             $list[$k]['contract_id_info']['contract_id'] = $v['contract_id'];
155 188
             $list[$k]['contract_id_info']['name'] = $v['contract_name'];
156 189
             $list[$k]['customer_id_info']['customer_id'] = $v['create_user_id'];
@@ -232,16 +265,18 @@ class VisitLogic extends Common
232 265
      */
233 266
     public function createData($param)
234 267
     {
268
+        // 回访扩展表数据
269
+        $visitData = [];
270
+
235 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 277
             return false;
244 278
         }
279
+
245 280
         if (!$param['customer_id']) {
246 281
             $this->error = '请选择相关客户';
247 282
             return false;
@@ -263,14 +298,88 @@ class VisitLogic extends Common
263 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 371
         $visitModel = new Visit();
268 372
         if ($visitModel->data($param)->allowField(true)->save()) {
269 373
             $visit_id = $visitModel->visit_id;
374
+            $data['visit_id'] = $visit_id;
270 375
             updateActionLog($param['create_user_id'], 'crm_visit', $visitModel->visit_id, '', '', '创建了客户回访');
271 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 383
             return $data;
275 384
         } else {
276 385
             $this->error = '添加失败';
@@ -283,6 +392,9 @@ class VisitLogic extends Common
283 392
      */
284 393
     public function updateDataById($param, $visit_id = '')
285 394
     {
395
+        // 回访扩展表数据
396
+        $visitData = [];
397
+
286 398
         $Visit = model('Visit');
287 399
         $productModel = new \app\crm\model\Product();
288 400
         $dataInfo = $this->getDataById($visit_id);
@@ -298,15 +410,14 @@ class VisitLogic extends Common
298 410
         }
299 411
 
300 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 418
             return false;
309 419
         }
420
+
310 421
         // 处理部门、员工、附件、多选类型字段
311 422
         $arrFieldAtt = $fieldModel->getArrayField('crm_visit');
312 423
         foreach ($arrFieldAtt as $k => $v) {
@@ -320,13 +431,88 @@ class VisitLogic extends Common
320 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 504
         if ($Visit->update($param, ['visit_id' => $visit_id], true)) {
505
+            $data['visit_id'] = $visit_id;
325 506
             //修改记录           
326 507
             updateActionLog($param['user_id'], 'crm_visit', $visit_id, $dataInfo, $param);
327 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 516
             return $data;
331 517
         } else {
332 518
             $this->rollback();
@@ -371,6 +557,8 @@ class VisitLogic extends Common
371 557
             if (!$data) {
372 558
                 return resultArray(['error' => $this->getError()]);
373 559
             }
560
+            // 删除回访扩展数据
561
+            db('crm_visit_data')->whereIn('visit_id', $delIds)->delete();
374 562
             //删除关联附件
375 563
             $fileModel->delRFileByModule('crm_visit', $delIds);
376 564
             //删除关联操作记录

+ 219
- 33
application/crm/model/Business.php 查看文件

@@ -6,14 +6,15 @@
6 6
 // +----------------------------------------------------------------------
7 7
 namespace app\crm\model;
8 8
 
9
+use app\admin\traits\FieldVerificationTrait;
9 10
 use think\Db;
10 11
 use app\admin\model\Common;
11
-use think\Request;
12
-use think\Validate;
13 12
 use app\crm\model\Business as CrmBusinessModel;
14 13
 
15 14
 class Business extends Common
16 15
 {
16
+    use FieldVerificationTrait;
17
+
17 18
     /**
18 19
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19 20
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
@@ -47,6 +48,7 @@ class Business extends Common
47 48
         $getCount = $request['getCount'];
48 49
         $businessTypeId = $request['typesId']; // 针对mobile
49 50
         $businessStatusId = $request['statusId']; // 针对mobile
51
+        $overdue = $request['overdue']; // 待办事项下需联系商机(逾期)
50 52
         unset($request['scene_id']);
51 53
         unset($request['search']);
52 54
         unset($request['user_id']);
@@ -57,7 +59,7 @@ class Business extends Common
57 59
         unset($request['getCount']);
58 60
         unset($request['typesId']);
59 61
         unset($request['statusId']);
60
-
62
+        unset($request['overdue']);
61 63
         $request = $this->fmtRequest($request);
62 64
         $requestMap = $request['map'] ?: [];
63 65
         $sceneModel = new \app\admin\model\Scene();
@@ -97,18 +99,16 @@ class Business extends Common
97 99
         }
98 100
         $partMap = [];
99 101
         //优先级:普通筛选>高级筛选>场景
100
-        if ($sceneMap['ro_user_id'] && $sceneMap['rw_user_id']) {
102
+        if ($requestMap['team_id']) {
101 103
             //相关团队查询
102 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 107
         } else {
108 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 112
         $authMap = [];
113 113
         if (!$partMap) {
114 114
             $a = 'index';
@@ -156,6 +156,11 @@ class Business extends Common
156 156
         $userField = $fieldModel->getFieldByFormType('crm_business', 'user'); //人员类型
157 157
         $structureField = $fieldModel->getFieldByFormType('crm_business', 'structure');  //部门类型
158 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 164
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
160 165
         $temporaryField = str_replace('_name', '', $order_field);
161 166
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@@ -178,13 +183,20 @@ class Business extends Common
178 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 193
         $readAuthIds = $userModel->getUserByPer('crm', 'business', 'read');
182 194
         $updateAuthIds = $userModel->getUserByPer('crm', 'business', 'update');
183 195
         $deleteAuthIds = $userModel->getUserByPer('crm', 'business', 'delete');
184 196
         $dataCount = db('crm_business')
185 197
             ->alias('business')
186 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 200
         if (!empty($getCount) && $getCount == 1) {
189 201
             $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
190 202
             # 商机总金额
@@ -199,11 +211,19 @@ class Business extends Common
199 211
             ->where($map)
200 212
             ->where($partMap)
201 213
             ->where($authMap)
214
+            ->where($overdueWhere)
202 215
             ->limit($request['offset'], $request['length'])
203 216
             ->field('business.*,customer.name as customer_name')
204 217
             ->orderRaw($order)
205 218
             ->select();
206 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 227
         foreach ($list as $k => $v) {
208 228
             $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
209 229
             $list[$k]['customer_id_info']['name'] = $v['customer_name'];
@@ -213,15 +233,35 @@ class Business extends Common
213 233
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
214 234
             foreach ($userField as $key => $val) {
215 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 238
             foreach ($structureField as $key => $val) {
219 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 242
             foreach ($datetimeField as $key => $val) {
223 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 265
             $statusInfo = [];
226 266
             $status_count = 0;
227 267
             if (!$v['is_end']) {
@@ -281,14 +321,15 @@ class Business extends Common
281 321
      */
282 322
     public function createData($param)
283 323
     {
324
+        // 商机扩展表数据
325
+        $businessData = [];
326
+
284 327
         $fieldModel = new \app\admin\model\Field();
285 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 333
             return false;
293 334
         }
294 335
         if (!$param['customer_id']) {
@@ -308,6 +349,75 @@ class Business extends Common
308 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 423
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
@@ -318,6 +428,7 @@ class Business extends Common
318 428
             updateActionLog($param['create_user_id'], 'crm_business', $this->business_id, '', '', '创建了商机');
319 429
             RecordActionLog($param['create_user_id'],'crm_business','save',$param['name'],'','','新增了商机'.$param['name']);
320 430
             $business_id = $this->business_id;
431
+            $data['business_id'] = $business_id;
321 432
             if ($param['product']) {
322 433
                 //产品数据处理
323 434
                 $resProduct = $productModel->createObject('crm_business', $param, $business_id);
@@ -334,11 +445,6 @@ class Business extends Common
334 445
             $data_log['owner_user_id'] = $param['owner_user_id'];
335 446
             $data_log['remark'] = '新建商机';
336 447
             Db::name('CrmBusinessLog')->insert($data_log);
337
-
338
-            $data = [];
339
-            $data['business_id'] = $business_id;
340
-
341
-
342 448
             # 添加活动记录
343 449
             Db::name('crm_activity')->insert([
344 450
                 'type' => 2,
@@ -350,6 +456,11 @@ class Business extends Common
350 456
                 'create_time' => time(),
351 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 465
             return $data;
355 466
         } else {
@@ -366,6 +477,9 @@ class Business extends Common
366 477
      */
367 478
     public function updateDataById($param, $business_id = '')
368 479
     {
480
+        // 商机扩展表数据
481
+        $businessData = [];
482
+
369 483
         $productModel = new \app\crm\model\Product();
370 484
         $dataInfo = $this->getDataById($business_id);
371 485
         if (!$dataInfo) {
@@ -380,14 +494,11 @@ class Business extends Common
380 494
         }
381 495
 
382 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 502
             return false;
392 503
         }
393 504
 
@@ -408,6 +519,75 @@ class Business extends Common
408 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 593
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
@@ -422,13 +602,19 @@ class Business extends Common
422 602
             $param['is_end'] = $param['status_id'];
423 603
         }
424 604
         if ($this->update($param, ['business_id' => $business_id], true)) {
605
+            $data['business_id'] = $business_id;
425 606
             //产品数据处理
426 607
             $resProduct = $productModel->createObject('crm_business', $param, $business_id);
427 608
             //修改记录
428 609
             updateActionLog($param['user_id'], 'crm_business', $business_id, $dataInfo, $param);
429 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 618
             return $data;
433 619
         } else {
434 620
             $this->rollback();

+ 7
- 13
application/crm/model/BusinessStatus.php 查看文件

@@ -199,9 +199,7 @@ class BusinessStatus extends Common
199 199
 			// 提交事务
200 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 203
             return true;
206 204
 		} catch (\Exception $e) {
207 205
 			$this->error = '编辑失败';
@@ -230,13 +228,13 @@ class BusinessStatus extends Common
230 228
 
231 229
 	/**
232 230
 	 * [delDataById 根据id删除数据]
233
-	 * @param     string                   $id     [主键]
231
+	 * @param     string                   $param['id']     [主键]
234 232
 	 * @param     boolean                  $delSon [是否删除子孙数据]
235 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 238
 			$this->error = '删除失败';
241 239
 			return false;
242 240
 		}
@@ -249,16 +247,12 @@ class BusinessStatus extends Common
249 247
 		//启动事务
250 248
 		Db::startTrans();
251 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 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 257
             return true;
264 258
 		} catch(\Exception $e) {

+ 509
- 300
application/crm/model/Contacts.php 查看文件

@@ -6,181 +6,236 @@
6 6
 // +----------------------------------------------------------------------
7 7
 namespace app\crm\model;
8 8
 
9
+use app\admin\traits\FieldVerificationTrait;
9 10
 use think\Db;
10 11
 use app\admin\model\Common;
11
-use think\Request;
12 12
 use think\Validate;
13 13
 
14 14
 class Contacts extends Common
15 15
 {
16
-	/**
16
+    use FieldVerificationTrait;
17
+    
18
+    /**
17 19
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
18 20
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
19 21
      */
20
-	protected $name = 'crm_contacts';
22
+    protected $name = 'crm_contacts';
21 23
     protected $createTime = 'create_time';
22 24
     protected $updateTime = 'update_time';
23
-	protected $autoWriteTimestamp = true;
24
-
25
-	/**
25
+    protected $autoWriteTimestamp = true;
26
+    
27
+    /**
26 28
      * [getDataList 联系人list]
27
-     * @author Michael_xu
28 29
      * @param     [string]                   $map [查询条件]
29 30
      * @param     [number]                   $page     [当前页数]
30 31
      * @param     [number]                   $limit    [每页数量]
31 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 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 139
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
113 140
         $temporaryField = str_replace('_name', '', $order_field);
114 141
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
115 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 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 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 203
             foreach ($datetimeField as $key => $val) {
168 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 240
             $starWhere = ['user_id' => $user_id, 'target_id' => $v['contacts_id'], 'type' => 'crm_contacts'];
186 241
             $star = Db::name('crm_star')->where($starWhere)->value('star_id');
@@ -188,7 +243,7 @@ class Contacts extends Common
188 243
             # 日期
189 244
             $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
190 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 248
             $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
194 249
             # 负责人
@@ -196,95 +251,174 @@ class Contacts extends Common
196 251
         }
197 252
         $data = [];
198 253
         $data['list'] = $list;
199
-        $data['dataCount'] = $dataCount ? : 0;
254
+        $data['dataCount'] = $dataCount ?: 0;
200 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 283
         $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
225 284
         if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
226 285
             # 设置首要联系人,去除其他首要联系人状态
227 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 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 298
         // 处理日期(date)类型
240 299
         $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
241 300
         if (!empty($dateField)) {
242
-            foreach ($param AS $key => $value) {
301
+            foreach ($param as $key => $value) {
243 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 382
             Db::name('crm_activity')->insert([
255
-                'type'             => 2,
256
-                'activity_type'    => 3,
383
+                'type' => 2,
384
+                'activity_type' => 3,
257 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 394
             if (!empty($businessId)) {
267 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,52 +431,121 @@ class Contacts extends Common
297 431
      * @throws \think\exception\DbException
298 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 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 448
             $this->error = '无权操作';
312 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 470
             if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
337
-		}
471
+        }
338 472
         // 处理日期(date)类型
339 473
         $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
340 474
         if (!empty($dateField)) {
341
-            foreach ($param AS $key => $value) {
475
+            foreach ($param as $key => $value) {
342 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 550
         $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
348 551
         if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
@@ -353,20 +556,26 @@ class Contacts extends Common
353 556
             # 为客户添加第一个联系人默认设置成首要联系人
354 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,18 +586,18 @@ class Contacts extends Common
377 586
      * @throws \think\db\exception\ModelNotFoundException
378 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 601
         $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
393 602
         $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
394 603
         $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
@@ -405,43 +614,43 @@ class Contacts extends Common
405 614
         }
406 615
         $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
407 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 619
         if (!empty($userId)) {
411 620
             $grantData = getFieldGrantData($userId);
412 621
             $userLevel = isSuperAdministrators($userId);
413
-            foreach ($dataInfo AS $key => $value) {
622
+            foreach ($dataInfo as $key => $value) {
414 623
                 if (!$userLevel && !empty($grantData['crm_contacts'])) {
415 624
                     $status = getFieldGrantStatus($key, $grantData['crm_contacts']);
416
-
625
+                    
417 626
                     # 查看权限
418 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 636
      * @param ids 联系人ID数组
429 637
      * @param owner_user_id 变更负责人
430 638
      * @param is_remove 1移出,2转为团队成员
431
-     * @return            
432
-     */	
639
+     * @return
640
+     * @author Michael_xu
641
+     */
433 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,10 +664,10 @@ class Contacts extends Common
455 664
     {
456 665
         Db::name('crm_contacts')->where('customer_id', $customerId)->update(['primary' => 0]);
457 666
         Db::name('crm_contacts')->where(['customer_id' => $customerId, 'contacts_id' => $contactsId])->update(['primary' => 1]);
458
-
667
+        
459 668
         return true;
460 669
     }
461
-
670
+    
462 671
     /**
463 672
      * 获取跟进记录联系人
464 673
      *
@@ -472,7 +681,7 @@ class Contacts extends Common
472 681
     {
473 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,7 +697,7 @@ class Contacts extends Common
488 697
         $contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('contacts_id', $id)->find();
489 698
         # 创建人
490 699
         $realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname');
491
-
700
+        
492 701
         return [
493 702
             'create_user_id' => $realname,
494 703
             'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),

+ 233
- 49
application/crm/model/Contract.php 查看文件

@@ -6,14 +6,15 @@
6 6
 // +----------------------------------------------------------------------
7 7
 namespace app\crm\model;
8 8
 
9
+use app\admin\traits\FieldVerificationTrait;
9 10
 use think\Db;
10 11
 use app\admin\model\Common;
11 12
 use app\admin\model\Message;
12
-use think\Request;
13
-use think\Validate;
14 13
 
15 14
 class Contract extends Common
16 15
 {
16
+    use FieldVerificationTrait;
17
+
17 18
 	/**
18 19
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19 20
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
@@ -48,6 +49,7 @@ class Contract extends Common
48 49
     	$is_excel = $request['is_excel']; //导出
49 50
         $getCount = $request['getCount'];
50 51
         $contractIdArray = $request['contractIdArray']; // 待办事项提醒参数
52
+        $isMessage = !empty($request['isMessage']);
51 53
 
52 54
 		unset($request['scene_id']);
53 55
 		unset($request['search']);
@@ -57,6 +59,7 @@ class Contract extends Common
57 59
 		unset($request['is_excel']);
58 60
         unset($request['getCount']);
59 61
         unset($request['contractIdArray']);
62
+        unset($request['isMessage']);
60 63
 
61 64
         $request = $this->fmtRequest( $request );
62 65
 
@@ -85,28 +88,19 @@ class Contract extends Common
85 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 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 104
 		$order = ['contract.update_time desc'];	
111 105
 		$authMap = [];
112 106
 		if (!$partMap) {
@@ -126,14 +120,17 @@ class Contract extends Common
126 120
 		        $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
127 121
 		        $authMap['contract.owner_user_id'] = array('in',$auth_user_ids); 
128 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 136
 		//合同签约人 | 与高级筛选冲突,加一个is_array判断
@@ -146,6 +143,11 @@ class Contract extends Common
146 143
 		$userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
147 144
 		$structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure');  //部门类型
148 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 151
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
150 152
         $temporaryField = str_replace('_name', '', $order_field);
151 153
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@@ -209,6 +211,13 @@ class Contract extends Common
209 211
         		->orderRaw($order)
210 212
         		->group('contract.contract_id')
211 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 221
         foreach ($list as $k=>$v) {
213 222
         	$list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
214 223
         	$list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
@@ -216,21 +225,42 @@ class Contract extends Common
216 225
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
217 226
 			foreach ($userField as $key => $val) {
218 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 230
 			foreach ($structureField as $key => $val) {
222 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 234
             foreach ($datetimeField as $key => $val) {
226 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 257
         	$list[$k]['business_id_info']['business_id'] = $v['business_id'];
229 258
         	$list[$k]['business_id_info']['name'] = $v['business_name'];
230 259
         	$list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
231 260
         	$list[$k]['customer_id_info']['name'] = $v['customer_name'];
232 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 264
         	$moneyInfo = [];
235 265
         	$moneyInfo = $receivablesModel->getMoneyByContractId($v['contract_id']);
236 266
         	$list[$k]['unMoney'] = $moneyInfo['doneMoney'] ? : '0.00';
@@ -266,6 +296,8 @@ class Contract extends Common
266 296
             # 签约人姓名
267 297
             $orderNames = Db::name('admin_user')->whereIn('id', trim($v['order_user_id'], ','))->column('realname');
268 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 302
         $data = [];
271 303
         $data['list'] = $list;
@@ -364,18 +396,19 @@ class Contract extends Common
364 396
 	 */	
365 397
 	public function createData($param)
366 398
 	{
399
+        // 合同扩展表数据
400
+        $contractData = [];
401
+
367 402
 		$fieldModel = new \app\admin\model\Field();
368 403
 		$userModel = new \app\admin\model\User();
369 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 414
         if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
@@ -392,6 +425,75 @@ class Contract extends Common
392 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 499
         $param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
@@ -456,6 +558,12 @@ class Contract extends Common
456 558
             }
457 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 567
 			return $data;
460 568
 		} else {
461 569
 			$this->error = '添加失败';
@@ -472,6 +580,9 @@ class Contract extends Common
472 580
 	 */	
473 581
 	public function updateDataById($param, $contract_id = '')
474 582
 	{
583
+        // 合同扩展表数据
584
+        $contractData = [];
585
+
475 586
 		$productModel = new \app\crm\model\Product();
476 587
 		$userModel = new \app\admin\model\User();
477 588
 		$dataInfo = db('crm_contract')->where(['contract_id' => $contract_id])->find();
@@ -482,16 +593,13 @@ class Contract extends Common
482 593
 		}
483 594
 		$param['contract_id'] = $contract_id;
484 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 605
         if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
@@ -512,6 +620,75 @@ class Contract extends Common
512 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 693
 		if ($this->update($param, ['contract_id' => $contract_id], true)) {
517 694
 			//产品数据处理
@@ -549,6 +726,13 @@ class Contract extends Common
549 726
             }
550 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 736
 			return $data;
553 737
 		} else {
554 738
 			$this->error = '编辑失败';

+ 370
- 219
application/crm/model/Customer.php 查看文件

@@ -8,16 +8,15 @@ namespace app\crm\model;
8 8
 
9 9
 use app\admin\controller\ApiCommon;
10 10
 use app\admin\model\User;
11
+use app\admin\traits\FieldVerificationTrait;
11 12
 use think\Db;
12 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 14
 use think\response\Json;
17
-use think\Validate;
18 15
 
19 16
 class Customer extends Common
20 17
 {
18
+    use FieldVerificationTrait;
19
+
21 20
 	/**
22 21
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
23 22
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
@@ -48,30 +47,33 @@ class Customer extends Common
48 47
      */		
49 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 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 65
     	foreach ($unsetRequest as $v) {
68 66
     		unset($request[$v]);
69 67
     	}
70
-        $request = $this->fmtRequest( $request );
68
+
69
+    	# 格式化参数
70
+        $request    = $this->fmtRequest( $request );
71 71
         $requestMap = $request['map'] ? : [];
72 72
 		$sceneModel = new \app\admin\model\Scene();
73
-		# 默认条件
73
+
74
+		# 客户默认条件
74 75
         $customerMap = $this->getWhereByCustomer();
76
+
75 77
         # getCount是代办事项传来的参数,代办事项不需要使用场景
76 78
         $sceneMap = [];
77 79
         if (empty($getCount)) {
@@ -83,33 +85,32 @@ class Customer extends Common
83 85
                 $sceneMap = $sceneModel->getDefaultData('crm_customer', $user_id) ? : [];
84 86
             }
85 87
         }
88
+
89
+        # 普通筛选
86 90
 		$searchMap = [];
87 91
 		if ($search || $search == '0') {
88
-			//普通筛选
89 92
 			$searchMap = function($query) use ($search){
90 93
 			        $query->where('customer.name',array('like','%'.$search.'%'))
91 94
 			        	->whereOr('customer.mobile',array('like','%'.$search.'%'))
92 95
 			        	->whereOr('customer.telephone',array('like','%'.$search.'%'));
93 96
 			};
94 97
 		}
95
-		//优先级:普通筛选>高级筛选>场景
98
+
99
+		# 优先级:普通筛选 > 高级筛选 > 场景
96 100
         $map = [];
97 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 114
         $requestData = $this->requestData();
114 115
         $dashboardWhere = [];
115 116
         if ($requestData['a'] == 'indexlist' && $requestData['c'] == 'index') {
@@ -119,9 +120,9 @@ class Customer extends Common
119 120
             };
120 121
             unset($map['customer.create_time']);
121 122
         }
122
-        //权限
123
+
124
+        # 权限
123 125
         $authMap = [];
124
-        $auth_user_ids = [];
125 126
         if (!$partMap) {
126 127
             $a = 'index';
127 128
             if ($is_excel) $a = 'excelExport';
@@ -156,6 +157,7 @@ class Customer extends Common
156 157
             }
157 158
         }
158 159
 
160
+
159 161
         # 代办事项 - 待进入公海
160 162
         $remindWhere = [];
161 163
         if ($is_remind) {
@@ -163,7 +165,17 @@ class Customer extends Common
163 165
             $userIds[] = $user_id;
164 166
             $poolDays = $this->getPoolDay([], $userIds);
165 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 181
 		$dataCount = db('crm_customer')->alias('customer')
@@ -175,29 +187,35 @@ class Customer extends Common
175 187
         			->where($partMap)
176 188
         			->where($otherMap)
177 189
                     ->where($remindWhere)
190
+                    ->where($overdueWhere)
178 191
         			->count();
179 192
 
180 193
         if ($getCount == 1) {
181 194
 			$data['dataCount'] = $dataCount ? : 0;
182 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 207
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
190 208
         $temporaryField = str_replace('_name', '', $order_field);
191 209
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
192 210
             $order_field = $temporaryField;
193 211
         }
194
-		//排序
212
+		# 排序
195 213
 		if ($order_type && $order_field) {
196 214
 			$order = $fieldModel->getOrderByFormtype('crm_customer','customer',$order_field,$order_type);
197 215
 		} else {
198 216
 			$order = 'customer.update_time desc';
199 217
 		}
200
-
218
+  
201 219
 		$list = db('crm_customer')->alias('customer')
202 220
 				->where($map)
203 221
 				->where($dashboardWhere)
@@ -207,12 +225,11 @@ class Customer extends Common
207 225
 				->where($partMap)
208 226
 				->where($otherMap)
209 227
                 ->where($remindWhere)
228
+                ->where($overdueWhere)
210 229
         		->limit($request['offset'], $request['length'])
211 230
         		->field($indexField)
212 231
         		->orderRaw($order)
213 232
 				->select();
214
-        # 查询公海数据的条件
215
-        $poolWhere = [];
216 233
         $readAuthIds = $userModel->getUserByPer('crm', 'customer', 'read');
217 234
         $updateAuthIds = $userModel->getUserByPer('crm', 'customer', 'update');
218 235
 		$deleteAuthIds = $userModel->getUserByPer('crm', 'customer', 'delete');
@@ -231,29 +248,62 @@ class Customer extends Common
231 248
 			$business_count = array_column($business_count, null, 'customer_id');
232 249
 			$field_list = $fieldModel->getIndexFieldConfig('crm_customer', $user_id);
233 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 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 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 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 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 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 305
 				$list[$k]['business_count'] = $business_count[$v['customer_id']]['count'] ?: 0;
256
-	        	//权限
306
+	        	# 权限
257 307
 	        	$roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read');
258 308
 	        	$rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update');
259 309
 				$permission = [];
@@ -272,22 +322,16 @@ class Customer extends Common
272 322
                 $starWhere = ['user_id' => $user_id, 'target_id' => $v['customer_id'], 'type' => 'crm_customer'];
273 323
                 $star = Db::name('crm_star')->where($starWhere)->value('star_id');
274 324
                 $list[$k]['star'] = !empty($star) ? 1 : 0;
325
+
275 326
                 # 日期
276 327
                 $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
277 328
                 $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
278 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 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 336
         $data = [];
293 337
         $data['list'] = $list ? : [];
@@ -303,21 +347,31 @@ class Customer extends Common
303 347
 	 */	
304 348
 	public function createData($param)
305 349
 	{
350
+        unset($param['excel']);
351
+
352
+	    // 客户扩展表数据
353
+	    $customerData = [];
354
+
355
+	    $userId = $param['user_id'];
356
+
306 357
 		$fieldModel = new \app\admin\model\Field();
307
-		$userModel = new \app\admin\model\User();
308 358
 		$customerConfigModel = new \app\crm\model\CustomerConfig();
309
-		//添加上限检测
359
+
360
+		// 添加上限检测
310 361
 		if (!$customerConfigModel->checkData($param['create_user_id'],1)) {
311 362
 			$this->error = $customerConfigModel->getError();
312 363
 			return false;
313 364
 		}
365
+
314 366
 		// 获取客户时间
315 367
         $param['obtain_time'] = time();
316
-		//地址
368
+
369
+		// 地址
317 370
 		$param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
318 371
 		$param['deal_time'] = time(); //领取、分配时间
319 372
 		$param['deal_status'] = '未成交';		
320
-		//线索转客户
373
+
374
+		// 线索转客户
321 375
 		if ($param['leads_id']) {
322 376
 			$leadsData = $param;
323 377
 			$leadsData['create_user_id'] = $param['create_user_id'];
@@ -327,15 +381,17 @@ class Customer extends Common
327 381
             $leadsData['detail_address'] = $param['detail_address']	? : '';
328 382
 
329 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 395
         unset($param['customer_id']);
340 396
 
341 397
 		// 处理部门、员工、附件、多选类型字段
@@ -343,6 +399,7 @@ class Customer extends Common
343 399
 		foreach ($arrFieldAtt as $k=>$v) {
344 400
 			$param[$v] = arrayToString($param[$v]);
345 401
 		}
402
+
346 403
         // 处理日期(date)类型
347 404
         $dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
348 405
         if (!empty($dateField)) {
@@ -351,23 +408,94 @@ class Customer extends Common
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 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 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 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 499
             Db::name('crm_activity')->insert([
372 500
                 'type'             => 2,
373 501
                 'activity_type'    => 2,
@@ -377,6 +505,11 @@ class Customer extends Common
377 505
                 'update_time'      => time(),
378 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 514
 			return $data;
382 515
 		} else {
@@ -404,20 +537,26 @@ class Customer extends Common
404 537
 	 */
405 538
     public function updateDataById($param, $customer_id = '')
406 539
     {
540
+        // 客户扩展表数据
541
+        $customerData = [];
542
+
407 543
         $user_id = $param['user_id'];
408 544
         $dataInfo = $this->get($customer_id);
409 545
         if (!$dataInfo) {
410 546
             $this->error = '数据不存在或已删除';
411 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 553
         $userModel = new \app\admin\model\User();
417 554
         $auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'update');
418
-        //读写权限
555
+
556
+        // 读写权限
419 557
         $rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
420
-        //判断是否客户池数据
558
+
559
+        // 判断是否客户池数据
421 560
         if(empty($param['pool_id'])){
422 561
             $wherePool = $this->getWhereByPool();
423 562
             $resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $id])->where($wherePool)->find();
@@ -426,24 +565,23 @@ class Customer extends Common
426 565
                 return false;
427 566
             }
428 567
         }
429
-        $param['customer_id'] = $customer_id;
430
-        //过滤不能修改的字段
568
+
569
+        // 过滤不能修改的字段
431 570
         $unUpdateField = ['create_user_id','is_deleted','delete_time','user_id'];
432 571
         foreach ($unUpdateField as $v) {
433 572
             unset($param[$v]);
434 573
         }
435 574
         $param['deal_status'] = $dataInfo['deal_status'];
436 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 581
             return false;
445 582
         }
446
-        //地址
583
+
584
+        // 地址
447 585
         $param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
448 586
         if ($param['deal_status'] == '已成交' && $dataInfo->data['deal_status'] == '未成交') {
449 587
             $param['deal_time'] = time();
@@ -454,6 +592,7 @@ class Customer extends Common
454 592
         foreach ($arrFieldAtt as $k=>$v) {
455 593
             if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
456 594
         }
595
+
457 596
         // 处理日期(date)类型
458 597
         $dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
459 598
         if (!empty($dateField)) {
@@ -462,17 +601,97 @@ class Customer extends Common
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 676
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
677
+
678
+        // 修改数据
467 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 686
             updateActionLog($user_id, 'crm_customer', $customer_id, $dataInfo->data, $param);
473 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 695
             return $data;
477 696
         } else {
478 697
             $this->error = '编辑失败';
@@ -537,6 +756,12 @@ class Customer extends Common
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 765
         return $dataInfo;
541 766
    	}
542 767
 
@@ -671,94 +896,28 @@ class Customer extends Common
671 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 906
     public function getWhereByCustomer()
681 907
     {
682 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 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,31 +1608,22 @@ class Customer extends Common
1449 1608
      */
1450 1609
     public function getNearbyList($param)
1451 1610
     {
1452
-        $apiCommon = new ApiCommon();
1453 1611
         $userModel = new \app\admin\model\User();
1454 1612
 
1455
-        $poolStatus = checkPerByAction('crm', 'customer', 'pool');
1456
-
1457
-        # 客户
1458
-        $customerAuth = [];
1613
+        # 客户条件
1459 1614
         $customerWhere = [];
1460
-        if ((!empty($param['type']) && $param['type'] == 2) || !$poolStatus) {
1615
+        if (!empty($param['type']) && $param['type'] == 2) {
1461 1616
             $customerWhere = $this->getWhereByCustomer();
1462 1617
         }
1463 1618
 
1464
-        # 公海
1619
+        # 公海条件
1465 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 1623
             $model = '公海客户管理模块';
1469 1624
         }
1470 1625
 
1471
-        if (!empty($param['type']) && $param['type'] == 9 && !$poolStatus) {
1472
-            $model = '客户管理模块';
1473
-            return [];
1474
-        }
1475
-
1476
-        # 附近
1626
+        # 距离条件
1477 1627
         $lngLatRange = $this->getLngLatRange($param['lng'], $param['lat'], $param['distance']);
1478 1628
         $lngLatWhere = function ($query) use ($lngLatRange) {
1479 1629
             $query->where(['lng' => ['egt', $lngLatRange['minLng']]]);
@@ -1493,14 +1643,12 @@ class Customer extends Common
1493 1643
             ->where($customerWhere)
1494 1644
             ->where($poolWhere)
1495 1645
             ->where($lngLatWhere)
1496
-            ->where($customerAuth)
1497 1646
             ->field(['customer_id', 'name', 'address', 'detail_address', 'owner_user_id', 'lat', 'lng','next_time','last_time'])
1498 1647
             ->order('update_time', 'desc')
1499 1648
             ->select();
1500 1649
 
1501 1650
         # 组装数据
1502 1651
         foreach ($list as $key => $value) {
1503
-            # todo 暂时将查询写在循环中
1504 1652
             $ownerUserInfo = !empty($value['owner_user_id'])    ? $userModel->getUserById($value['owner_user_id']) : [];
1505 1653
             $ownerUserName = !empty($ownerUserInfo['realname']) ? $ownerUserInfo['realname'] : '';
1506 1654
             $list[$key]['owner_user_name'] = !empty($ownerUserName) ? $ownerUserName : '暂无负责人';
@@ -1585,15 +1733,18 @@ class Customer extends Common
1585 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 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 1743
         return [
1594 1744
             'obtain_time' => !empty($customer['obtain_time']) ? date('Y-m-d H:i:s', $customer['obtain_time']) : '',
1595 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 1748
             'create_time' => date('Y-m-d H:i:s', $customer['create_time']),
1598 1749
             'update_time' => date('Y-m-d H:i:s', $customer['update_time']),
1599 1750
             'last_time' => !empty($customer['last_time']) ? date('Y-m-d H:i:s', $customer['last_time']) : '',

+ 1
- 3
application/crm/model/CustomerConfig.php 查看文件

@@ -93,9 +93,7 @@ class CustomerConfig extends Common
93 93
                 $content='添加员工拥有、锁定客户限制';
94 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 97
             return $data;
100 98
 		} else {
101 99
 			$this->error = '创建失败';

+ 0
- 1
application/crm/model/Invoice.php 查看文件

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

+ 235
- 24
application/crm/model/Leads.php 查看文件

@@ -6,14 +6,14 @@
6 6
 // +----------------------------------------------------------------------
7 7
 namespace app\crm\model;
8 8
 
9
+use app\admin\traits\FieldVerificationTrait;
9 10
 use think\Db;
10 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 13
 class Leads extends Common
16 14
 {
15
+    use FieldVerificationTrait;
16
+
17 17
     /**
18 18
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19 19
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
@@ -43,6 +43,7 @@ class Leads extends Common
43 43
         $order_field = $request['order_field'];
44 44
         $order_type = $request['order_type'];
45 45
         $getCount = $request['getCount'];
46
+        $overdue = $request['overdue']; // 待办事项下需联系线索(逾期)
46 47
         unset($request['scene_id']);
47 48
         unset($request['search']);
48 49
         unset($request['user_id']);
@@ -50,6 +51,7 @@ class Leads extends Common
50 51
         unset($request['order_field']);
51 52
         unset($request['order_type']);
52 53
         unset($request['getCount']);
54
+        unset($request['overdue']);
53 55
 
54 56
         $request = $this->fmtRequest($request);
55 57
         $requestMap = $request['map'] ?: [];
@@ -74,13 +76,13 @@ class Leads extends Common
74 76
                     ->whereOr('leads.mobile', array('like', '%' . $search . '%'))
75 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 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 87
         $a = 'index';
86 88
         if ($is_excel) $a = 'excelExport';
@@ -105,6 +107,11 @@ class Leads extends Common
105 107
         $userField = $fieldModel->getFieldByFormType('crm_leads', 'user'); //人员类型
106 108
         $structureField = $fieldModel->getFieldByFormType('crm_leads', 'structure');  //部门类型
107 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 115
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
109 116
         $temporaryField = str_replace('_name', '', $order_field);
110 117
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@@ -121,23 +128,39 @@ class Leads extends Common
121 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 137
         $readAuthIds = $userModel->getUserByPer('crm', 'leads', 'read');
125 138
         $updateAuthIds = $userModel->getUserByPer('crm', 'leads', 'update');
126 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 141
         if (!empty($getCount) && $getCount == 1) {
129 142
             $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
130 143
             return $data;
131 144
         }
145
+
132 146
         $list = db('crm_leads')
133 147
             ->alias('leads')
134 148
             ->where($map)
135 149
             ->where($searchMap)
136 150
             ->where($authMap)
151
+            ->where($overdueWhere)
137 152
             ->limit($request['offset'], $request['length'])
138 153
             ->field(implode(',', $indexField))
139 154
             ->orderRaw($order)
140 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 164
         foreach ($list as $k => $v) {
142 165
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
143 166
             $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
@@ -145,15 +168,35 @@ class Leads extends Common
145 168
             $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
146 169
             foreach ($userField as $key => $val) {
147 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 173
             foreach ($structureField as $key => $val) {
151 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 177
             foreach ($datetimeField as $key => $val) {
155 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 201
             $permission = [];
159 202
             $is_read = 0;
@@ -201,14 +244,26 @@ class Leads extends Common
201 244
      */
202 245
     public function createData($param)
203 246
     {
247
+        unset($param['excel']);
248
+
249
+        // 线索扩展表数据
250
+        $leadsData = [];
251
+
204 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 267
             return false;
213 268
         }
214 269
 
@@ -224,11 +279,81 @@ class Leads extends Common
224 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 353
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
230 354
 
231 355
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
356
+            $data['leads_id'] = $this->leads_id;
232 357
             //修改记录
233 358
             updateActionLog($param['create_user_id'], 'crm_leads', $this->leads_id, '', '', '创建了线索');
234 359
             RecordActionLog($param['create_user_id'],'crm_leads','save',$param['name'],'','','新增了线索'.$param['name']);
@@ -245,8 +370,12 @@ class Leads extends Common
245 370
                 'contacts_ids'     => null,
246 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 379
             return $data;
251 380
         } else {
252 381
             $this->error = '添加失败';
@@ -262,6 +391,9 @@ class Leads extends Common
262 391
      */
263 392
     public function updateDataById($param, $leads_id = '')
264 393
     {
394
+        // 线索扩展表数据
395
+        $leadsData = [];
396
+
265 397
         $userModel = new \app\admin\model\User();
266 398
         $dataInfo = $this->getDataById($leads_id);
267 399
         if (!$dataInfo) {
@@ -284,12 +416,17 @@ class Leads extends Common
284 416
 
285 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 430
             return false;
294 431
         }
295 432
 
@@ -305,16 +442,90 @@ class Leads extends Common
305 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 516
         if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
311 517
 
312 518
         if ($this->update($param, ['leads_id' => $leads_id], true)) {
519
+            $data['leads_id'] = $leads_id;
313 520
             //修改记录
314 521
             updateActionLog($param['user_id'], 'crm_leads', $leads_id, $dataInfo, $param);
315 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 529
             return $data;
319 530
         } else {
320 531
             $this->error = '编辑失败';

+ 213
- 27
application/crm/model/Product.php 查看文件

@@ -6,17 +6,15 @@
6 6
 // +----------------------------------------------------------------------
7 7
 namespace app\crm\model;
8 8
 
9
+use app\admin\traits\FieldVerificationTrait;
9 10
 use think\Db;
10 11
 use app\admin\model\Common;
11 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 13
 use traits\model\SoftDelete;
16 14
 
17 15
 class Product extends Common
18 16
 {
19
-    use SoftDelete;
17
+    use SoftDelete, FieldVerificationTrait;
20 18
     
21 19
     protected $deleteTime = 'delete_time';
22 20
     
@@ -72,7 +70,7 @@ class Product extends Common
72 70
         //优先级:普通筛选>高级筛选>场景
73 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 74
         if (!empty($isStatus)) {
77 75
             $map['product.status'] = '上架';
78 76
         }
@@ -104,6 +102,11 @@ class Product extends Common
104 102
         $userField = $fieldModel->getFieldByFormType('crm_product', 'user'); //人员类型
105 103
         $structureField = $fieldModel->getFieldByFormType('crm_product', 'structure');  //部门类型
106 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 110
         # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
108 111
         $temporaryField = str_replace('_name', '', $order_field);
109 112
         if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
@@ -132,6 +135,13 @@ class Product extends Common
132 135
         $dataCount = db('crm_product')->alias('product')
133 136
             ->where($map)->where($authMap)
134 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 145
         foreach ($list as $k => $v) {
136 146
             $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
137 147
             $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
@@ -148,6 +158,26 @@ class Product extends Common
148 158
             foreach ($datetimeField as $key => $val) {
149 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 182
             $list[$k]['category_id_info'] = $v['category_name'];
153 183
             # 处理日期格式
@@ -169,20 +199,28 @@ class Product extends Common
169 199
      */
170 200
     public function createData($param)
171 201
     {
202
+        // 产品扩展表数据
203
+        $productData = [];
204
+
172 205
         $fieldModel = new \app\admin\model\Field();
173 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 218
                 return false;
219
+
184 220
             }
185 221
         }
222
+        unset($param['excel']);
223
+
186 224
         // 处理部门、员工、附件、多选类型字段
187 225
         $arrFieldAtt = $fieldModel->getArrayField('crm_product');
188 226
         foreach ($arrFieldAtt as $k => $v) {
@@ -195,6 +233,75 @@ class Product extends Common
195 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 307
         $category_id = $param['category_id'];
@@ -213,10 +320,15 @@ class Product extends Common
213 320
         }
214 321
         
215 322
         if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
323
+            $data['product_id'] = $this->product_id;
216 324
             updateActionLog($param['create_user_id'], 'crm_product', $this->product_id, '', '', '创建了产品');
217 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 332
             return $data;
221 333
         } else {
222 334
             $this->error = '添加失败';
@@ -232,6 +344,9 @@ class Product extends Common
232 344
      */
233 345
     public function updateDataById($param, $product_id = '')
234 346
     {
347
+        // 产品扩展表数据
348
+        $productData = [];
349
+
235 350
         $userModel = new \app\admin\model\User();
236 351
         $dataInfo = $this->getDataById($product_id);
237 352
         $productCategoryModel = model('ProductCategory');
@@ -254,18 +369,14 @@ class Product extends Common
254 369
         }
255 370
         
256 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 377
             return false;
266 378
         }
267 379
         
268
-        
269 380
         // 处理部门、员工、附件、多选类型字段
270 381
         $arrFieldAtt = $fieldModel->getArrayField('crm_product');
271 382
         foreach ($arrFieldAtt as $k => $v) {
@@ -278,6 +389,75 @@ class Product extends Common
278 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 463
         $category_id = $param['category_id'];
@@ -295,11 +475,17 @@ class Product extends Common
295 475
             }
296 476
         }
297 477
         if ($this->update($param, ['product_id' => $product_id], true)) {
478
+            $data['product_id'] = $product_id;
298 479
             //修改记录
299 480
             updateActionLog($param['user_id'], 'crm_product', $product_id, $dataInfo, $param);
300 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 489
             return $data;
304 490
         } else {
305 491
             $this->rollback();

+ 13
- 18
application/crm/model/ProductCategory.php 查看文件

@@ -62,9 +62,7 @@ class ProductCategory extends Common
62 62
 			$data = [];
63 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 66
             return $data;
69 67
 		} else {
70 68
 			$this->error = '添加失败';
@@ -93,12 +91,11 @@ class ProductCategory extends Common
93 91
 			$this->error = $validate->getError();
94 92
 			return false;
95 93
 		}
96
-
94
+		$user_id=$param['user_id'];
95
+        unset($param['user_id']);
97 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 99
             return true;
103 100
 		} else {
104 101
 			$this->error = '编辑失败';
@@ -108,19 +105,19 @@ class ProductCategory extends Common
108 105
 
109 106
 	/**
110 107
 	 * [delDataById 根据id删除数据]
111
-	 * @param     string                   $id     [主键]
108
+	 * @param     string                   $param['id']    [主键]
112 109
 	 * @param     boolean                  $delSon [是否删除子孙数据]
113 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 115
 			$this->error = '删除失败';
119 116
 			return false;
120 117
 		}
121 118
 		//分类下已有产品,则不能删除
122 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 121
 			$resDel = false;			
125 122
 		}
126 123
 		if ($delSon && is_numeric($id)) {
@@ -135,22 +132,20 @@ class ProductCategory extends Common
135 132
 			$this->error = '请先移除该类型及子类下的相关产品';
136 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 137
 		$this->startTrans();
141 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 143
 				if ($childIds) {
147 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 149
             $this->commit();
155 150
 			return true;
156 151
 		} catch(\Exception $e) {

+ 717
- 511
application/crm/model/Receivables.php
文件差異過大導致無法顯示
查看文件


+ 213
- 21
application/crm/model/ReceivablesPlan.php 查看文件

@@ -6,6 +6,7 @@
6 6
 // +----------------------------------------------------------------------
7 7
 namespace app\crm\model;
8 8
 
9
+use app\admin\traits\FieldVerificationTrait;
9 10
 use think\Db;
10 11
 use app\admin\model\Common;
11 12
 use app\crm\model\Contract as ContractModel;
@@ -14,6 +15,8 @@ use think\Validate;
14 15
 
15 16
 class ReceivablesPlan extends Common
16 17
 {
18
+    use FieldVerificationTrait;
19
+
17 20
 	/**
18 21
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
19 22
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
@@ -59,7 +62,8 @@ class ReceivablesPlan extends Common
59 62
 			$map['name'] = ['like', '%'.$map['search'].'%'];
60 63
 			unset($map['search']);
61 64
 		} else {
62
-			$map = where_arr($map, 'crm', 'receivables_plan', 'index'); //高级筛选
65
+            // 高级筛选
66
+			$map = advancedQuery($map, 'crm', 'receivables_plan', 'index');
63 67
 		}
64 68
 		if ($map['receivables_plan.owner_user_id']) {
65 69
 			$map['contract.owner_user_id'] = $map['receivables_plan.owner_user_id'];
@@ -99,12 +103,6 @@ class ReceivablesPlan extends Common
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 106
         $dataCount = db('crm_receivables_plan')
109 107
             ->alias('receivables_plan')
110 108
             ->join('__CRM_CONTRACT__ contract','receivables_plan.contract_id = contract.contract_id','LEFT')
@@ -147,7 +145,9 @@ class ReceivablesPlan extends Common
147 145
 	 * @return                            
148 146
 	 */	
149 147
 	public function createData($param)
150
-	{	
148
+	{
149
+	    $userId = $param['user_id'];
150
+	    unset($param['user_id']);
151 151
 		if (!$param['contract_id']) {
152 152
 			$this->error = '请先选择合同';
153 153
 			return false;
@@ -166,21 +166,115 @@ class ReceivablesPlan extends Common
166 166
 			$this->error = '提前提醒最大时间为 90 天';
167 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 181
 		if ($param['file_ids']) $param['file'] = arrayToString($param['file_ids']); //附件
176 182
 		//期数规则(1,2,3..)
177 183
 		$maxNum = db('crm_receivables_plan')->where(['contract_id' => $param['contract_id']])->max('num');
178 184
 		$param['num'] = $maxNum ? $maxNum+1 : 1;
179 185
 		//提醒日期
180 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 270
 		if ($this->data($param)->allowField(true)->save()) {
182 271
 			$data = [];
183 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 278
 			return $data;
185 279
 		} else {
186 280
 			$this->error = '添加失败';
@@ -196,6 +290,8 @@ class ReceivablesPlan extends Common
196 290
 	 */	
197 291
 	public function updateDataById($param, $plan_id = '')
198 292
 	{
293
+	    $userId = $param['user_id'];
294
+	    unset($param['user_id']);
199 295
 		$dataInfo = $this->getDataById($plan_id);
200 296
 		if (!$dataInfo) {
201 297
 			$this->error = '数据不存在或已删除';
@@ -208,18 +304,114 @@ class ReceivablesPlan extends Common
208 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 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 406
 		if ($this->allowField(true)->save($param, ['plan_id' => $plan_id])) {
221 407
 			$data = [];
222 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 415
 			return $data;
224 416
 		} else {
225 417
 			$this->error = '编辑失败';

+ 46
- 11
application/crm/model/Setting.php 查看文件

@@ -36,7 +36,7 @@ class Setting extends Common
36 36
         if (!is_array($param['types_id'])) {
37 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 40
 		if ($res == '1') {
41 41
             //同时关联其他模块(仅限客户模块)
42 42
             if (is_array($param['module']) && $param['types'] == 'crm_customer') {
@@ -49,9 +49,11 @@ class Setting extends Common
49 49
                         case 'crm_contacts' : $module_id = 'contacts_id'; break;
50 50
                         case 'crm_business' : $module_id = 'business_id'; break;
51 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 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,7 +72,7 @@ class Setting extends Common
70 72
      * @throws \think\Exception
71 73
      * @throws \think\exception\PDOException
72 74
      */
73
-    public function setVisitDay($status, $day)
75
+    public function setVisitDay($status, $day,$userId)
74 76
     {
75 77
         $status = intval($status);
76 78
         $day    = intval($day);
@@ -99,9 +101,7 @@ class Setting extends Common
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 105
         return true;
106 106
     }
107 107
 
@@ -124,7 +124,7 @@ class Setting extends Common
124 124
      * @param $param
125 125
      * @return bool
126 126
      */
127
-    public function setNumber($param)
127
+    public function setNumber($param,$userId)
128 128
     {
129 129
         $apiCommon = new ApiCommon();
130 130
 
@@ -176,9 +176,7 @@ class Setting extends Common
176 176
 
177 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 180
             return true;
183 181
         } catch (Exception $e) {
184 182
             Db::rollback();
@@ -186,4 +184,41 @@ class Setting extends Common
186 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 查看文件

@@ -47,7 +47,7 @@ trait AutoNumberTrait
47 47
                 
48 48
                 if ($currentDate[$value['reset']] != $lastDate[$value['reset']]) {
49 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 查看文件

@@ -90,192 +90,4 @@ class Addresslist extends ApiCommon
90 90
 
91 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 查看文件

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

+ 19
- 1
application/oa/controller/Log.php 查看文件

@@ -38,7 +38,8 @@ class Log extends ApiCommon
38 38
                 'activitycount',
39 39
                 'activitylist',
40 40
                 'querylog',
41
-                'onebulletin'
41
+                'onebulletin',
42
+                'favourupdate'
42 43
             ]
43 44
         ];
44 45
         Hook::listen('check_auth', $action);
@@ -331,6 +332,7 @@ class Log extends ApiCommon
331 332
         $param = $this->param;
332 333
         $userInfo = $this->userInfo;
333 334
         $log_id = $param['log_id'];
335
+        $param['user_id']=$userInfo['id'];
334 336
         if ($log_id) {
335 337
             $dataInfo = db('oa_log')->where(['log_id' => $log_id])->find();
336 338
             $adminTypes = adminGroupTypes($userInfo['id']);
@@ -494,4 +496,20 @@ class Log extends ApiCommon
494 496
         $data = $TaskLogic->queryLog($param);
495 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 查看文件

@@ -243,7 +243,11 @@ class LogLogic extends Common
243 243
             $query->where('create_time', array('between', $between_time))
244 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 249
         $customerNum = Db::name('CrmCustomer')
250
+            ->where($userMap)
247 251
             ->where($logMap)
248 252
             ->count();
249 253
         $businessNum = Db::name('CrmBusiness')
@@ -304,21 +308,20 @@ class LogLogic extends Common
304 308
         if ($search) {
305 309
             $map['name'] = array('like', '%' . $search . '%');
306 310
         }
307
-        $customerModel=new \app\crm\model\Customer();
308
-        $customerMap =$customerModel->getWhereByCustomer();
309 311
         $type = $param['log_type'];
310 312
         switch ($type) {
311 313
             case '1':
312 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 319
                 $activityData = Db::name('CrmCustomer')
316 320
                     ->alias('customer')
317 321
                     ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
318 322
                     ->where($map)
319 323
                     ->where($map1)
320
-                    ->where($customerMap)
321
-                    ->whereOr($logMap)
324
+                    ->where($logMap)
322 325
                     ->order('customer.customer_id desc')
323 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 327
                     ->page($param['page'],$param['limit'])
@@ -331,7 +334,8 @@ class LogLogic extends Common
331 334
                     ->join('__ADMIN_USER__ user', 'user.id = customer.owner_user_id', 'LEFT')
332 335
                     ->where($map)
333 336
                     ->where($map1)
334
-                    ->where($customerMap)
337
+                    ->where($logMap)
338
+                    ->where('customer.owner_user_id' , ['neq', 0])
335 339
                     ->count();
336 340
                 break;
337 341
             case '2':
@@ -378,20 +382,19 @@ class LogLogic extends Common
378 382
                 $activityData = Db::name('CrmContract')
379 383
                     ->alias('contract')
380 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 385
                     ->where($map)
383 386
                     ->where($map3)
384 387
                     ->order('contract.contract_id desc')
385 388
                     ->page($param['page'],$param['limit'])
386
-                    ->field(['contract.contract_id',
389
+                    ->field([
390
+                        'contract.contract_id',
387 391
                         'contract.name',
388 392
                         'contract.create_time',
389 393
                         'contract.check_status',
390 394
                         'contract.order_date',
391 395
                         'contract.money',
392 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 398
                     ->select();
396 399
                 foreach ($activityData as $k => $v){
397 400
                     if(!empty($v['contract_id'])){
@@ -835,7 +838,7 @@ class LogLogic extends Common
835 838
         } else if ($param['page'] != 1 && (int)($param['page'] * $param['limit']) < $dataCount) {
836 839
             $data['firstPage'] = false;
837 840
             $data['lastPage'] = false;
838
-        } else if ($param['page'] == 1) {
841
+        } else if ($param['page'] == 1  && (int)($param['page'] * $param['limit']) < $dataCount ) {
839 842
             $data['firstPage'] = true;
840 843
             $data['lastPage'] = false;
841 844
         }
@@ -1015,4 +1018,38 @@ class LogLogic extends Common
1015 1018
         $data['list'] = $item;
1016 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 查看文件

@@ -311,6 +311,5 @@ class UserLogic
311 311
         if ($asc >= -10247 && $asc <= -10247) {
312 312
             return 'Z';
313 313
         }
314
-//        return '#';
315 314
     }
316 315
 }

+ 3
- 0
application/oa/model/Event.php 查看文件

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

+ 45
- 24
application/oa/model/Examine.php 查看文件

@@ -6,15 +6,16 @@
6 6
 // +----------------------------------------------------------------------
7 7
 namespace app\oa\model;
8 8
 
9
+use app\admin\traits\FieldVerificationTrait;
9 10
 use think\Db;
10 11
 use app\admin\model\Common;
11 12
 use app\admin\model\Message;
12
-use think\Request;
13 13
 use think\Validate;
14
-use app\admin\model\Field;
15 14
 
16 15
 class Examine extends Common
17 16
 {
17
+    use FieldVerificationTrait;
18
+
18 19
     /**
19 20
      * 为了数据库的整洁,同时又不影响Model和Controller的名称
20 21
      * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
@@ -284,12 +285,19 @@ class Examine extends Common
284 285
             $this->error = '参数错误';
285 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 301
             return false;
294 302
         }
295 303
         
@@ -297,8 +305,8 @@ class Examine extends Common
297 305
         
298 306
         $fileArr = $param['file_id']; //接收表单附件
299 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 310
         if ($this->data($param)->allowField(true)->save()) {
303 311
             //处理自定义字段数据
304 312
             $resData = $examineDataModel->createData($param, $this->examine_id);
@@ -394,7 +402,9 @@ class Examine extends Common
394 402
         $examineCategoryModel = new \app\oa\model\ExamineCategory();
395 403
         $examineDataModel = new \app\oa\model\ExamineData();
396 404
         $create_user_id = $param['create_user_id'];
405
+        $userId = $param['user_id'];
397 406
         unset($param['id']);
407
+        unset($param['user_id']);
398 408
         $dataInfo = db('oa_examine')->where(['examine_id' => $examine_id])->find();
399 409
         if (!$dataInfo) {
400 410
             $this->error = '数据不存在或已删除';
@@ -409,12 +419,18 @@ class Examine extends Common
409 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 434
             return false;
419 435
         }
420 436
         
@@ -524,7 +540,6 @@ class Examine extends Common
524 540
     public function getDataById($id = '')
525 541
     {
526 542
         $examineData = new \app\oa\model\ExamineData();
527
-        $fieldModel = new \app\admin\model\Field();
528 543
         $fileModel = new \app\admin\model\File();
529 544
         $userModel = new \app\admin\model\User();
530 545
         $recordModel = new \app\admin\model\Record();
@@ -549,14 +564,21 @@ class Examine extends Common
549 564
         $dataInfo['create_time'] = $dataInfo['create_time'] ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;;
550 565
         $realname=$userModel->getUserById($dataInfo['create_user_id']);
551 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 582
         $relationArr = $recordModel->getListByRelationId('examine', $id);
561 583
         $dataInfo['businessList'] = $relationArr['businessList'];
562 584
         $dataInfo['contactsList'] = $relationArr['contactsList'];
@@ -604,7 +626,6 @@ class Examine extends Common
604 626
         $where = [];
605 627
         $where['module'] = 'oa_examine';
606 628
         $where['module_id'] = $id;
607
-        $newFileList = [];
608 629
         $newFileList = $fileModel->getDataList($where, 'all');
609 630
         foreach ($newFileList['list'] as $val) {
610 631
             if ($val['types'] == 'file') {

+ 1
- 3
application/oa/model/ExamineCategory.php 查看文件

@@ -249,9 +249,7 @@ class ExamineCategory extends Common
249 249
             $data['delete_user_id'] = $user_id;
250 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 253
             $this->commit();
256 254
             return true;
257 255
         } catch (\Exception $e) {

+ 19
- 10
application/oa/model/ExamineData.php 查看文件

@@ -37,20 +37,29 @@ class ExamineData extends Common
37 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 38
 		$data = [];
39 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 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 60
 		if ($data) {
61
+		    db('oa_examine_data')->where('examine_id', $examine_id)->delete();
62
+//		    print_r($data);exit;
54 63
 			$resData = db('oa_examine_data')->insertAll($data);
55 64
 			if (!$resData) {
56 65
 				$this->error = '添加失败';

+ 33
- 18
application/oa/model/Log.php 查看文件

@@ -40,10 +40,8 @@ class Log extends Common
40 40
         $fileModel = new \app\admin\model\File();
41 41
         $commonModel = new \app\admin\model\Comment();
42 42
         $recordModel = new \app\admin\model\Record();
43
-        
44 43
         $user_id = $request['read_user_id'];
45 44
         $by = $request['by'] ?: '';
46
-        
47 45
         $map = [];
48 46
         $search = $request['search'];
49 47
         if (isset($request['search']) && $request['search']) {
@@ -130,6 +128,9 @@ class Log extends Common
130 128
             $list[$k]['imgList'] = $imgList ?: [];
131 129
             $list[$k]['sendUserList'] = $userModel->getDataByStr($v['send_user_ids']) ?: [];
132 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 134
             $param['type_id'] = $v['log_id'];
134 135
             $param['type'] = 'oa_log';
135 136
             $list[$k]['replyList'] = $commonModel->read($param);
@@ -174,17 +175,17 @@ class Log extends Common
174 175
         $data = [];
175 176
         $data['page']['list'] = $list;
176 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 189
         return $data;
189 190
     }
190 191
     
@@ -375,9 +376,7 @@ class Log extends Common
375 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 380
             return $data;
382 381
         } else {
383 382
             $this->error = '编辑失败';
@@ -453,8 +452,6 @@ class Log extends Common
453 452
      */
454 453
     public function delDataById($param)
455 454
     {
456
-        $user=new ApiCommon();
457
-        $userInfo=$user->userInfo;
458 455
         $map['log_id'] = $param['log_id'];
459 456
         $dataInfo = $this->get($map['log_id']);
460 457
         if (!$dataInfo) {
@@ -469,7 +466,7 @@ class Log extends Common
469 466
             $fileModel->delRFileByModule('oa_log', $param['log_id']);
470 467
             //删除相关评论
471 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 471
             Db::name('crm_activity')->where(['activity_type' => 8, 'activity_type_id' => $param['log_id']])->delete();
475 472
             return true;
@@ -478,4 +475,22 @@ class Log extends Common
478 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 查看文件

@@ -158,15 +158,16 @@ class work extends ApiCommon
158 158
 
159 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 171
         return resultArray(['data' => $workInfo]);
171 172
     }
172 173
 
@@ -288,6 +289,7 @@ class work extends ApiCommon
288 289
     {   
289 290
         $param = $this->param;
290 291
         $userInfo = $this->userInfo;
292
+        $userId=$userInfo['id'];
291 293
         if (!$param['work_id'] || !$param['owner_user_id']) {
292 294
             return resultArray(['error'=>'参数错误']);
293 295
         }
@@ -301,7 +303,7 @@ class work extends ApiCommon
301 303
 //            header('Content-Type:application/json; charset=utf-8');
302 304
 //            exit(json_encode(['code'=>102,'error'=>'无权操作']));
303 305
 //        }
304
-        $res = $workModel->delOwner($param);
306
+        $res = $workModel->delOwner($param,$userId);
305 307
         if ($res) {
306 308
             
307 309
             return resultArray(['data'=>'操作成功']);
@@ -381,7 +383,7 @@ class work extends ApiCommon
381 383
 //            header('Content-Type:application/json; charset=utf-8');
382 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 387
         if ($ret) {
386 388
             return resultArray(['data'=>'操作成功']);
387 389
         } else {

+ 10
- 23
application/work/model/Task.php 查看文件

@@ -330,6 +330,11 @@ class Task extends Common
330 330
             ->select();
331 331
         $complete = 0;
332 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 338
             $subTaskList[$key]['thumb_img'] = $value['thumb_img'] ? getFullPath($value['thumb_img']) : '';
334 339
             $subTaskList[$key]['stop_time'] = !empty($value['stop_time']) ? date('Y-m-d', $value['stop_time']) : null;
335 340
             if ($value['status'] == 5) ++$complete;
@@ -442,8 +447,6 @@ class Task extends Common
442 447
                 $datalog['task_id'] = $task_id;
443 448
                 $datalog['work_id'] = $param['work_id'] ?: '';
444 449
                 $ret = $taskLog->newTaskLog($datalog);
445
-                //操作日志
446
-//                actionLog($task_id, '', '', '新建了任务');
447 450
                 //抄送站内信
448 451
                 (new Message())->send(
449 452
                     Message::TASK_ALLOCATION,
@@ -480,8 +483,6 @@ class Task extends Common
480 483
                 }
481 484
                 db('work_task_file')->insertAll($fileData);
482 485
             }
483
-            $user=new ApiCommon();
484
-            $userInfo=$user->userInfo;
485 486
             # 添加子任务
486 487
             if (!empty($subtask)) {
487 488
                 $subtaskData = [];
@@ -503,15 +504,10 @@ class Task extends Common
503 504
                 }
504 505
                 Db::name('task')->insertAll($subtaskData);
505 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 511
             return $task_id;
516 512
         } else {
517 513
             $this->error = '添加失败';
@@ -701,16 +697,13 @@ class Task extends Common
701 697
             if (!$param['pid']) {
702 698
                 $LogModel = new LogModel();
703 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 700
                 if(empty($name)){
708 701
                     if(!empty($param['description'])){
709 702
                         $name='描述';
710 703
                     }
711 704
                 }
712 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 707
                 $resRelation = Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->find();
715 708
                 if ($resRelation) {
716 709
                     Db::name('TaskRelation')->where(['task_id' => $param['task_id']])->update($rdata); //更新关联关系
@@ -847,11 +840,7 @@ class Task extends Common
847 840
         $dataInfo = json_decode(json_encode($dataInfo), true);
848 841
         $flag = $this->where(['task_id' => $param['task_id']])->update($data);
849 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 844
             return true;
856 845
         } else {
857 846
             $this->error = '归档失败';
@@ -872,9 +861,7 @@ class Task extends Common
872 861
         $flag = $this->where(['task_id' => $param['task_id']])->setField('is_archive', 0);
873 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 865
             return true;
879 866
         } else {
880 867
             $this->error = '操作失败';

+ 20
- 22
application/work/model/Work.php 查看文件

@@ -76,7 +76,8 @@ class Work extends Common
76 76
 			$ownerData['work_id']        = $workId;
77 77
 			$ownerData['create_user_id'] = $createUserId;
78 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 82
 			$this->addOwner($ownerData);
82 83
 
@@ -173,9 +174,7 @@ class Work extends Common
173 174
 			$datalog['work_id'] = $param['work_id'];
174 175
 			$datalog['user_id'] = $userId;
175 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 178
             return true;
180 179
 		} else {
181 180
 			$this->error = '重命名失败';
@@ -227,9 +226,7 @@ class Work extends Common
227 226
 			$data['status'] = 3;
228 227
 			$data['archive_time'] = time();
229 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 230
             return true;
234 231
 		} else {
235 232
 			$this->error = '归档失败';
@@ -268,7 +265,7 @@ class Work extends Common
268 265
      * @param
269 266
      * @return
270 267
      */	
271
-	public function arRecover($work_id='')
268
+	public function arRecover($work_id='',$userId)
272 269
 	{
273 270
 		if (!$work_id) {
274 271
 			$this->error = '参数错误';
@@ -281,9 +278,7 @@ class Work extends Common
281 278
 		$this->where($map)->setField('status',1);
282 279
 		$map['status'] = 3;
283 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 283
         return true;
289 284
 	}
@@ -301,8 +296,6 @@ class Work extends Common
301 296
 			$this->error = '项目创建人不可以退出';
302 297
 			return false;
303 298
 		}
304
-		$user=new ApiCommon();
305
-		$userInfo=$user->userInfo;
306 299
 		//从项目成员中移除
307 300
 		db('work_user')->where(['work_id' => $work_id,'user_id' => $user_id])->delete();
308 301
 		$str = ','.$user_id.',';
@@ -317,13 +310,13 @@ class Work extends Common
317 310
 				$new_own_user_id = str_replace($str,',',$value['owner_user_id']);
318 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 314
 				$data['main_user_id'] = '';
322 315
 			}
323 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 320
         return true;
328 321
 	}
329 322
 
@@ -356,7 +349,7 @@ class Work extends Common
356 349
 			$data['types'] = 0;
357 350
 			if ($v == $create_user_id) {
358 351
 				$data['types'] = 1;
359
-				$group_id = 1;
352
+				$group_id = $param['group_id'];
360 353
 			} else {
361 354
 				# 默认角色
362 355
 				$group_id = !empty($param['group_id']) ? $param['group_id'] : db('admin_group')->where(['pid' => 5, 'system' => 1])->order('id asc')->value('id');
@@ -380,7 +373,7 @@ class Work extends Common
380 373
      * @param
381 374
      * @return
382 375
      */	
383
-	public function delOwner($param)
376
+	public function delOwner($param,$userId)
384 377
 	{
385 378
 		$work_id = $param['work_id'];
386 379
 		$workUserInfo = db('work_user')->where(['work_id' => $work_id,'user_id' => $param['owner_user_id']])->find();
@@ -403,11 +396,9 @@ class Work extends Common
403 396
 			$this->error = '删除失败,请重试!';
404 397
 			return false;
405 398
 		}
406
-        $user=new ApiCommon();
407
-        $userInfo=$user->userInfo;
408 399
         $user= new \app\admin\model\User();
409 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 402
         return true;
412 403
 	}
413 404
 	
@@ -423,7 +414,14 @@ class Work extends Common
423 414
 			$workInfo = $this->get($param['work_id']);
424 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 425
 			} else {
428 426
 				// $exp = new \think\db\Expression('field(types,1,0,2)');
429 427
 				$list = db('work_user')

+ 2
- 6
application/work/model/WorkClass.php 查看文件

@@ -69,9 +69,7 @@ class WorkClass extends Model
69 69
 			$data['order_id'] = $max_order_id ? $max_order_id+1 : 0;
70 70
 			$this->insert($data);
71 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 73
             return true;
76 74
 		} catch(\Exception $e) {
77 75
 			$this->rollback();
@@ -95,9 +93,7 @@ class WorkClass extends Model
95 93
 			$this->error = '重命名失败';
96 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 98
         return true;
103 99
 	}

+ 2882
- 0
composer.lock
文件差異過大導致無法顯示
查看文件


+ 8
- 4
config/config.php 查看文件

@@ -182,16 +182,20 @@ return [
182 182
     'cache'                  => [
183 183
         // 驱动方式
184 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 192
         'prefix' => '',
189 193
         // 缓存有效期 0表示永久缓存
190 194
         'expire' => 86400*30,
195
+        // 缓存保存目录
196
+        'path'   => CACHE_PATH,
191 197
         // 禁用缓存子目录
192 198
         'cache_subdir' => false,
193
-        // 密码
194
-        'password' => ''
195 199
     ],
196 200
 
197 201
     // +----------------------------------------------------------------------

+ 39
- 0
config/database_template.php 查看文件

@@ -0,0 +1,39 @@
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 查看文件

@@ -344,7 +344,29 @@ return [
344 344
     'admin/setting/customerLevel' => ['admin/setting/customerLevel', ['method' => 'POST']],
345 345
     //【设置】公海字段
346 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 370
 	// MISS路由
349 371
 	'__miss__'  => 'admin/base/miss',
350 372
 ];

+ 26
- 5
config/route_crm.php 查看文件

@@ -298,7 +298,9 @@ return [
298 298
     'crm/invoice/count' => ['crm/invoice/count', ['method' => 'POST']],
299 299
     // 【发票】重置开票信息
300 300
     'crm/invoice/resetInvoiceStatus' => ['crm/invoice/resetInvoiceStatus', ['method' => 'POST']],
301
-
301
+    // 【发票】导出
302
+    'crm/invoice/excelExport' => ['crm/invoice/excelExport', ['method' => 'POST']],
303
+    
302 304
     // 【发票-开户行】列表
303 305
     'crm/invoiceInfo/index' => ['crm/invoiceInfo/index', ['method' => 'POST']],
304 306
     // 【发票-开户行】详情
@@ -380,7 +382,9 @@ return [
380 382
     'crm/index/queryDataInfo' => ['crm/index/queryDataInfo', ['method' => 'POST']],
381 383
     // 【获取自动编号开启状态】
382 384
     'crm/index/autoNumberStatus' => ['crm/index/autoNumberStatus', ['method' => 'POST']],
383
-
385
+    // 【商机阶段列表】
386
+    'crm/index/businessList' => ['crm/index/businessList', ['method' => 'POST']],
387
+    
384 388
     // 【获取仪表盘布局】
385 389
     'crm/index/dashboard' => ['crm/index/dashboard', ['method' => 'POST']],
386 390
     // 【修改仪表盘布局】
@@ -477,7 +481,7 @@ return [
477 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 486
     'crm/activity/excelImport' => ['crm/activity/excelImport', ['method' => 'POST']],
483 487
     //跟进记录导出
@@ -495,10 +499,27 @@ return [
495 499
     'crm/market/enables' => ['crm/market/enables', ['method' => 'POST']],
496 500
     //市场活动状态删除
497 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 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 523
     // MISS路由
503 524
     '__miss__' => 'admin/base/miss',
504 525
 ];

+ 5
- 2
config/route_oa.php 查看文件

@@ -162,6 +162,8 @@ return [
162 162
     'oa/log/queryLog' => ['oa/log/queryLog', ['method' => 'POST']],
163 163
     //日志销售简报
164 164
     'oa/log/oneBulletin' => ['oa/log/oneBulletin', ['method' => 'POST']],
165
+    //日志销售简报
166
+    'oa/log/favourUpdate' => ['oa/log/favourUpdate', ['method' => 'POST']],
165 167
     
166 168
     // 【审批】类型列表
167 169
 	'oa/examine/category'=>['oa/examine/category', ['method' => 'POST']],
@@ -203,8 +205,9 @@ return [
203 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 211
 	// MISS路由
209 212
 	'__miss__'  => 'admin/base/miss',
210 213
 ];

+ 2
- 2
config/version.php 查看文件

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

二進制
favicon.ico 查看文件


+ 1
- 0
index.html
文件差異過大導致無法顯示
查看文件


+ 4
- 0
nginx.htaccess 查看文件

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

+ 589
- 252
public/sql/5kcrm.sql
文件差異過大導致無法顯示
查看文件


+ 0
- 0
public/sql/5kcrm_all.sql 查看文件


部分文件因文件數量過多而無法顯示