Sfoglia il codice sorgente

【Add】批量操作客户积分

liuxiangxin 6 mesi fa
parent
commit
de28a7050b

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

@@ -4,6 +4,7 @@ use App\Http\Requests\Admin\CustomScore as Request;
 use App\Models\Custom;
 use App\Models\CustomScore as Model;
 use Illuminate\Support\Facades\DB;
+use App\Models\FilesManager;
 
 /**
  * 客户管理
@@ -100,5 +101,42 @@ class CustomScore extends Auth{
 		return									$this->fetch(); 
 	}
 
+	/**
+	 * 表格导入
+	 * 
+	 * */
+	public function import_execl( Request $request,Model $Model,Custom $Custom,FilesManager $FilesManager){
+		// 验证参数
+		$request->scene('import_execl')->validate();
+		// 获取表格信息
+		$file								= request()->file('score_file');
+		// 返回结果
+		$sheetList							= $FilesManager->excelToScore($file);
+		// 如果不存在结果
+		if( isset($sheetList['error']) )	return json_send(['code'=>'error','msg'=>$sheetList['error']]);
+		// 组合数据,写入订单表,子表
+		DB::beginTransaction();
+		// 循环表格数据
+		foreach ($sheetList as $value) 		{
+			// 客户ID
+			$customUid						= $Custom->codeToId($value['custom_uid']);
+			// 如果客户ID有误
+			if( !$customUid )				return json_send(['code'=>'error','msg'=>$value['custom_uid'].'编码有误']);
+			// 写入数据表
+			$payId							= $Model->trade($customUid,0,$value['score'],4,($value['score']>0?1:2),$value['description']);
+			// 如果操作失败
+			if( isset($payId['error']) ) 	{
+				// 回滚
+				DB::rollBack();
+				// 结果提示
+				return 						json_send(['code'=>'error','msg'=>$value['custom_uid'].'=>'.$payId['error']]);
+			}
+		}
+		// 提交事务
+		DB::commit();
+		// 提示成功
+		return								json_send(['code'=>'success','msg'=>'批量导入成功','path'=>'']);
+	}
+
 
 }

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

@@ -32,6 +32,8 @@ class VerifyCsrfToken extends Middleware
         // 导入表格
         'admin/orders/import_execl',
         // 导入表格
-        'admin/custom/import_execl'
+        'admin/custom/import_execl',
+        // 导入表格
+        'admin/custom_score/import_execl'
     ];
 }

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

@@ -39,7 +39,7 @@ class Custom extends BaseRequest
 		'add'  		            => ['username','phone'],
         'edit'  		        => ['uid','username','phone'],
         'set_status'  		    => ['uid'],
-        'import_execl'          => ['order_file'],
+        'import_execl'          => ['custom_file'],
 	];
 
     /**

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

@@ -22,6 +22,7 @@ class CustomScore extends BaseRequest
 	        'incr_score' 		=> 'required|integer|gt:0',
             'decr_score'		=> 'required|integer|gt:0',
 	        'custom_uid'        => 'required|integer|gt:0',
+            'score_file'       => 'required|file'
         ];
     }
 
@@ -30,6 +31,7 @@ class CustomScore extends BaseRequest
     protected   $scenes         = [
 		'incr'  		        => ['custom_uid','incr_score'],
         'decr'  		        => ['custom_uid','decr_score'],
+        'import_execl'          => ['custom_file'],
 	];
 
     /**
@@ -49,6 +51,8 @@ class CustomScore extends BaseRequest
             'decr_score.required'   => '请填写扣减积分',
             'decr_score.integer'   	=> '积分格式错误',
             'decr_score.gt'   		=> '积分格式错误',
+            'import_execl.required' => '请上传Excel',
+            'import_execl.file'     => '请上传Excel文件',
         ];
     }
     

+ 64 - 0
app/Models/FilesManager.php

@@ -325,4 +325,68 @@ class FilesManager extends Model
         // 返回字段值
         return                          $field;
     }
+
+
+    /**
+     * 从Excel获取积分操作
+     * 
+     * @param     \Illuminate\Http\UploadedFile   $file     传入的文件
+     * 
+     */
+    public function excelToScore($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->scoreToField($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['custom_uid']) )  return ['error' => ($row + 1).' 没有识别到客户ID'];
+            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 scoreToField($column)
+    {
+        // 字段值
+        $field                              = [];
+        // 循环列标题
+        foreach ($column as $key => $value) {
+            if( $value == '客户ID')         $field[$key] = 'custom_uid';
+            if( $value == '积分数量')        $field[$key] = 'score';
+            if( $value == '备注' )          $field[$key] = 'description';
+        }
+        // 返回字段值
+        return                          $field;
+    }
+
 }

BIN
public/uploads/score_tpl.xlsx


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

@@ -5,8 +5,14 @@ style="margin: 0 auto;width: 96%;padding: 30px 0px;"
 @section('content')
 @if( check_auth('admin/orders/import_execl') )
 <div class="page-header">
+	@if( check_auth('admin/custom/import_execl') )
 	<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>
+	<a href="/uploads/custom_tpl.xlsx" class="btn btn-primary" download="客户导入模版"> <span class="fa fa-download"></span> 客户模版</a>
+	@endif
+	@if( check_auth('admin/custom_score/import_execl') )
+	<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
 </div>
 @endif
 <form action="" method="get" class="form-horizontal form-line">
@@ -147,4 +153,53 @@ style="margin: 0 auto;width: 96%;padding: 30px 0px;"
 	});
  })
 </script>
+<script type="text/javascript">
+ $(function(){
+	$('.upload_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_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

+ 2 - 0
routes/web.php

@@ -138,6 +138,8 @@ Route::middleware('admin')->prefix('admin')->group(function(){
     Route::any('custom_score/incr',[App\Http\Controllers\Admin\CustomScore::class,'incr']);
     // 添加
     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']);
 
     /* 客户资质审核 */
     // 列表