Jelajahi Sumber

匯入工具完成

steve07s 3 tahun lalu
induk
melakukan
ac08d8ff5f

+ 1 - 1
script/php/importTool/form.css

@@ -44,7 +44,7 @@
 /* ===================== BASIC STYLING ===================== */
 * {
     box-sizing: border-box;
-    font-family: 'Lato', sans-serif;
+    
 }
 html, body {
     margin: 0;

+ 12 - 3
script/php/importTool/getConstructionCategory.php

@@ -5,10 +5,19 @@ $conn = sqlsrv_connect($hostname, $connectionInfo);
 if ($conn === false) {
     die(print_r(sqlsrv_errors(), true));
 }
-$ajax = array();
+$data = array();
+$category = array();
+$project = array();
 $sql = "SELECT [category_id],[category_name] FROM [21000X].[dbo].[Construction_Category]";
 $fetchResult = sqlsrv_query($conn, $sql);
 while ($row = sqlsrv_fetch_array($fetchResult,1)) {
-    array_push($ajax,$row);
+    array_push($category,$row);
 }
-echo json_encode($ajax,JSON_UNESCAPED_UNICODE);
+$sql = "SELECT [project_id],[project_name],[category_id] FROM [21000X].[dbo].[Project_Table]";
+$fetchResult = sqlsrv_query($conn, $sql);
+while ($row = sqlsrv_fetch_array($fetchResult,1)) {
+    array_push($project,$row);
+}
+$data["category"] = $category;
+$data["project"] = $project;
+echo json_encode($data,JSON_UNESCAPED_UNICODE);

+ 5 - 20
script/php/importTool/getExcel.php

@@ -14,7 +14,6 @@ if ($conn === false) {
 $fileinfo = array(array("計畫編號", "工程類別", "此計畫是否匯入過"));
 
 $file = '00000.xlsx';
-$Category_List = [];
 if (isset($_GET['file'])) {
     $file = "uploads/{$_GET['file']}";
 }
@@ -64,22 +63,7 @@ for ($s = 0; $s < $sheetCount; $s++) {
     while ($row = sqlsrv_fetch_array($fetchResult)) {
         array_push($isImportArray, $row[0]);
     }
-    $sql = "SELECT [type_id] FROM [File_Category] WHERE [type_name] = '{$Category}';";
-
-    $fetchResult = sqlsrv_query($conn, $sql);
-    $id = 0;
-    while ($row = sqlsrv_fetch_array($fetchResult)) {
-        $id = $row[0];
-    }
-    array_push($Category_List, $id);
 }
-$Category_List_s = implode(",", $Category_List);
-$sql = "IF NOT EXISTS (SELECT [list_id] FROM [Category_List] WHERE [category_list] = '{$Category_List_s}')
-            BEGIN
-                INSERT INTO [Category_List] ([category_list])
-                VALUES ('{$Category_List_s}')
-            END";
-$fetchResult = sqlsrv_query($conn, $sql);
 
 for ($s = 0; $s < $sheetCount; $s++) {
     $normalCheck = "";
@@ -110,14 +94,15 @@ for ($s = 0; $s < $sheetCount; $s++) {
         array_push($data, $row);
     }
     $ajax[$sheetName] = $data;
-    array_push($importinfo, array($sheetName, "<input type='radio' id='normal{$s}' name='type{$s}' value='[File_table]' {$normalCheck}>
+    array_push($importinfo, array($sheetName, "<input type='radio' id='normal{$s}' name='type{$s}' value='[File_Table]' {$normalCheck}>
     <label for='normal{$s}'>一般檔案</label><br>
     <input type='radio' id='blueprint{$s}' name='type{$s}' value='[Blueprint]' {$blueprintCheck}>
     <label for='blueprint{$s}'>設計圖或成果圖</label><br>
-    <input type='radio' id='canel{$s}' name='type{$s}' value='canel' {$cancelCheck}>
-    <label for='canel{$s}'>不進行匯入</label>  ", $isImportArray[$s]));
+    <input type='radio' id='cancel{$s}' name='type{$s}' value='cancel' {$cancelCheck}>
+    <label for='cancel{$s}'>不進行匯入</label>  ", $isImportArray[$s]));
 }
 $data["table"] = $ajax;
 $data["info"] = $importinfo;
 
-echo json_encode($data, JSON_UNESCAPED_UNICODE);
+echo json_encode($data, JSON_UNESCAPED_UNICODE);
+sqlsrv_close($conn);  

+ 10 - 10
script/php/importTool/index.php

@@ -1,17 +1,16 @@
 <?php
+if(!isset($_FILES['excel']['error'])){
+    header("Location: ./upload.html");
+}
 if (0 < $_FILES['excel']['error']) {
     echo 'Error: ' . $_FILES['excel']['error'] . '<br>';
 } else {
     $filepath = 'uploads/' . $_FILES['excel']['name'];
-    move_uploaded_file($_FILES['excel']['tmp_name'], $filepath);
-    //$project_id = pathinfo($_FILES['excel']['name'])['filename'];
+    move_uploaded_file($_FILES['excel']['tmp_name'], $filepath);    
     $project_id = $_POST['projectId'];
+    $project_name = $_POST['projectName'];
     $category_id = $_POST['category'];
     $file = $_FILES['excel']['name'];
-
-
-    //header("Location: ./index.php?excel={$_FILES['excel']['name']}");
-
 } ?>
 
 <!DOCTYPE html>
@@ -107,11 +106,12 @@ if (0 < $_FILES['excel']['error']) {
             var file = '<?= $file ?>';
             var categoryId = '<?= $category_id ?>';
             var projectId = '<?= $project_id ?>';
-            getExcel(file, projectId,categoryId);
+            var projectName = '<?= $project_name ?>';
+            getExcel(file, projectId,projectName,categoryId);
 
         });
 
-        function getExcel(file, projectId,categoryId) {
+        function getExcel(file, projectId,projectName,categoryId) {
 
             $.ajax({
                     url: "./getExcel.php",
@@ -143,8 +143,8 @@ if (0 < $_FILES['excel']['error']) {
                     }
                     $(`#page${0}`).append("<form id='form' method='post' action='./insertExcel.php'></form>");
                     appendTable(info, "#form");
-                    $("#form").append("<div class='center'><input class='submit' type='submit' value='開始匯入'><button type='button' class='submit' onClick=\"location.href='./upload.html'\" >重新選擇檔案</button></div>");
-
+                    $("#form").append(`<div class='center'><input class='submit' type='submit' value='開始匯入'><button type='button' class='submit' onClick=\"location.href='./upload.html'\" >重新選擇檔案</button></div>`);
+                    $("#form").append(`<input id='projectId' name='projectId' type='hidden' value='${projectId}'><input id='projectName' name='projectName' type='hidden' value='${projectName}'><input id='file' name='file' type='hidden' value='${file}'><input id='categoryId' name='categoryId' style='display:none;' value='${categoryId}'>`);
                 })
                 .error(function(error) {
                     console.log(error);

+ 76 - 39
script/php/importTool/insertExcel.php

@@ -4,10 +4,11 @@ include("../sql.php");
 
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
 use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+
 $type = array();
 $i = 0;
-while(isset($_POST["type{$i}"])){
-    $type[$i] = $_POST["type{$i}"];    
+while (isset($_POST["type{$i}"])) {
+    $type[$i] = $_POST["type{$i}"];
     $i++;
 }
 
@@ -20,11 +21,16 @@ if ($conn === false) {
 }
 
 $Category_List = [];
-if (isset($_GET['file'])) {
-    $file = $_GET['file'];
+if (isset($_POST['file'])) {
+    $file = $_POST['file'];
+    $project_id = $_POST['projectId'];
+    $project_name = $_POST['projectName'];
+    $category_id = $_POST['categoryId'];
+} else {
+    header("Location: ./upload.html#error");
 }
+
 $filename = "uploads/{$file}";
-$project_id = pathinfo($filename)['filename'];
 $importinfo = array();
 
 
@@ -36,15 +42,27 @@ $spreadsheet = $reader->load($filename);
 $sheetCount = $spreadsheet->getSheetCount();
 $all = $spreadsheet->getSheetNames();
 
+$sql = "DELETE FROM [Blueprint] WHERE [project_id] = ?";
+$stmt = sqlsrv_query($conn, $sql, array($project_id));
+$sql = "DELETE FROM [File_table] WHERE [project_id] = ?";
+$stmt = sqlsrv_query($conn, $sql, array($project_id));
 
-
+$sql =  "IF NOT EXISTS (SELECT [project_id] FROM [Project_Table] WHERE [project_id] = '{$project_id}')
+            BEGIN
+                INSERT INTO [dbo].[Project_Table] ([project_id],[project_name],[category_id])
+                VALUES
+                (?,?,?)
+            END";
+$stmt = sqlsrv_query($conn, $sql, array($project_id,$project_name,$category_id));
 for ($s = 0; $s < $sheetCount; $s++) {
-    if($type[$s] !='cancel'){
-        
+    if ($type[$s] != 'cancel') {
+
         if (str_contains($all[$s], "_")) {
             $Category = explode("_", $all[$s])[1];
         } else if (str_contains($all[$s], ".")) {
             $Category = explode(".", $all[$s])[1];
+        } else if (str_contains($all[$s], "-")) {
+            $Category = explode("-", $all[$s])[1];
         } else {
             $Category =  $all[$s];
         }
@@ -55,19 +73,60 @@ for ($s = 0; $s < $sheetCount; $s++) {
                     INSERT INTO [File_Category] ([type_name],[filetype_id]) VALUES ('{$Category}',@filetype_id);
                 END";
         $fetchResult = sqlsrv_query($conn, $sql);
-        
+
         $sql = "SELECT [type_id] FROM [File_Category] WHERE [type_name] = '{$Category}';";
-    
+
         $fetchResult = sqlsrv_query($conn, $sql);
-        $id = 0;
+        $type_id = 0;
         while ($row = sqlsrv_fetch_array($fetchResult)) {
-            $id = $row[0];
+            $type_id = $row[0];
         }
-        array_push($Category_List, $id);
-    }
+        array_push($Category_List, $type_id);
+
+        $sheet = $spreadsheet->getSheet($s);
+        $cellCollection = $sheet->getCellCollection();
+        $column = $cellCollection->getHighestRowAndColumn();
+        $data = array();
 
-    
+        for ($i = 2; $i <= $column['row']; $i++) { //行
+            $row = array($project_id, $type_id);
+            for ($j = 'A'; $j <= $column['column']; $j++) { //列
+                $key = $j . $i;
+                $value = $sheet->getCell($key)->getValue();
+                array_push($row, $value);
+            }
+            if ($type[$s] == '[Blueprint]') {
+                $sql = "INSERT INTO [Blueprint]
+                            ([project_id]
+                            ,[type_id]
+                            ,[SN]
+                            ,[blueprint_id]
+                            ,[original_name]
+                            ,[keyword]
+                            ,[notes]
+                            ,[filename])
+                        VALUES
+                            (?,?,?,?,?,?,?,?)";
+            } else if ($type[$s] == '[File_Table]') {
+                $sql = "INSERT INTO [File_Table]
+                            ([project_id]
+                            ,[type_id]
+                            ,[SN]
+                            ,[original_name]
+                            ,[filename]
+                            ,[keyword])
+                        VALUES
+                            (?,?,?,?,?,?)";
+                array_push($row, 'NULL');
+            }
+            $stmt = sqlsrv_query($conn, $sql, $row);
+            echo "<br>";
+        }
+        echo "<br>";
+        echo "<br>";
+    }
 }
+
 $Category_List_s = implode(",", $Category_List);
 $sql = "IF NOT EXISTS (SELECT [list_id] FROM [Category_List] WHERE [category_list] = '{$Category_List_s}')
             BEGIN
@@ -75,27 +134,5 @@ $sql = "IF NOT EXISTS (SELECT [list_id] FROM [Category_List] WHERE [category_lis
                 VALUES ('{$Category_List_s}')
             END";
 $fetchResult = sqlsrv_query($conn, $sql);
-
-
-for ($s = 0; $s < $sheetCount; $s++) {
-    
-    
-    $sheet = $spreadsheet->getSheet($s);
-    $sheetName = $spreadsheet->getSheetNames()[$s];
-    $cellCollection = $sheet->getCellCollection();
-    $column = $cellCollection->getHighestRowAndColumn();
-    $data = array();
-
-    for ($i = 1; $i <= $column['row']; $i++) { //行
-        $row = array();
-        for ($j = 'A'; $j <= $column['column']; $j++) { //列
-            $key = $j . $i;
-            $value = $sheet->getCell($key)->getValue();
-            array_push($row, $value);
-        }
-        array_push($data, $row);
-    }
-    $ajax[$sheetName] = $data;
-    array_push($importinfo, array($sheetName, ""));
-}
-
+sqlsrv_close($conn);
+header("Location: ./upload.html");

+ 39 - 0
script/php/importTool/test.html

@@ -0,0 +1,39 @@
+<!DOCTYPE html>
+<html>
+
+<head>
+    <title>設計群匯入工具</title>
+    <meta charset="utf-8">
+    <link rel="shortcut icon" href="/Database/assets/images/favicon.ico" />
+    <meta name="viewport" content="width=device-width, initial-scale=1">
+    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
+    <script src="/DataBase/assets/vendor/jquery/jquery.js"></script>
+    <script src="/DataBase/script/js/bootstrap.js"></script>
+    <link rel="stylesheet" href="/DataBase/assets/vendor/font-awesome/css/font-awesome.css" />
+    
+</html>
+<body>
+    <form id="form" method="post" action="./test.php">
+        <input type="text" name="id" id="id" />
+        <input type="submit" name="submit" id="submit" />
+    </form>
+<script>/*
+    $.ajax({
+                    url: "./test.php",
+                    data: {id: 1},
+                    async: false,
+                    //contentType: "application/json",
+                    dataType: "json",
+                    type: "POST",
+                })
+                .success(function(response) {
+                    console.log(response);
+                })
+                .error(function(error) {
+                    console.log(error);
+                })
+                .complete(function() {
+                   
+                });*/
+</script>
+</body>

+ 17 - 0
script/php/importTool/test.php

@@ -0,0 +1,17 @@
+<?php
+include("../sql.php");
+$connectionInfo = array("Database" => "$dbname", "UID" => "$username", "PWD" => "$password", "CharacterSet" => "UTF-8");
+$conn = sqlsrv_connect($hostname, $connectionInfo);
+if ($conn === false) {
+    die(print_r(sqlsrv_errors(), true));
+}
+$data = array();
+$id = $_POST["id"];
+$sql = "SELECT [category_name] FROM [Construction_Category] WHERE [category_id] = ?";
+
+
+$fetchResult = sqlsrv_query($conn, $sql, array($id));
+while ($row = sqlsrv_fetch_array($fetchResult)) {
+    array_push($data, $row);
+}
+echo json_encode($data, JSON_UNESCAPED_UNICODE);

+ 41 - 7
script/php/importTool/upload.html

@@ -9,6 +9,7 @@
     <link rel="stylesheet" href="form.css" />
     <link href='https://fonts.googleapis.com/css?family=Lato:100,200,300,400,500,600,700' rel='stylesheet'
         type='text/css'>
+    <link rel="stylesheet" href="/DataBase/assets/vendor/font-awesome/css/font-awesome.css" />
     <script src="/DataBase/assets/vendor/jquery/jquery.js"></script>
 </head>
 <form method="post" enctype="multipart/form-data" action="./index.php">
@@ -19,6 +20,10 @@
         <label for="projectId">計畫編號 </label>
         <input type="text" name="projectId" id="projectId" class="form-controll" required="required" />
     </div>
+    <div class="form-group">
+        <label for="projectName">計畫名稱 </label>
+        <input type="text" name="projectName" id="projectName" class="form-controll" required="required" />
+    </div>
     <div class="form-group">
         <label for="category">工程類別</label>
         <select name="category" id="category" class="form-controll" required="required">
@@ -44,8 +49,31 @@
 <a href="../../../index.php" class="back-to-article" target="_blank">返回至查詢工具</a>
 
 <script type="text/javascript">
+    var projectTable;
+    var projectName;
     $(document).ready(function () {
         getCategory();
+        $("#projectId").change(function () {
+            const find = projectTable.find(element => element[0] == this.value);
+            if (find != null) {
+                projectName = find[1];
+                category = find[2];
+                $("#projectName").val(projectName);
+                $("#projectName").css("cursor", "not-allowed");
+                $('#projectName').attr('readonly', true);
+                $('#category').val(category);
+                $("#category").css("cursor", "not-allowed");
+                $('#category').prop('disabled', true);
+            } else {
+                $("#projectName").val("");
+                $("#projectName").css("cursor", "text");
+                $('#projectName').attr('readonly', false);
+                $('#category').val(1);
+                $("#category").css("cursor", "default");
+                $('#category').prop('disabled', false);
+            }
+
+        });
     });
     var inputElement = document.getElementById("excel");
     inputElement.addEventListener("change", handleFiles, false);
@@ -53,22 +81,28 @@
     function handleFiles() {
         var fileList = this.files;
         $("#filename").text(fileList[0].name);
-        console.log(fileList[0].name);
     }
 
+    jQuery(function ($) {
+        $('form').bind('submit', function () {
+            $(this).find(':input').prop('disabled', false);
+        });
+    });
+
     function getCategory() {
-        
+
         $.ajax({
-                url: "./getConstructionCategory.php",               
+                url: "./getConstructionCategory.php",
                 async: false,
                 contentType: "application/json",
                 dataType: "json",
                 type: "GET",
             })
-            .success(function (response) {     
-                for (i=0;i<response.length;i++) {
-                    console.log(category);     
-                    $('#category').append(`<option value='${response[i][0]}'>${response[i][1]}</option>`);
+            .success(function (response) {
+                projectTable = response["project"];
+                for (i = 0; i < response["category"].length; i++) {
+                    $('#category').append(
+                        `<option value='${response["category"][i][0]}'>${response["category"][i][1]}</option>`);
                 }
             })
             .error(function (error) {