Kaynağa Gözat

【Add】微伴用户积分导入

liuxiangxin 5 ay önce
ebeveyn
işleme
134df02a6a

+ 1 - 1
app/Http/Controllers/Admin/Custom.php

@@ -302,7 +302,7 @@ class Custom extends Auth{
 		$writer 				= IOFactory::createWriter($spreadsheet, 'Xlsx');
 		header('Pragma: public');
 		header('Content-type:application/vnd.ms-excel');
-		header('Content-Disposition: inline;filename=下载订单.xlsx');
+		header('Content-Disposition: inline;filename=客户列表.xlsx');
 		// 输出数据流
 		return $writer->save('php://output');
 	}

+ 44 - 0
app/Http/Controllers/Admin/CustomScore.php

@@ -5,6 +5,7 @@ use App\Models\Custom;
 use App\Models\CustomScore as Model;
 use Illuminate\Support\Facades\DB;
 use App\Models\FilesManager;
+use App\Models\WeiBan\External as WeiBanExternal;
 
 /**
  * 客户管理
@@ -138,5 +139,48 @@ class CustomScore extends Auth{
 		return								json_send(['code'=>'success','msg'=>'批量导入成功','path'=>'']);
 	}
 
+	/**
+	 * 表格导入
+	 * 
+	 * */
+	public function import_weiban( Request $request,Model $Model,Custom $Custom,FilesManager $FilesManager,WeiBanExternal $WeiBanExternal){
+		// 验证参数
+		$request->scene('import_execl')->validate();
+		// 获取表格信息
+		$file								= request()->file('score_file');
+		// 返回结果
+		$sheetList							= $FilesManager->weibanToScore($file);
+		// 如果不存在结果
+		if( isset($sheetList['error']) )	return json_send(['code'=>'error','msg'=>$sheetList['error']]);
+		// 通过微伴ID查询用户ID
+		$uidList							= $WeiBanExternal->query()->whereIn('id',array_column($sheetList,'weiban_extid'))->pluck('custom_uid','id')->toArray();
+		// 循环列表
+		foreach ($sheetList as $key=>$value) 		{
+			// 如果查询不到数据
+			if( empty($uidList[$value['weiban_extid']]) )   return json_send(['code'=>'error','msg'=>$value['weiban_extid'].'不在系统内']);
+			// 获取客户ID
+			$value['custom_uid']			= $uidList[$value['weiban_extid']];
+			// 重组
+			$sheetList[$key]				= $value;
+		}
+		// 组合数据,写入订单表,子表
+		DB::beginTransaction();
+		// 循环表格数据
+		foreach ($sheetList as $value) 		{
+			// 写入数据表
+			$payId							= $Model->trade($value['custom_uid'],0,$value['score'],4,($value['score']>0?1:2),$value['description']);
+			// 如果操作失败
+			if( isset($payId['error']) ) 	{
+				// 回滚
+				DB::rollBack();
+				// 结果提示
+				return 						json_send(['code'=>'error','msg'=>$value['weiban_extid'].'=>'.$payId['error']]);
+			}
+		}
+		// 提交事务
+		DB::commit();
+		// 提示成功
+		return								json_send(['code'=>'success','msg'=>'批量导入成功','path'=>'']);
+	}
 
 }

+ 2 - 0
app/Http/Middleware/VerifyCsrfToken.php

@@ -37,5 +37,7 @@ class VerifyCsrfToken extends Middleware
         'admin/custom/import_execl',
         // 导入表格
         'admin/custom_score/import_execl',
+        // 微伴积分导入
+        'admin/custom_score/import_weiban',
     ];
 }

+ 63 - 0
app/Models/FilesManager.php

@@ -459,4 +459,67 @@ class FilesManager extends Model
         return                          $field;
     }
 
+    /**
+     * 从Excel获取积分操作
+     * 
+     * @param     \Illuminate\Http\UploadedFile   $file     传入的文件
+     * 
+     */
+    public function weibanToScore($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->weibanToField($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['phone']) )           return ['error' => ($row + 1).' 没有识别到联系方式'];
+            if( empty($custom['score']) )           return ['error' => ($row + 1).' 没有识别到积分数量'];
+            if( empty($custom['description']) )     $custom['description'] = '';
+            // 积分转整数
+            $custom['score']                    = intval($custom['score']);
+            // 追加到订单列表
+            $sheetList[$row]                    = $custom;
+        }
+        // 返回结果
+        return                                  $sheetList;
+    }
+
+    /**
+     * 获取列对应的数据库字段名
+     * 
+     */
+    private function weibanToField($column){
+        // 字段值
+        $field                              = [];
+        // 循环列标题
+        foreach ($column as $key => $value) {
+            if( $value == '微伴ID')         $field[$key]  = 'weiban_extid';
+            if( $value == '联系方式')        $field[$key]  = 'phone';
+            if( $value == '积分数量')        $field[$key] = 'score';
+            if( $value == '备注' )          $field[$key] = 'description';
+        }
+        // 返回字段值
+        return                          $field;
+    }
+
 }

+ 53 - 0
resources/views/admin/custom/index.blade.php

@@ -13,6 +13,10 @@ style="margin: 0 auto;width: 96%;padding: 30px 0px;"
 	<a href="javascript:;" class="btn btn-primary upload_score"> <span class="fa fa-upload"></span> 积分批量导入</a>
 	<a href="/uploads/score_tpl.xlsx" class="btn btn-primary" download="积分批量导入模版"> <span class="fa fa-download"></span> 积分模版</a>
 	@endif
+	@if( check_auth('admin/custom_score/import_weiban') )
+	<a href="javascript:;" class="btn btn-primary upload_weiban_score"> <span class="fa fa-upload"></span> 微伴积分导入</a>
+	<a href="/uploads/weiban_score_tpl.xlsx" class="btn btn-primary" download="积分批量导入模版"> <span class="fa fa-download"></span> 微伴模版</a>
+	@endif
 </div>
 @endif
 <form action="" method="get" name="thisform" class="form-horizontal form-line">
@@ -220,4 +224,53 @@ style="margin: 0 auto;width: 96%;padding: 30px 0px;"
 	});
  })
 </script>
+<script type="text/javascript">
+ $(function(){
+	$('.upload_weiban_score').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="score_file" multiple="multiple" /></form>');
+		$('#form-upload input[name=\'score_file\']').trigger('click');
+		$('[osctype="btn_upload_file"]').fileupload({
+			dataType: 'json',
+			url: "{{url('admin/custom_score/import_weiban')}}",
+			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

+ 2 - 0
routes/web.php

@@ -142,6 +142,8 @@ Route::middleware('admin')->prefix('admin')->group(function(){
     Route::any('custom_score/decr',[App\Http\Controllers\Admin\CustomScore::class,'decr']);
     // 批量
     Route::any('custom_score/import_execl',[App\Http\Controllers\Admin\CustomScore::class,'import_execl']);
+    // 批量
+    Route::any('custom_score/import_weiban',[App\Http\Controllers\Admin\CustomScore::class,'import_weiban']);
 
     /* 客户资质审核 */
     // 列表