Kaynağa Gözat

项目导入

ChenWuJie 4 yıl önce
ebeveyn
işleme
cdbe6893a7

+ 22 - 0
app/Http/Controllers/Admin/ProjectController.php

xqd xqd xqd
@@ -2,6 +2,7 @@
 
 namespace App\Http\Controllers\Admin;
 
+use App\Imports\ProjectImport;
 use App\Models\AdminRoleModel;
 use App\Models\Department;
 use App\Models\Notification;
@@ -13,6 +14,8 @@ use App\Models\Role;
 use App\User;
 use Carbon\Carbon;
 use Illuminate\Http\Request;
+use Maatwebsite\Excel\Facades\Excel;
+
 
 class ProjectController extends BaseController
 {
@@ -198,4 +201,23 @@ class ProjectController extends BaseController
         }
         return compact('start_at', 'end_at');
     }
+    public function exportTemplate(Request $request)
+    {
+        return response()->download(public_path() . '/项目导入模板.xlsx', '项目导入模板.xlsx', [
+            'Content-Type: application/vnd.ms-excel'
+        ]);
+    }
+    public function import(Request $request)
+    {
+        if(!$request->hasFile('file')) {
+            return response()->json(['status' => 'error', 'info' => '参数错误']);
+        }
+        $file = $request->file('file');
+        try {
+            Excel::import(new ProjectImport(), $file);
+        } catch (ImportError $e) {
+            return response()->json(['status' => 'error', 'info' => $e->getMessage()]);
+        }
+        return response()->json(['status' => 'success', 'info' => '上传成功']);
+    }
 }

+ 110 - 0
app/Imports/ProjectImport.php

xqd
@@ -0,0 +1,110 @@
+<?php
+
+namespace App\Imports;
+
+use App\Exceptions\ImportError;
+use App\Models\Device;
+use App\Models\DeviceName;
+use App\Models\InnerDevice;
+use App\Models\InnerDeviceNamesModel;
+use App\Models\Option;
+use App\Models\Project;
+use App\Models\ProjectUser;
+use App\Models\ProjectZone;
+use App\Models\Road;
+use App\Models\Spec;
+use App\Models\User;
+use App\Models\WorkPoint;
+use App\Models\Zone;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Facades\Log;
+use Maatwebsite\Excel\Concerns\ToCollection;
+use PhpOffice\PhpSpreadsheet\Shared\Date;
+
+class ProjectImport implements ToCollection
+{
+    protected $model;
+
+    protected $zone;
+
+    protected $road;
+
+    protected $project_zone;
+
+    public function __construct()
+    {
+        $this->model = new Project();
+    }
+
+    public function collection(Collection $rows)
+    {
+        if(count($rows) <= 1) {
+            /** @noinspection PhpUnhandledExceptionInspection */
+            return false;
+        };
+        foreach ($rows as $key => $row) {
+            if($key == 0) continue;
+            if(empty($row[0])&&empty($row[1])&&empty($row[2]))
+            {
+                break;
+            }
+            //项目id
+            $project_id = null;
+            //用户id
+            $user_id = null;
+            $password = '123456';
+            $password = bcrypt($password);
+            /*
+             * 项目名称
+             * 逻辑
+             *      1.如果不存在该项目,那么就创建一个项目,并且active为激活状态
+             *      2.如果存在该项目,返回项目id
+             * */
+            if ($row[0])
+            {
+                $project_id = Project::firstOrCreate([
+                    'name' => $row[0],
+                ],[
+                    'name' => $row[0],
+                    'active' => 1
+                ]);
+            }
+
+            //手机号
+            if ($row[1]&&$row[2])
+            {
+                $user_id = User::firstOrCreate([
+                    'phone' => $row[2]
+                ],[
+                    'name' => $row[1],
+                    'phone'=> $row[2],
+                    'password' => $password
+                ]);
+            }
+            //如果相同电话号码,不同名字的话就替换原来的名字
+            if ($user_id->name != $row[1])
+            {
+                User::where('id',$user_id->id)->update(['name'=>$row[1]]);
+            }
+            /*
+             * 导入到项目成员表里
+             *      如果原本这个项目存在项目经理,那就把这个项目经理替换成项目副经理
+             *          然后再插入新的数据
+             * */
+            $manager_num = ProjectUser::where('project_id',$project_id['id'])->where('project_role_id',4)->count();
+            if ($manager_num != 0)
+            {
+                $manager_user = ProjectUser::where('project_id',$project_id['id'])->where('project_role_id',4)->first();
+                ProjectUser::where('id',$manager_user['id'])->update(['project_role_id'=>3]);
+            }
+            $data =[
+                'project_id' => $project_id['id'],
+                'user_id' => $user_id['id'],
+                'project_role_id' => 4
+            ];
+            ProjectUser::create($data);
+        }
+        return true;
+    }
+}

