ソースを参照

【Add】客户导入功能

liuxiangxin 6 ヶ月 前
コミット
f75c08f988

+ 50 - 0
app/Http/Controllers/Admin/Custom.php

@@ -3,9 +3,12 @@
 use App\Http\Requests\Admin\Custom as Request;
 use App\Models\City;
 use App\Models\Custom as Model;
+use App\Models\CustomAddr;
 use App\Models\CustomScore;
 use Illuminate\Support\Carbon;
 use App\Models\WeiBan\Follow as WeiBanFollow;
+use App\Models\FilesManager;
+use App\Models\WeiBan\External as WeiBanExternal;
 
 /**
  * 客户管理
@@ -164,5 +167,52 @@ class Custom extends Auth{
 		return 				json_send(['code'=>'success','msg'=>'设置成功','path'=>'']);
 	}
 
+	/**
+	 * 表格导入
+	 * 
+	 * */
+	public function import_execl( Request $request,Model $Model,FilesManager $FilesManager,City $City,CustomAddr $CustomAddr,WeiBanExternal $WeiBanExternal){
+		// 验证参数
+		$request->scene('import_execl')->validate();
+		// 获取表格信息
+		$file								= request()->file('custom_file');
+		// 返回结果
+		$sheetList							= $FilesManager->excelToCustom($file);
+		// 如果不存在结果
+		if( isset($sheetList['error']) )	return json_send(['code'=>'error','msg'=>$sheetList['error']]);
+		// 循环表格数据
+		foreach ($sheetList as $value) 		{
+			// 获取城市ID
+			$value['city_id']				= 0;
+			// 存在城市名称,查询城市ID
+			if( $value['contact_city'] )	{
+				// 获取城市ID
+				$value['city_id']			= (int) $City->getIdByName($value['contact_city']);
+				// 如果城市不存在的话
+				if ( !$value['city_id'] )	return json_send(['code'=>'error','msg'=>$value['contact_city'].' => 未找到匹配的城市,请核对城市全称']);
+			}
+			// 获取手机号,查询是否用客户
+			$custom							= $Model->getOneByPhone($value['phone']);
+			// 组装数据
+			$data							= ['weiban_extid'=>$value['weiban_extid'],'username'=>$value['username']];
+			// 如果客户不存在
+			if( !$custom )					$data['phone'] = $value['phone'];
+			// 如果存在城市ID,才修改城市
+			if( $value['city_id'] )			$data['city_id'] = $value['city_id'];
+			// 如果存在手机号
+			$uid							= $custom ? $Model->edit($custom['uid'],$data) : $Model->add($data);
+			// 如果客户存在
+			if( !$uid )						return json_send(['code'=>'error','msg'=>$value['username'].'【'.$value['phone'].'】'.'用户创建或者更新失败']);
+			// 存在详细地址,才创建地址库
+			if( $value['contact_name'] && $value['contact_phone'] && $value['contact_province'] && $value['contact_city'] && $value['contact_area'] && $value['contact_addr'] )	{
+				// 收件地址是否存在
+				$oldAddr					= $CustomAddr->query()->where([['custom_uid','=',$uid]])->first();
+				// 如果不存在地址
+				if( !$oldAddr )				$CustomAddr->add(['custom_uid'=>$uid,'contact_name'=>$value['contact_name'],'contact_shop'=>$value['contact_shop'],'contact_phone'=>$value['contact_phone'],'contact_province'=>$value['contact_province'],'contact_city'=>$value['contact_city'],'contact_area'=>$value['contact_area'],'contact_addr'=>$value['contact_addr']]);
+			}
+		}
+		// 提示成功
+		return								json_send(['code'=>'success','msg'=>'批量导入成功','path'=>'']);
+	}
 
 }

+ 3 - 1
app/Http/Middleware/VerifyCsrfToken.php

@@ -30,6 +30,8 @@ class VerifyCsrfToken extends Middleware
         // 编辑器
         'admin/ueditor/upload',
         // 导入表格
-        'admin/orders/import_execl'
+        'admin/orders/import_execl',
+        // 导入表格
+        'admin/custom/import_execl'
     ];
 }

+ 4 - 0
app/Http/Requests/Admin/Custom.php

@@ -34,6 +34,7 @@ class Custom extends BaseRequest
 	        'username' 			=> ['required',$unique],
             'phone'		        => ['required','regex:/^1[3456789][0-9]{9}$/',$uniphone],
 	        'uid'               => 'required|integer|gt:0',
+            'custom_file'       => 'required|file'
         ];
     }
 
@@ -43,6 +44,7 @@ class Custom extends BaseRequest
 		'add'  		            => ['username','phone'],
         'edit'  		        => ['uid','username','phone'],
         'set_status'  		    => ['uid'],
