Browse Source

新增客户导入功能

yb 6 months ago
parent
commit
f5c310a60c

+ 12 - 0
app/admin/controller/consultant/CustomController.php

@@ -212,4 +212,16 @@ class CustomController extends Curd
     {
         return CustomService::statisticsMonth();
     }
+
+    /**
+     * Notes: 导入客户
+     * User: yb
+     * Date: 2024/9/10
+     * Time: 10:29
+     */
+    public function importCustom(Request $request)
+    {
+        $params = $request->post();
+        return CustomService::import($params);
+    }
 }

+ 1 - 1
app/admin/service/consultant/ConsultantService.php

@@ -53,7 +53,7 @@ class ConsultantService
         $paginator = Consultant::where(function ($query) use ($whereDept, $whereTopDept) {
                 $query->orWhere($whereDept)
                 ->orWhere($whereTopDept);
-        })->where($where)->paginate($limit, '*', 'page', $page);
+        })->where($where)->orderBy('id', 'DESC')->paginate($limit, '*', 'page', $page);
         $total = $paginator->total();
         $items = $paginator->items();
         if (!empty($items)) {

+ 194 - 7
app/admin/service/consultant/CustomService.php

@@ -11,6 +11,11 @@ use app\model\MarketCustomerFollow;
 use app\model\MarketCustomerLogs;
 use app\model\Member;
 use app\model\SysDept;
+use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+use PhpOffice\PhpSpreadsheet\Reader\Csv;
+use PhpOffice\PhpSpreadsheet\Reader\Xls;
+use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
 use support\Db;
 use support\exception\BusinessException;
 use support\Request;
@@ -1104,13 +1109,6 @@ class CustomService
         return substr_replace($val, '****', 3, 4);
     }
 