BIN
public/项目导入模板.xlsx


+ 121 - 2
resources/views/admin/projects/index.blade.php

xqd xqd xqd xqd
@@ -2,7 +2,44 @@
 
 @section('header')
     <style>
-
+        .sg-search-box {
+            display: flex;
+            align-items: center;
+            justify-content: space-between;
+        }
+        .sg-import-box {
+            display: none;
+        }
+        .sg-import-box.sg-show {
+            display: block;
+        }
+        .sg-import-box .layui-col-sm8 {
+            float: none;
+        }
+        .layui-card .layui-form-item .layui-inline {
+            margin-bottom: 0;
+        }
+        .sg-export-list {
+            margin: 50px 0;
+        }
+        .sg-export-list .sg-item {
+            margin: 20px 0;
+        }
+        .sg-export-list .sg-item .sg-title {
+            margin: 20px 0;
+        }
+        .sg-export-list .sg-item .sg-desc,
+        .sg-export-list .sg-item ul {
+            color: rgb(140, 140, 140);
+            margin-left: 30px;
+        }
+        .sg-down-link {
+            color: blue;
+            text-decoration: underline;
+        }
+        .sg-down-link:hover {
+            color: blue;
+        }
     </style>
 @endsection
 
@@ -11,6 +48,9 @@
         <div class="layui-card-header sg-card-header">
             {{ $model_name }}管理
             <div class="sg-card-create">
+                <button id="sg-import-all" class="layui-btn layui-btn-sm layui-btn-normal">批量导入</button>
+            </div>
+            <div class="sg-card-create" style="margin-right: 10px">
                 <button id="sg-create-btn" class="layui-btn layui-btn-sm">创建</button>
             </div>
         </div>
@@ -54,6 +94,27 @@
             </script>
         </div>
     </div>
+    <div id="sg-import-box" class="sg-import-box">
+        <div class="layui-row">
+            {{--<input type="file" id="sg-upload-file">--}}
+            <div class="layui-col-sm8 layui-col-sm-offset2">
+                <div class="sg-export-list">
+                    <div class="sg-item">
+                        <h3 class="sg-title">一、请按照数据模板的格式准备要导入的数据。<a href="{{ $pre_uri . 'exportTemplate?t=' . time() }}" class="sg-down-link">点击下载</a>《项目导入模板》</h3>
+                        <ul>
+                            <li>注意事项</li>
+                            <li>1、模板中的表头名称不能更改,表头行不能删除</li>
+                            <li>2、导入文件请勿超过 20 MB</li>
+                        </ul>
+                    </div>
+                    <div class="sg-item">
+                        <h3 class="sg-title">二、请选择需要导入的文件</h3>
+                        <div class="sg-desc"><input type="file" id="sg-upload-file"></div>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
 @endsection
 
 @section('footer')
@@ -65,7 +126,65 @@
                     form = layui.form,
                     laydate = layui.laydate,
                     top_window = window;
-
+                $('#sg-import-all').click(function() {
+                    layer.open({
+                        title: '导入设备',
+                        type: 1,
+                        area: ['90%', '90%'],
+                        content: $('#sg-import-box'),
+                        btn: ['导入', '取消'],
+                        yes: function () {
+                            importFile();
+                        }
+                    });
+                    // $('#sg-upload-file').click();
+                });
+                function importFile() {
+                    var file = $('#sg-upload-file')[0].files[0];
+                    if(file) {
+                        var name = file['name'];
+                        var ext = name.split('.').pop();
+                        if(['xls', 'xlsx'].indexOf(ext) !== -1) {
+                            var formData = new FormData();
+                            formData.append('file', file);
+                            $.ajax({
+                                method: 'POST',
+                                url: '{{ $pre_uri }}' + 'import',
+                                headers: {
+                                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
+                                },
+                                data: formData,
+                                contentType: false,
+                                cache: false,
+                                processData: false,
+                                success: function (data) {
+                                    if(data.status === 'success') {
+                                        layer.msg('上传成功', {
+                                            icon: 1
+                                        });
+                                        setTimeout(function() {
+                                            top_window.location.reload();
+                                        }, 1000)
+                                    } else {
+                                        layer.alert(data.info, {
+                                            icon: 2
+                                        });
+                                    }
+                                },
+                                error: function () {
+                                    layer.msg('导入失败', {
+                                        icon: 2
+                                    });
+                                }
+                            });
+                        }
+                    } else {
+                        layer.msg('只支持xls,xlsx格式的文件', {
+                            icon: 2
+                        });
+                    }
+                    this.value = '';
+                }
                 table.render({
                     elem: '#sg-main-table',
                     url: '{{ $pre_uri }}' + 'get',