+        'import_execl'          => ['order_file'],
 	];
 
     /**
@@ -61,6 +63,8 @@ class Custom extends BaseRequest
             'uid.required'      => 'ID未知',
             'uid.integer'   	=> 'ID格式错误',
             'uid.gt'   		    => 'ID格式错误',
+            'import_execl.required'=> '请上传Excel',
+            'import_execl.file' => '请上传Excel文件',
         ];
     }
     

+ 76 - 0
app/Models/FilesManager.php

@@ -249,4 +249,80 @@ class FilesManager extends Model
         // 返回字段值
         return                          $field;
     }
+
+    /**
+     * 从Excel获取客户信息
+     * 
+     * @param     \Illuminate\Http\UploadedFile   $file     传入的文件
+     * 
+     */
+    public function excelToCustom($file)
+    {
+        // 获取文件后缀名
+        $ext                        = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
+        // 验证文件格式
+        if (!in_array($ext, ['csv', 'xlsx', 'xls']))    return ['error' => '请上传Excel'];
+        // 读取文件
+        $reader                     = IOFactory::createReader(ucwords($ext))->load($file->getPathname());
+        // 提取数据
+        $sheetList                  = $reader->getActiveSheet()->toArray('');
+        // 表格列标题
+        $column                     = array_shift($sheetList);
+        // 列标题换字段
+        $column                     = $this->customToField($column);
+        // 字段值
+        if( !$column )              return ['error' => '请检查内容表头格式'];
+        // 循环表格数据
+        foreach ($sheetList as $row=>$value)    {
+            // 获取对应的数据
+            $custom                             = [];
+            // 循环每个字段,获取值
+            foreach ($value as $kk => $vv)      {
+                // 根据字段索引获取对应的值,转存到客户信息
+                if( isset($column[$kk]) )       $custom[$column[$kk]] = $vv;
+            }
+            // 验证必须数据
+            if( empty($custom['weiban_extid']) )      return ['error' => ($row + 1).' 没有识别到微伴ID'];
+            if( empty($custom['username']) )          return ['error' => ($row + 1).' 没有识别到用户昵称'];
+            if( empty($custom['phone']) )             return ['error' => ($row + 1).' 没有识别到用户手机号'];
+            // 没有详细地址,则默认为空
+            if( empty($custom['contact_name']) )      $custom['contact_name'] = '';
+            if( empty($custom['contact_phone']) )     $custom['contact_phone'] = '';
+            if( empty($custom['contact_shop']) )      $custom['contact_shop'] = '';
+            if( empty($custom['contact_province']) )  $custom['contact_province'] = '';
+            if( empty($custom['contact_city']) )      $custom['contact_city'] = '';
+            if( empty($custom['contact_area']) )      $custom['contact_area'] = '';
+            if( empty($custom['contact_addr']) )      $custom['contact_addr'] = '';
+            // 追加到订单列表
+            $sheetList[$row]                    = $custom;
+        }
+        // 返回结果
+        return                                  $sheetList;
+    }
+
+
+    /**
+     * 获取列对应的数据库字段名
+     * 
+     */
+    private function customToField($column)
+    {
+        // 字段值
+        $field                              = [];
+        // 循环列标题
+        foreach ($column as $key => $value) {
+            if( $value == '微伴ID')         $field[$key] = 'weiban_extid';
+            if( $value == '用户昵称')        $field[$key] = 'username';
+            if( $value == '用户手机号' )     $field[$key] = 'phone';
+            if( $value == '收货人')          $field[$key] = 'contact_name';
+            if( $value == '店铺信息')        $field[$key] = 'contact_shop';
+            if( $value == '收货人手机号' )   $field[$key] = 'contact_phone';
+            if( $value == '省')             $field[$key] = 'contact_province';
+            if( $value == '市')             $field[$key] = 'contact_city';
+            if( $value == '区')             $field[$key] = 'contact_area';
+            if( $value == '收货地址')        $field[$key] = 'contact_addr';
+        }
+        // 返回字段值
+        return                          $field;
+    }
 }

+ 19 - 0
app/Models/WeiBan/External.php

@@ -24,6 +24,25 @@ class External extends Model
     // const CREATED_AT = 'insert_time';
     // const UPDATED_AT = 'update_time';
 