-    /**
-     * Notes: 判客指定顾问
-     * User: yb
-     * Date: 2024/9/5
-     * Time: 15:50
-     * @param $params
-     */
     /**
      * Notes: 指定顾问
      * User: yb
@@ -1171,4 +1169,193 @@ class CustomService
 
 
     }
+
+    /**
+     * Notes: 导入客户
+     * User: yb
+     * Date: 2024/9/10
+     * Time: 10:30
+     * @param $params
+     */
+    public static function import($params)
+    {
+        if (empty($params['path'])) {
+            return json_fail('文件地址不能为空');
+        }
+        $path = 'public'.$params['path'];
+        if (is_file($path)) {
+            $teamKeys = [];
+            //查询顾问信息
+            $teamData = Db::table('consultant')
+                ->leftJoin('sys_dept', 'consultant.dept_id', '=', 'sys_dept.dept_id')
+                ->select(['consultant.id', 'consultant.name', 'sys_dept.dept_name', 'sys_dept.dept_id'])
+                ->whereNull('consultant.deleted_at')
+                ->get();
+            if (!($teamData->isEmpty())) {
+                foreach ($teamData as $item) {
+                    $key = $item->name.'-'.$item->dept_name;
+                    $teamKeys[$key] = [
+                        'consultant_id' => $item->id,
+                        'dept_id' => $item->dept_id,
+                        'name' => $item->name,
+                        'dept_name' => $item->dept_name
+                    ];
+                }
+            }
+            $data = self::readExcel($path);
+//            $fields = ['到访时间', '客户姓名', '客户手机号', 'A类', 'B类', 'C类', 'D类', '健康顾问', '报备人', '团队'];
+            if (empty($data)) {
+                return json_fail('无可导入内容');
+            } else {
+                $sucNums = 0;
+                $errNums = 0;
+                $validate = '/^1\d{10}$/';
+                Db::beginTransaction();
+                try {
+                    foreach ($data as $key => $val) {
+                        if ($val[3] == 1) {$level = 1;} else if ($val[4] == 1) {$level = 2;} else if ($val[5] == 1) {$level = 3;} else if ($val[6] == 1) {$level = 4;}
+                        $line = '第'.($key + 2).'行:';
+                        if (empty($val[7]) && empty($val[8])) {
+                            return json_fail($line.'报备人和顾问必须存在其中之一');
+                        }
+                        if (empty($val[9])) {
+                            return json_fail($line.'无团队信息');
+                        }
+                        if ($val[0] == '1970-01-01 08:00:00') {
+                            return json_fail($line.'日期格式错误');
+                        }
+                        if (empty($val[2])) {
+                            return json_fail($line.'手机号不能为空');
+                        }
+                        if (!preg_match($validate, $val[2])) {
+                            return json_fail($line.'手机号格式非法');
+                        }
+                        $consultantName = $val[7];
+                        $reportName = $val[8];
+                        $teamName = $val[9];
+                        $consultantKey = $consultantName.'-'.$teamName;
+                        $consultantId = $teamKeys[$consultantKey]['consultant_id'] ?? 0;
+                        $reportKey = $reportName.'-'.$teamName;
+                        $reportConsultantId = $teamKeys[$reportKey]['consultant_id'] ?? 0;
+                        if ($consultantId <= 0 && $reportConsultantId <= 0) {
+                            return json_fail($line.'健康顾问或报备人都不存在');
+                        }
+                        if ($consultantId > 0) {
+                            $deptId = $teamKeys[$consultantKey]['dept_id'] ?? 0;
+                        }
+                        if ($reportConsultantId > 0) {
+                            $deptId = $teamKeys[$reportKey]['dept_id'] ?? 0;
+                        } else {
+                            if ($consultantId > 0) {
+                                $reportConsultantId = $consultantId;
+                            }
+                        }
+                        if (empty($deptId)) {
+                            return json_fail($line.'团队不存在');
+                        }
+                        if (MarketCustomer::checkCustomExists($val[2])) {
+                            return json_fail($line.'客户已转到访,无法二次录入');
+                        }
+                        //查看手机号是否存在
+                        $insertData = [
+                            'name' => $val[1],
+                            'mobile' => $val[2],
+                            'level' => $level ?? null,
+                            'consultant_id' => $consultantId,
+                            'report_consultant_id' => $reportConsultantId,
+                            'create_consultant_id' => $reportConsultantId,
+                            'dept_id' => $deptId,
+                            'belong_status' => 1,
+                            'current_status' => 1,
+                            'check_status' => 1,
+                            'type' => 1,
+                            'visit_time' => time(),
+                            'created_at' => strtotime($val[0]),
+                        ];
+                        $result = Db::table('market_customer')->insert($insertData);
+                        if ($result) {
+                            $sucNums++;
+                        } else {
+                            $errNums++;
+                        }
+                    }
+                    Db::commit();
+                }catch (\Exception $e) {
+                    Db::rollBack();
+                    return json_fail($e->getMessage());
+                }
+
+            }
+        } else {
+            return json_fail('文件不存在');
+        }
+        $total = count($data);
+        return json_success("全部数据:{$total},成功:{$sucNums},失败:{$errNums}");
+    }
+
+    /**
+     * Notes: 读取excel文件
+     * User: yb
+     * Date: 2024/9/10
+     * Time: 10:41
+     * @param $filePath
+     */
+    public static function readExcel($filePath)
+    {
+        set_time_limit(0);
+        ini_set('memory_limit', '1024M');
+        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
+        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
+            return json_fail('未知的导入文件类型');
+        }
+        if ($ext === 'csv') {
+            $file = fopen($filePath, 'r');
+            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
+            $fp = fopen($filePath, "w");
+            $n = 0;
+            while ($line = fgets($file)) {
+                $line = rtrim($line, "\n\r\0");
+                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
+                if ($encoding != 'utf-8') {
+                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
+                }
+                if ($n == 0 || preg_match('/^".*"$/', $line)) {
+                    fwrite($fp, $line . "\n");
+                } else {
+                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
+                }
+                $n++;
+            }
+            fclose($file) || fclose($fp);
+            $reader = new Csv();
+        } else if ($ext === 'xls') {
+            $reader = new Xls();
+        } else {
+            $reader = new Xlsx();
+        }
+        try {
+            if (!$PHPExcel = $reader->load($filePath)) {
+                return json_fail('未知的导入文件类型');
+            }
+            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
+            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
+            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
+            $maxColumnNumber = 10;
+            $insertData = [];
+            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
+                $values = [];
+                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
+                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
+                    if ($currentColumn == 1) {
+                       $val = date('Y-m-d H:i:s', strtotime($val)); //时间
+                    }
+                    $values[] = is_null($val) ? '' : $val;
+                }
+                $insertData[] = $values;
+            }
+        }catch (\Exception $e) {
+            return json_fail($e->getMessage());
+        }
+        return $insertData;
+    }
 }

+ 2 - 1
composer.json

@@ -45,7 +45,8 @@
     "webman/console": "^1.3",
     "yansongda/pay": "v2.10",
     "webman/event": "^1.0",
-    "endroid/qr-code": "^4.6"
+    "endroid/qr-code": "^4.6",
+    "phpoffice/phpspreadsheet": "^1.12"
   },
   "suggest": {
     "ext-event": "For better performance. "

+ 1 - 0
route/admin.php

@@ -642,6 +642,7 @@ Route::group('/admin', function () {
             Route::get('/statistics_month', [\app\admin\controller\consultant\CustomController::class, 'statisticsByMonth']);
             Route::get('/export', [\app\admin\controller\consultant\CustomController::class, 'exportData']);
             Route::post('/appoint', [\app\admin\controller\consultant\CustomController::class, 'appointConsultant']);
+            Route::post('/import', [\app\admin\controller\consultant\CustomController::class, 'importCustom']);
         });
     });
     Route::group('/customer', function () {