+
+    /**
+     * 添加数据
+     * 
+     */
+    public function add($data)
+    {
+        if( empty($data['id']) )            return '';
+        // 更新时间
+        $data['insert_time']                = time();
+        $data['update_time']                = time();
+        // 写入数据表
+        $result						        = $this->query()->insert($data);
+        // 失败返回0
+        if( !$result )                      return '';
+        // 返回结果
+        return                              $data['id'];
+    }
+
     /**
      * 添加数据
      * 

BIN
public/uploads/custom_tpl.xlsx


+ 1 - 3
resources/views/admin/coupon/index.blade.php

@@ -19,10 +19,9 @@ style="margin: 0 auto;width: 96%;padding: 30px 0px;"
 		<select name="status" class="form-control">
 			<option value="" >优惠券状态</option>
 			<option value="0" @if (request('status') === '0' ) selected="selected" @endif >正常</option>
-			<option value="1" @if (request('status') === '1' ) selected="selected" @endif >已用</option>
 			<option value="2" @if (request('status') === '2' ) selected="selected" @endif >暂停</option>
 			<option value="2" @if (request('status') === '3' ) selected="selected" @endif >过期</option>
-			<option value="2" @if (request('status') === '3' ) selected="selected" @endif >作废</option>
+			<option value="2" @if (request('status') === '4' ) selected="selected" @endif >作废</option>
 		</select>
 	</div>
 	<div class="form-group col col-md-1" style="margin-right: 2px;">
@@ -74,7 +73,6 @@ style="margin: 0 auto;width: 96%;padding: 30px 0px;"
 						</td>
 						<td> 
 							@if ($a['status'] == 0) 正常 @endif
-							@if ($a['status'] == 1) 已用 @endif
 							@if ($a['status'] == 2) 暂停 @endif
 							@if ($a['status'] == 3) 过期 @endif
 							@if ($a['status'] == 4) 作废 @endif

+ 59 - 1
resources/views/admin/custom/index.blade.php

@@ -3,7 +3,12 @@
 style="margin: 0 auto;width: 96%;padding: 30px 0px;"
 @endsection
 @section('content')
-
+@if( check_auth('admin/orders/import_execl') )
+<div class="page-header">
+	<a href="javascript:;" class="btn btn-primary upload"> <span class="fa fa-upload"></span> 导入客户信息</a>
+	<a href="/uploads/custom_tpl.xlsx" class="btn btn-primary" download="客户导入模版"> <span class="fa fa-download"></span> 模版</a>
+</div>
+@endif
 <form action="" method="get" class="form-horizontal form-line">
 	<div class="form-group col col-lg-2 col-md-2 col-sm-2 col-xs-2" style="margin-right: 2px;">
 		<input type="text" class="form-control" name="custom_code" value="{{request('custom_code','')}}" placeholder="请输入客户编码查询" />
@@ -90,3 +95,56 @@ style="margin: 0 auto;width: 96%;padding: 30px 0px;"
 	</div>
 </div>
 @endsection
+@section('javascript')
+<script src="/static/fileupload/jquery.ui.widget.js"></script>
+<script src="/static/fileupload/jquery.fileupload.js"></script>
+<script type="text/javascript">
+ $(function(){
+	$('.upload').on('click', function() {
+		$('#form-upload').remove();
+		$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input osctype="btn_upload_file" type="file" name="custom_file" multiple="multiple" /></form>');
+		$('#form-upload input[name=\'custom_file\']').trigger('click');
+		$('[osctype="btn_upload_file"]').fileupload({
+			dataType: 'json',
+			url: "{{url('admin/custom/import_execl')}}",
+			singleFileUploads: false,
+			beforeSend: function() {
+				art.dialog({
+					id: 'loading',
+					lock: true,
+					title: '文件上传中'
+				});
+			},
+			done: function(e, data) {
+				art.dialog.list['loading'].close();
+				var result = data.result;
+				if (result.code == 'error') {
+					art.dialog({
+						content: result.msg,
+						lock: true,
+						ok: function() {}
+					});
+				}
+				if (result.code == 'success') {
+					art.dialog({
+						content: result.msg,
+						lock: true,
+						ok: function() {
+							location.reload();
+						}
+					});
+				}
+			},
+			fail: function(e,c) {
+				art.dialog.list['loading'].close();
+				art.dialog({
+					content: '<p>'+c.jqXHR.status+'=>'+c.jqXHR.statusText+'</p>',
+					lock: true,
+					ok: function() {}
+				});
+			}
+		});
+	});
+ })
+</script>
+@endsection

+ 1 - 1
resources/views/admin/custom_coupon/index.blade.php

@@ -22,7 +22,7 @@ style="margin: 0 auto;width: 96%;padding: 30px 0px;"
 			<option value="1" @if (request('status') === '1' ) selected="selected" @endif >已用</option>
 			<option value="2" @if (request('status') === '2' ) selected="selected" @endif >暂停</option>
 			<option value="2" @if (request('status') === '3' ) selected="selected" @endif >过期</option>
-			<option value="2" @if (request('status') === '3' ) selected="selected" @endif >作废</option>
+			<option value="2" @if (request('status') === '4' ) selected="selected" @endif >作废</option>
 		</select>
 	</div>
 	<div class="form-group col col-md-1" style="margin-right: 2px;">

+ 2 - 0
routes/web.php

@@ -130,6 +130,8 @@ Route::middleware('admin')->prefix('admin')->group(function(){
     Route::any('custom/edit',[App\Http\Controllers\Admin\Custom::class,'edit']);
     // 状态
     Route::any('custom/set_status',[App\Http\Controllers\Admin\Custom::class,'set_status']);
+    // 订单导入
+    Route::any('custom/import_execl',[App\Http\Controllers\Admin\Custom::class,'import_execl']);
 
     /* 积分管理 */
     // 列表