diff --git a/Backend/Controllers/DeviceImportController.cs b/Backend/Controllers/DeviceImportController.cs index 39cab47..5e534a4 100644 --- a/Backend/Controllers/DeviceImportController.cs +++ b/Backend/Controllers/DeviceImportController.cs @@ -15,181 +15,181 @@ using System.Threading.Tasks; namespace Backend.Controllers { - public class DeviceImportController : MybaseController - { - private readonly IBackendRepository backendRepository; - private readonly IDeviceImportRepository deviceImportRepository; - - public DeviceImportController(IBackendRepository backendRepository, IDeviceImportRepository deviceImportRepository) + public class DeviceImportController : MybaseController { - this.backendRepository = backendRepository; - this.deviceImportRepository = deviceImportRepository; - } + private readonly IBackendRepository backendRepository; + private readonly IDeviceImportRepository deviceImportRepository; - - public IActionResult Index() - { - return View(); - } - - /// - /// 設備匯入列表 - /// - /// - [HttpPost] - public async Task>> RawDataList() - { - ApiResult> apiResult = new ApiResult>(); - List deviceImports = new List(); - - try - { - deviceImports = await backendRepository.GetAllAsync("device_import_temp", null, null, "device_result DESC,created_at DESC"); - - apiResult.Code = "0000"; - apiResult.Data = deviceImports; - } - catch (Exception exception) - { - apiResult.Code = "9999"; - Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); - } - - return apiResult; - } - - - [HttpPost] - public async Task> ImportRawDataFile(IFormFile[] import_files) - { - ApiResult apiResult = new ApiResult(); - - try - { - Dictionary workbooks = new Dictionary(); - - //List workbooks = new List(); - - #region 檢驗各檔案是否正確 - foreach (var import_file in import_files) + public DeviceImportController(IBackendRepository backendRepository, IDeviceImportRepository deviceImportRepository) { - IWorkbook workbook; - - var filename_ext = Path.GetExtension(import_file.FileName).ToLower(); - - if (filename_ext == ".xls") - { - workbook = new HSSFWorkbook(import_file.OpenReadStream()); - workbooks.Add($"{import_file.FileName}", workbook); - } - else if (filename_ext == ".xlsx") - { - workbook = new XSSFWorkbook(import_file.OpenReadStream()); - workbooks.Add($"{import_file.FileName}", workbook); - } - else - { - workbook = null; - } - - if (workbook == null) - { - apiResult.Code = "9998"; - apiResult.Msg = $"{import_file.FileName}該檔案失效,請重新操作。"; - - return apiResult; - } + this.backendRepository = backendRepository; + this.deviceImportRepository = deviceImportRepository; } - #endregion - List> deviceImports = new List>(); - //抓取系統類別(以供驗證判斷) - var sWhere = @$"deleted = 0 AND system_type = @system_type"; - var system_category_param = new { system_type = "device_system_category_layer3" }; - var system_categories_layer3 = await backendRepository.GetAllAsync("variable", sWhere, system_category_param); - - var disaster_param = new { system_type = "disaster" }; - var disasters = await backendRepository.GetAllAsync("variable", sWhere, disaster_param); - var temp_building = ""; //預設的棟別(檢查用,整份excel需相同),目前只針對單一檔案情況,如後續有需再改成多檔情況。 - - #region 抓取每個檔案的資料 - foreach (var keyValuePair in workbooks) + public IActionResult Index() { - IWorkbook workbook = keyValuePair.Value; + return View(); + } - var total_sheet = workbook.NumberOfSheets; - for (var sheet_num = 2; sheet_num < total_sheet - 1; sheet_num++) - { - var tags_name_index = -1; - var system_category_index = -1; //系統類別 - var disaster_index = -1; //緊急應變程序(等同災害類別) - var sheet = workbook.GetSheetAt(sheet_num); + /// + /// 設備匯入列表 + /// + /// + [HttpPost] + public async Task>> RawDataList() + { + ApiResult> apiResult = new ApiResult>(); + List deviceImports = new List(); - //表頭 - IRow header = sheet.GetRow(sheet.FirstRowNum); - List columns = new List(); - if (header != null) + try { - for (int i = 0; i < header.LastCellNum; i++) - { - ICell cell = header.GetCell(i); - if (cell != null) - { - var header_str = cell.ToString().ToLower(); - if (!string.IsNullOrEmpty(header_str) && header_str == "tags name") - { - tags_name_index = i; - } - if (!string.IsNullOrEmpty(header_str) && header_str == "系統類別") - { - system_category_index = i; - } - if (!string.IsNullOrEmpty(header_str) && header_str == "系統程式軟體") - { - IRow sub_header = sheet.GetRow(1); + deviceImports = await backendRepository.GetAllAsync("device_import_temp", null, null, "device_result DESC,created_at DESC"); - for (int j = 0; j < sub_header.LastCellNum; j++) - { - ICell sub_cell = sub_header.GetCell(j); - var sub_header_str = sub_cell.ToString().ToLower(); - if (!string.IsNullOrEmpty(sub_header_str) && sub_header_str == "緊急應變程序") - { - disaster_index = j; - } - } - } - - if (tags_name_index > 0 && system_category_index > 0 && disaster_index > 0) - { - break; - } - } - } + apiResult.Code = "0000"; + apiResult.Data = deviceImports; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } - //資料 - if (tags_name_index < 0 || system_category_index < 0 || disaster_index < 0) + return apiResult; + } + + + [HttpPost] + public async Task> ImportRawDataFile(IFormFile[] import_files) + { + ApiResult apiResult = new ApiResult(); + + try { - List errMsg = new List(); - var result = $@"查無[{keyValuePair.Key}]在[{workbook.GetSheetName(sheet_num)}]分頁的"; + Dictionary workbooks = new Dictionary(); - if (tags_name_index < 0) - { - errMsg.Add($@"[tags name]"); - } + //List workbooks = new List(); - if (system_category_index < 0) - { - errMsg.Add($@"[系統類別]"); - } + #region 檢驗各檔案是否正確 + foreach (var import_file in import_files) + { + IWorkbook workbook; - if (disaster_index < 0) - { - errMsg.Add($@"[緊急應變程序]"); - } + var filename_ext = Path.GetExtension(import_file.FileName).ToLower(); - Dictionary deviceImport = new Dictionary() + if (filename_ext == ".xls") + { + workbook = new HSSFWorkbook(import_file.OpenReadStream()); + workbooks.Add($"{import_file.FileName}", workbook); + } + else if (filename_ext == ".xlsx") + { + workbook = new XSSFWorkbook(import_file.OpenReadStream()); + workbooks.Add($"{import_file.FileName}", workbook); + } + else + { + workbook = null; + } + + if (workbook == null) + { + apiResult.Code = "9998"; + apiResult.Msg = $"{import_file.FileName}該檔案失效,請重新操作。"; + + return apiResult; + } + } + #endregion + + List> deviceImports = new List>(); + + //抓取系統類別(以供驗證判斷) + var sWhere = @$"deleted = 0 AND system_type = @system_type"; + var system_category_param = new { system_type = "device_system_category_layer3" }; + var system_categories_layer3 = await backendRepository.GetAllAsync("variable", sWhere, system_category_param); + + var disaster_param = new { system_type = "disaster" }; + var disasters = await backendRepository.GetAllAsync("variable", sWhere, disaster_param); + var temp_building = ""; //預設的棟別(檢查用,整份excel需相同),目前只針對單一檔案情況,如後續有需再改成多檔情況。 + + #region 抓取每個檔案的資料 + foreach (var keyValuePair in workbooks) + { + IWorkbook workbook = keyValuePair.Value; + + var total_sheet = workbook.NumberOfSheets; + for (var sheet_num = 2; sheet_num < total_sheet - 1; sheet_num++) + { + var tags_name_index = -1; + var system_category_index = -1; //系統類別 + var disaster_index = -1; //緊急應變程序(等同災害類別) + var sheet = workbook.GetSheetAt(sheet_num); + + //表頭 + IRow header = sheet.GetRow(sheet.FirstRowNum); + List columns = new List(); + if (header != null) + { + for (int i = 0; i < header.LastCellNum; i++) + { + ICell cell = header.GetCell(i); + if (cell != null) + { + var header_str = cell.ToString().ToLower(); + if (!string.IsNullOrEmpty(header_str) && header_str == "tags name") + { + tags_name_index = i; + } + if (!string.IsNullOrEmpty(header_str) && header_str == "系統類別") + { + system_category_index = i; + } + if (!string.IsNullOrEmpty(header_str) && header_str == "系統程式軟體") + { + IRow sub_header = sheet.GetRow(1); + + for (int j = 0; j < sub_header.LastCellNum; j++) + { + ICell sub_cell = sub_header.GetCell(j); + var sub_header_str = sub_cell.ToString().ToLower(); + if (!string.IsNullOrEmpty(sub_header_str) && sub_header_str == "緊急應變程序") + { + disaster_index = j; + } + } + } + + if (tags_name_index > 0 && system_category_index > 0 && disaster_index > 0) + { + break; + } + } + } + } + + //資料 + if (tags_name_index < 0 || system_category_index < 0 || disaster_index < 0) + { + List errMsg = new List(); + var result = $@"查無[{keyValuePair.Key}]在[{workbook.GetSheetName(sheet_num)}]分頁的"; + + if (tags_name_index < 0) + { + errMsg.Add($@"[tags name]"); + } + + if (system_category_index < 0) + { + errMsg.Add($@"[系統類別]"); + } + + if (disaster_index < 0) + { + errMsg.Add($@"[緊急應變程序]"); + } + + Dictionary deviceImport = new Dictionary() { { "@device_number", null}, { "@device_system_category_layer3", null}, @@ -197,138 +197,138 @@ namespace Backend.Controllers { "@device_result", result + String.Join("、", errMsg)} }; - deviceImports.Add(deviceImport); - } - else - { - for (var i = sheet.FirstRowNum + 2; i < sheet.LastRowNum; i++) - { - - IRow row = sheet.GetRow(i); - if (row != null) - { - List errMsg = new List(); - Dictionary deviceImport = new Dictionary(); - - ICell tags_name_cell = row.GetCell(tags_name_index); - if (tags_name_cell != null) - { - var tempData = tags_name_cell.ToString().Trim(); - var system_category = string.Empty; - var disaster = string.Empty; - if (!string.IsNullOrEmpty(tempData)) - { - var arr_tempData = tempData.Split('_'); - - #region tags name驗證條件 - if (string.IsNullOrEmpty(temp_building)) //抓第一筆當作該excel 比對棟別的依據 - { - temp_building = arr_tempData[0]; - } - else - { - if (temp_building != arr_tempData[0]) - { - errMsg.Add("資料棟別錯誤"); - } - } - - if (arr_tempData.Length != 5) - { - errMsg.Add("資料格式錯誤"); - } - - if (arr_tempData[arr_tempData.Length - 1].Contains('~')) - { - errMsg.Add("設備流水號格式錯誤"); - } - - if (arr_tempData[arr_tempData.Length - 1].Split('~').Length > 2) - { - errMsg.Add("設備流水號格式錯誤"); - } - #endregion - - #region 系統類別驗證條件 - ICell system_category_cell = row.GetCell(system_category_index); - if (system_category_cell == null) - { - errMsg.Add(@"該設備的[系統類別]未填值"); - } - else - { - system_category = system_category_cell.ToString().Trim(); - if (!string.IsNullOrEmpty(system_category)) - { - var exist = system_categories_layer3.Exists(x => x.system_value == system_category); - if (!exist) - { - errMsg.Add(@"該設備的[系統類別]不存在"); - } + deviceImports.Add(deviceImport); } else { - errMsg.Add(@"該設備的[系統類別]未填值"); - } - } - #endregion - - #region 緊急應變程序驗證條件 - ICell disaster_cell = row.GetCell(disaster_index); - if (disaster_cell == null) - { - errMsg.Add(@"該設備的[緊急應變程序]未填值"); - } - else - { - disaster = disaster_cell.ToString().Trim(); - if (!string.IsNullOrEmpty(disaster)) - { - if (disaster != "0") - { - var exist = disasters.Exists(x => x.system_value == disaster); - if (!exist) + for (var i = sheet.FirstRowNum + 2; i < sheet.LastRowNum; i++) { - errMsg.Add(@"該設備的[緊急應變程序]不存在"); + + IRow row = sheet.GetRow(i); + if (row != null) + { + List errMsg = new List(); + Dictionary deviceImport = new Dictionary(); + + ICell tags_name_cell = row.GetCell(tags_name_index); + if (tags_name_cell != null) + { + var tempData = tags_name_cell.ToString().Trim(); + var system_category = string.Empty; + var disaster = string.Empty; + if (!string.IsNullOrEmpty(tempData)) + { + var arr_tempData = tempData.Split('_'); + + #region tags name驗證條件 + if (string.IsNullOrEmpty(temp_building)) //抓第一筆當作該excel 比對棟別的依據 + { + temp_building = arr_tempData[0]; + } + else + { + if (temp_building != arr_tempData[0]) + { + errMsg.Add("資料棟別錯誤"); + } + } + + if (arr_tempData.Length != 5) + { + errMsg.Add("資料格式錯誤"); + } + + if (arr_tempData[arr_tempData.Length - 1].Contains('~')) + { + errMsg.Add("設備流水號格式錯誤"); + } + + if (arr_tempData[arr_tempData.Length - 1].Split('~').Length > 2) + { + errMsg.Add("設備流水號格式錯誤"); + } + #endregion + + #region 系統類別驗證條件 + ICell system_category_cell = row.GetCell(system_category_index); + if (system_category_cell == null) + { + errMsg.Add(@"該設備的[系統類別]未填值"); + } + else + { + system_category = system_category_cell.ToString().Trim(); + if (!string.IsNullOrEmpty(system_category)) + { + var exist = system_categories_layer3.Exists(x => x.system_value == system_category); + if (!exist) + { + errMsg.Add(@"該設備的[系統類別]不存在"); + } + } + else + { + errMsg.Add(@"該設備的[系統類別]未填值"); + } + } + #endregion + + #region 緊急應變程序驗證條件 + ICell disaster_cell = row.GetCell(disaster_index); + if (disaster_cell == null) + { + errMsg.Add(@"該設備的[緊急應變程序]未填值"); + } + else + { + disaster = disaster_cell.ToString().Trim(); + if (!string.IsNullOrEmpty(disaster)) + { + if (disaster != "0") + { + var exist = disasters.Exists(x => x.system_value == disaster); + if (!exist) + { + errMsg.Add(@"該設備的[緊急應變程序]不存在"); + } + } + } + else + { + errMsg.Add(@"該設備的[緊急應變程序]未填值"); + } + } + #endregion + + if (errMsg.Count > 0) + { + deviceImport.Add("@device_number", tempData); + deviceImport.Add("@device_system_category_layer3", system_category); + deviceImport.Add("@device_disaster", disaster); + deviceImport.Add("@device_result", String.Join(", ", errMsg)); + } + else + { + deviceImport.Add("@device_number", tempData); + deviceImport.Add("@device_system_category_layer3", system_category); + deviceImport.Add("@device_disaster", disaster); + deviceImport.Add("@device_result", null); + } + + deviceImports.Add(deviceImport); + } + } + } } - } } - else - { - errMsg.Add(@"該設備的[緊急應變程序]未填值"); - } - } - #endregion - if (errMsg.Count > 0) - { - deviceImport.Add("@device_number", tempData); - deviceImport.Add("@device_system_category_layer3", system_category); - deviceImport.Add("@device_disaster", disaster); - deviceImport.Add("@device_result", String.Join(", ", errMsg)); - } - else - { - deviceImport.Add("@device_number", tempData); - deviceImport.Add("@device_system_category_layer3", system_category); - deviceImport.Add("@device_disaster", disaster); - deviceImport.Add("@device_result", null); - } - - deviceImports.Add(deviceImport); } - } } - } - } - } - } + deviceImports = deviceImports.Distinct().ToList(); - deviceImports = deviceImports.Distinct().ToList(); - - //先刪除整份資料表 - var sql = @"IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[device_import_temp]') AND type in (N'U')) + //先刪除整份資料表 + var sql = @"IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[device_import_temp]') AND type in (N'U')) BEGIN DROP TABLE [dbo].[device_import_temp]; END @@ -346,151 +346,151 @@ namespace Backend.Controllers ALTER TABLE [dbo].[device_import_temp] ADD CONSTRAINT [DF_device_import_temp_device_disaster] DEFAULT ((0)) FOR [device_disaster] ALTER TABLE [dbo].[device_import_temp] ADD CONSTRAINT [DF_device_import_temp_created_at] DEFAULT (getdate()) FOR [created_at] "; - await backendRepository.ExecuteSql(sql); + await backendRepository.ExecuteSql(sql); - //如有發現錯誤,直接insert 至 device_import_temp,不做後續處理 - await backendRepository.AddMutiByCustomTable(deviceImports, "device_import_temp"); + //如有發現錯誤,直接insert 至 device_import_temp,不做後續處理 + await backendRepository.AddMutiByCustomTable(deviceImports, "device_import_temp"); - //var err = deviceImports.Where(x => x.ContainsKey("@device_result")).Select(x => x.Values).ToList(); - var err = deviceImports.SelectMany(x => x).Where(x => x.Key == "@device_result" && x.Value != null).ToList(); - if (err.Count > 0) - { - apiResult.Code = "9997"; - apiResult.Msg = "資料內容有誤,請重新匯入。"; - - return apiResult; - } - else - { - //拆分每一份資料 - List> deviceImportChecks = new List>(); //檢查OK的列表 - - - foreach (var deviceImport in deviceImports) - { - - object device_number = null; - object device_system_category_layer3 = null; - object device_disaster = null; - deviceImport.TryGetValue("@device_number", out device_number); - deviceImport.TryGetValue("@device_system_category_layer3", out device_system_category_layer3); - deviceImport.TryGetValue("@device_disaster", out device_disaster); - - var arr_device_number = device_number.ToString().Split('_'); - - //抓出是否為組數的設備 - var arr_device_number_final_col = arr_device_number[arr_device_number.Length - 1].Contains('~') ? arr_device_number[arr_device_number.Length - 1].Split('~') : null; - if (arr_device_number_final_col != null && arr_device_number_final_col.Length > 0) - { - var start_num = Convert.ToInt32(arr_device_number_final_col[0].Trim()); - var end_num = Convert.ToInt32(arr_device_number_final_col[1].Trim()); - for (var i = start_num; i <= end_num; i++) - { - Dictionary deviceImportCheck = new Dictionary(); - var pre_device_number = String.Join('_', arr_device_number, 0, 4); - deviceImportCheck.Add("@device_building_tag", arr_device_number[0]); //設備區域 - deviceImportCheck.Add("@device_system_tag", arr_device_number[1]); //設備系統別 - deviceImportCheck.Add("@device_floor_tag", arr_device_number[2]); //設備樓層 - deviceImportCheck.Add("@device_name_tag", arr_device_number[3]); //設備名稱 - - var pad = string.Empty; - if (i < 10) + //var err = deviceImports.Where(x => x.ContainsKey("@device_result")).Select(x => x.Values).ToList(); + var err = deviceImports.SelectMany(x => x).Where(x => x.Key == "@device_result" && x.Value != null).ToList(); + if (err.Count > 0) { - pad = i.ToString().PadLeft(2, '0'); + apiResult.Code = "9997"; + apiResult.Msg = "資料內容有誤,請重新匯入。"; + + return apiResult; } else { - pad = i.ToString(); + //拆分每一份資料 + List> deviceImportChecks = new List>(); //檢查OK的列表 + + + foreach (var deviceImport in deviceImports) + { + + object device_number = null; + object device_system_category_layer3 = null; + object device_disaster = null; + deviceImport.TryGetValue("@device_number", out device_number); + deviceImport.TryGetValue("@device_system_category_layer3", out device_system_category_layer3); + deviceImport.TryGetValue("@device_disaster", out device_disaster); + + var arr_device_number = device_number.ToString().Split('_'); + + //抓出是否為組數的設備 + var arr_device_number_final_col = arr_device_number[arr_device_number.Length - 1].Contains('~') ? arr_device_number[arr_device_number.Length - 1].Split('~') : null; + if (arr_device_number_final_col != null && arr_device_number_final_col.Length > 0) + { + var start_num = Convert.ToInt32(arr_device_number_final_col[0].Trim()); + var end_num = Convert.ToInt32(arr_device_number_final_col[1].Trim()); + for (var i = start_num; i <= end_num; i++) + { + Dictionary deviceImportCheck = new Dictionary(); + var pre_device_number = String.Join('_', arr_device_number, 0, 4); + deviceImportCheck.Add("@device_building_tag", arr_device_number[0]); //設備區域 + deviceImportCheck.Add("@device_system_tag", arr_device_number[1]); //設備系統別 + deviceImportCheck.Add("@device_floor_tag", arr_device_number[2]); //設備樓層 + deviceImportCheck.Add("@device_name_tag", arr_device_number[3]); //設備名稱 + + var pad = string.Empty; + if (i < 10) + { + pad = i.ToString().PadLeft(2, '0'); + } + else + { + pad = i.ToString(); + } + deviceImportCheck.Add("@device_serial_tag", pad); //設備流水號 + + deviceImportCheck.Add("@device_number", pre_device_number + "_" + pad); //設備完整編號 + deviceImportCheck.Add("@device_system_category_layer3", device_system_category_layer3.ToString()); //系統類別(第3層) + deviceImportCheck.Add("@device_disaster", device_disaster.ToString()); //緊急應變程序 + deviceImportCheck.Add("@is_correct", 0); //驗證是否正確 + + deviceImportChecks.Add(deviceImportCheck); + } + } + else + { + Dictionary deviceImportCheck = new Dictionary(); + var pre_device_number = String.Join('_', arr_device_number, 0, 3); + deviceImportCheck.Add("@device_building_tag", arr_device_number[0]); //設備區域 + deviceImportCheck.Add("@device_system_tag", arr_device_number[1]); //設備系統別 + deviceImportCheck.Add("@device_floor_tag", arr_device_number[2]); //設備樓層 + deviceImportCheck.Add("@device_name_tag", arr_device_number[3]); //設備名稱 + deviceImportCheck.Add("@device_serial_tag", arr_device_number[4]); //設備流水號 + deviceImportCheck.Add("@device_number", device_number); //設備完整編號 + deviceImportCheck.Add("@device_system_category_layer3", device_system_category_layer3.ToString()); //系統類別(第3層) + deviceImportCheck.Add("@device_disaster", device_disaster.ToString()); //緊急應變程序 + deviceImportCheck.Add("@is_correct", 0); //驗證是否正確 + + deviceImportChecks.Add(deviceImportCheck); + } + + } + + //針對棟別刪除檢查OK的設備查詢表 + var sDeleteWhere = $@"device_building_tag = '{temp_building}'"; + await backendRepository.PurgeOneByGuidWithCustomDBNameAndTable("device_import_ckeck_temp", sDeleteWhere); + + //var sql_check = @"IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[device_import_ckeck_temp]') AND type in (N'U')) + // BEGIN + // DROP TABLE [dbo].[device_import_ckeck_temp] + // END + // CREATE TABLE [dbo].[device_import_ckeck_temp]( + // [id] [int] IDENTITY(1,1) NOT NULL, + // [device_building_tag] [nvarchar](50) NULL, + // [device_system_tag] [nvarchar](50) NULL, + // [device_floor_tag] [nvarchar](50) NULL, + // [device_kind] [nvarchar](50) NULL, + // [device_name_tag] [nvarchar](50) NULL, + // [device_serial_tag] [nvarchar](50) NULL, + // [device_number] [nvarchar](255) NULL, + // [device_system_category_layer3] [varchar](50) NULL, + // [device_disaster] [varchar](50) NULL, + // [created_at] [datetime] NULL, + // CONSTRAINT [PK_device_import_ckeck_temp] PRIMARY KEY CLUSTERED + // ( + // [id] ASC + // )) + + // ALTER TABLE [dbo].[device_import_ckeck_temp] ADD CONSTRAINT [DF_device_import_ckeck_temp_device_disaster] DEFAULT ((0)) FOR [device_disaster] + // ALTER TABLE [dbo].[device_import_ckeck_temp] ADD CONSTRAINT [DF_device_import_ckeck_temp_created_at] DEFAULT (getdate()) FOR [created_at] + // "; + //await backendRepository.ExecuteSql(sql_check); + + //檢查正確才寫入至check_temp資料表 + await backendRepository.AddMutiByCustomTable(deviceImportChecks, "device_import_ckeck_temp"); } - deviceImportCheck.Add("@device_serial_tag", pad); //設備流水號 - deviceImportCheck.Add("@device_number", pre_device_number + "_" + pad); //設備完整編號 - deviceImportCheck.Add("@device_system_category_layer3", device_system_category_layer3.ToString()); //系統類別(第3層) - deviceImportCheck.Add("@device_disaster", device_disaster.ToString()); //緊急應變程序 - deviceImportCheck.Add("@is_correct", 0); //驗證是否正確 - - deviceImportChecks.Add(deviceImportCheck); - } + apiResult.Code = "0000"; + apiResult.Msg = "匯入成功"; + #endregion } - else + catch (Exception exception) { - Dictionary deviceImportCheck = new Dictionary(); - var pre_device_number = String.Join('_', arr_device_number, 0, 3); - deviceImportCheck.Add("@device_building_tag", arr_device_number[0]); //設備區域 - deviceImportCheck.Add("@device_system_tag", arr_device_number[1]); //設備系統別 - deviceImportCheck.Add("@device_floor_tag", arr_device_number[2]); //設備樓層 - deviceImportCheck.Add("@device_name_tag", arr_device_number[3]); //設備名稱 - deviceImportCheck.Add("@device_serial_tag", arr_device_number[4]); //設備流水號 - deviceImportCheck.Add("@device_number", device_number); //設備完整編號 - deviceImportCheck.Add("@device_system_category_layer3", device_system_category_layer3.ToString()); //系統類別(第3層) - deviceImportCheck.Add("@device_disaster", device_disaster.ToString()); //緊急應變程序 - deviceImportCheck.Add("@is_correct", 0); //驗證是否正確 - - deviceImportChecks.Add(deviceImportCheck); + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } - } - - //針對棟別刪除檢查OK的設備查詢表 - var sDeleteWhere = $@"device_building_tag = '{temp_building}'"; - await backendRepository.PurgeOneByGuidWithCustomDBNameAndTable("device_import_ckeck_temp", sDeleteWhere); - - //var sql_check = @"IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[device_import_ckeck_temp]') AND type in (N'U')) - // BEGIN - // DROP TABLE [dbo].[device_import_ckeck_temp] - // END - // CREATE TABLE [dbo].[device_import_ckeck_temp]( - // [id] [int] IDENTITY(1,1) NOT NULL, - // [device_building_tag] [nvarchar](50) NULL, - // [device_system_tag] [nvarchar](50) NULL, - // [device_floor_tag] [nvarchar](50) NULL, - // [device_kind] [nvarchar](50) NULL, - // [device_name_tag] [nvarchar](50) NULL, - // [device_serial_tag] [nvarchar](50) NULL, - // [device_number] [nvarchar](255) NULL, - // [device_system_category_layer3] [varchar](50) NULL, - // [device_disaster] [varchar](50) NULL, - // [created_at] [datetime] NULL, - // CONSTRAINT [PK_device_import_ckeck_temp] PRIMARY KEY CLUSTERED - // ( - // [id] ASC - // )) - - // ALTER TABLE [dbo].[device_import_ckeck_temp] ADD CONSTRAINT [DF_device_import_ckeck_temp_device_disaster] DEFAULT ((0)) FOR [device_disaster] - // ALTER TABLE [dbo].[device_import_ckeck_temp] ADD CONSTRAINT [DF_device_import_ckeck_temp_created_at] DEFAULT (getdate()) FOR [created_at] - // "; - //await backendRepository.ExecuteSql(sql_check); - - //檢查正確才寫入至check_temp資料表 - await backendRepository.AddMutiByCustomTable(deviceImportChecks, "device_import_ckeck_temp"); + return apiResult; } - apiResult.Code = "0000"; - apiResult.Msg = "匯入成功"; - #endregion - } - catch (Exception exception) - { - apiResult.Code = "9999"; - apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; - Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); - } + /// + /// 取得設備檢核上方過濾選單 + /// + /// + [HttpPost] + public async Task>> GetRawDataCheckFilter() + { + ApiResult> apiResult = new ApiResult>(); - return apiResult; - } - - /// - /// 取得設備檢核上方過濾選單 - /// - /// - [HttpPost] - public async Task>> GetRawDataCheckFilter() - { - ApiResult> apiResult = new ApiResult>(); - - try - { - string sql = $@" + try + { + string sql = $@" SELECT ct.device_building_tag, ct.device_system_tag, @@ -499,86 +499,86 @@ namespace Backend.Controllers GROUP BY ct.device_building_tag, ct.device_system_tag, ct.device_system_category_layer3 "; - var deviceCheckFilterRawDatas = await backendRepository.GetAllAsync(sql); + var deviceCheckFilterRawDatas = await backendRepository.GetAllAsync(sql); - List deviceCheckFilters = new List(); + List deviceCheckFilters = new List(); - var deviceCheckFilterRawData_Group_Building_tag = deviceCheckFilterRawDatas.GroupBy(x => x.Device_building_tag).ToList(); - foreach (var deviceCheckFilterRawData_Building_tag in deviceCheckFilterRawData_Group_Building_tag) - { - DeviceCheckFilter deviceCheckFilter = new DeviceCheckFilter(); - deviceCheckFilter.Building_tag = deviceCheckFilterRawData_Building_tag.Key; + var deviceCheckFilterRawData_Group_Building_tag = deviceCheckFilterRawDatas.GroupBy(x => x.Device_building_tag).ToList(); + foreach (var deviceCheckFilterRawData_Building_tag in deviceCheckFilterRawData_Group_Building_tag) + { + DeviceCheckFilter deviceCheckFilter = new DeviceCheckFilter(); + deviceCheckFilter.Building_tag = deviceCheckFilterRawData_Building_tag.Key; - var sql_amount = @"SELECT COUNT(*) FROM device_import_ckeck_temp WHERE device_building_tag = @Device_building_tag"; - deviceCheckFilter.Building_amount = await backendRepository.GetOneAsync(sql_amount, new { Device_building_tag = deviceCheckFilterRawData_Building_tag.Key }); + var sql_amount = @"SELECT COUNT(*) FROM device_import_ckeck_temp WHERE device_building_tag = @Device_building_tag"; + deviceCheckFilter.Building_amount = await backendRepository.GetOneAsync(sql_amount, new { Device_building_tag = deviceCheckFilterRawData_Building_tag.Key }); - deviceCheckFilter.System_tags = new List(); + deviceCheckFilter.System_tags = new List(); - var deviceCheckFilterRawData_Group_System_tag = deviceCheckFilterRawData_Building_tag.GroupBy(x => x.Device_system_tag).ToList(); - foreach (var deviceCheckFilterRawData_System_tag in deviceCheckFilterRawData_Group_System_tag) - { - DeviceCheckSystemTag deviceCheckSystemTag = new DeviceCheckSystemTag(); - deviceCheckSystemTag.System_tag = deviceCheckFilterRawData_System_tag.Key; - deviceCheckSystemTag.System_categories = new List(); + var deviceCheckFilterRawData_Group_System_tag = deviceCheckFilterRawData_Building_tag.GroupBy(x => x.Device_system_tag).ToList(); + foreach (var deviceCheckFilterRawData_System_tag in deviceCheckFilterRawData_Group_System_tag) + { + DeviceCheckSystemTag deviceCheckSystemTag = new DeviceCheckSystemTag(); + deviceCheckSystemTag.System_tag = deviceCheckFilterRawData_System_tag.Key; + deviceCheckSystemTag.System_categories = new List(); - var deviceCheckFilterRawData_Group_System_category = deviceCheckFilterRawData_System_tag.GroupBy(x => x.Device_system_category_layer3).ToList(); - foreach (var deviceCheckFilterRawData_System_category in deviceCheckFilterRawData_Group_System_category) + var deviceCheckFilterRawData_Group_System_category = deviceCheckFilterRawData_System_tag.GroupBy(x => x.Device_system_category_layer3).ToList(); + foreach (var deviceCheckFilterRawData_System_category in deviceCheckFilterRawData_Group_System_category) + { + deviceCheckSystemTag.System_categories.Add(deviceCheckFilterRawData_System_category.Key); + } + + deviceCheckFilter.System_tags.Add(deviceCheckSystemTag); + } + + deviceCheckFilters.Add(deviceCheckFilter); + } + + + apiResult.Code = "0000"; + apiResult.Data = deviceCheckFilters; + } + catch (Exception exception) { - deviceCheckSystemTag.System_categories.Add(deviceCheckFilterRawData_System_category.Key); + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } - deviceCheckFilter.System_tags.Add(deviceCheckSystemTag); - } - - deviceCheckFilters.Add(deviceCheckFilter); + return apiResult; } - - apiResult.Code = "0000"; - apiResult.Data = deviceCheckFilters; - } - catch (Exception exception) - { - apiResult.Code = "9999"; - apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; - Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); - } - - return apiResult; - } - - /// - /// 資料檢核表格 - /// - /// - [HttpPost] - public async Task> DeviceCheckTableList(PostDeviceCheckFilter post) - { - ApiResult apiResult = new ApiResult(); - - try - { - string sWhere = ""; - string sSubTableWhere = " WHERE {0}.device_building_tag = @Device_building_tag"; - if (post.Abnormal == "all") - { //異常分類 為全選的時候,才可以指定選擇系統別、設備分類 - if (post.System_tag != "all") - { - sSubTableWhere += " AND {0}.device_system_tag = @Device_system_tag"; - } - if (post.System_category != "all") - { - sSubTableWhere += " AND {0}.device_system_category_layer3 = @Device_system_category_layer3"; - } - } - else + /// + /// 資料檢核表格 + /// + /// + [HttpPost] + public async Task> DeviceCheckTableList(PostDeviceCheckFilter post) { - sWhere += @"WHERE ct.device_number IS NULL AND d.device_number IS NOT NULL + ApiResult apiResult = new ApiResult(); + + try + { + string sWhere = ""; + string sSubTableWhere = " WHERE {0}.device_building_tag = @Device_building_tag"; + if (post.Abnormal == "all") + { //異常分類 為全選的時候,才可以指定選擇系統別、設備分類 + if (post.System_tag != "all") + { + sSubTableWhere += " AND {0}.device_system_tag = @Device_system_tag"; + } + if (post.System_category != "all") + { + sSubTableWhere += " AND {0}.device_system_category_layer3 = @Device_system_category_layer3"; + } + } + else + { + sWhere += @"WHERE ct.device_number IS NULL AND d.device_number IS NOT NULL -- OR ct.device_system_category_layer3 != d.device_system_category_layer3 -- OR ct.disaster_system_value != d.device_disaster"; - } + } - string sql_temp = $@" + string sql_temp = $@" SELECT ct.device_number AS check_temp_device_number, ct.device_system_category_layer3 AS check_temp_device_system_category_layer3, @@ -648,59 +648,59 @@ namespace Backend.Controllers ORDER BY d.device_number DESC "; - var sql = string.Format(sql_temp, string.Format(sSubTableWhere, "ct"), string.Format(sSubTableWhere, "d"), sWhere); + var sql = string.Format(sql_temp, string.Format(sSubTableWhere, "ct"), string.Format(sSubTableWhere, "d"), sWhere); - var param = new { Device_building_tag = post.Building_tag, Device_system_tag = post.System_tag, Device_system_category_layer3 = post.System_category }; + var param = new { Device_building_tag = post.Building_tag, Device_system_tag = post.System_tag, Device_system_category_layer3 = post.System_category }; - var deviceCheckTableList = await backendRepository.GetAllAsync(sql, param); + var deviceCheckTableList = await backendRepository.GetAllAsync(sql, param); - sSubTableWhere = " WHERE {0}.device_building_tag = @Device_building_tag"; + sSubTableWhere = " WHERE {0}.device_building_tag = @Device_building_tag"; - sWhere = @"WHERE ct.device_number IS NULL AND d.device_number IS NOT NULL + sWhere = @"WHERE ct.device_number IS NULL AND d.device_number IS NOT NULL -- OR ct.device_system_category_layer3 != d.device_system_category_layer3 -- OR ct.disaster_system_value != d.device_disaster"; - var sql_abnormal_amount = string.Format(sql_temp, string.Format(sSubTableWhere, "ct"), string.Format(sSubTableWhere, "d") + " AND d.deleted = 0", sWhere); + var sql_abnormal_amount = string.Format(sql_temp, string.Format(sSubTableWhere, "ct"), string.Format(sSubTableWhere, "d") + " AND d.deleted = 0", sWhere); - var abnormal = await backendRepository.GetAllAsync(sql_abnormal_amount, param); + var abnormal = await backendRepository.GetAllAsync(sql_abnormal_amount, param); - var abnormal_amount = abnormal.Count(); + var abnormal_amount = abnormal.Count(); - DeviceCheck deviceCheck = new DeviceCheck(); - deviceCheck.DeviceCheckAmount = abnormal_amount; - deviceCheck.DeviceCheckTableList = deviceCheckTableList; + DeviceCheck deviceCheck = new DeviceCheck(); + deviceCheck.DeviceCheckAmount = abnormal_amount; + deviceCheck.DeviceCheckTableList = deviceCheckTableList; - apiResult.Code = "0000"; - apiResult.Data = deviceCheck; - } - catch (Exception exception) - { - apiResult.Code = "9999"; - apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; - Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); - } + apiResult.Code = "0000"; + apiResult.Data = deviceCheck; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } - return apiResult; - } + return apiResult; + } - /// - /// 資料檢核表格 - /// - /// - [HttpPost] - public async Task> DeviceCheckReplace(PostDeviceCheckFilter post) - { - ApiResult apiResult = new ApiResult(); + /// + /// 資料檢核表格 + /// + /// + [HttpPost] + public async Task> DeviceCheckReplace(PostDeviceCheckFilter post) + { + ApiResult apiResult = new ApiResult(); - try - { - //將該棟別的資料更換為正確 - string sql_update_correct = @"UPDATE device_import_ckeck_temp SET is_correct = 1 WHERE device_building_tag = @Device_building_tag"; - var param = new { Device_building_tag = post.Building_tag }; - await backendRepository.ExecuteSql(sql_update_correct, param); + try + { + //將該棟別的資料更換為正確 + string sql_update_correct = @"UPDATE device_import_ckeck_temp SET is_correct = 1 WHERE device_building_tag = @Device_building_tag"; + var param = new { Device_building_tag = post.Building_tag }; + await backendRepository.ExecuteSql(sql_update_correct, param); - //找出當前在device裡面有的,以供後續取代用 - string sql = @" + //找出當前在device裡面有的,以供後續取代用 + string sql = @" SELECT ct.*, d.device_guid @@ -717,99 +717,108 @@ namespace Backend.Controllers ) ct LEFT JOIN device d ON d.deleted = 0 AND ct.device_number = d.device_number"; - var check_temp_replaces = await backendRepository.GetAllAsync(sql, param); + var check_temp_replaces = await backendRepository.GetAllAsync(sql, param); - foreach (var check_temp_replace in check_temp_replaces) - { - Dictionary device_replace = new Dictionary() + foreach (var check_temp_replace in check_temp_replaces) + { + Dictionary device_replace = new Dictionary() { {"@device_system_category_layer3", check_temp_replace.Device_system_category_layer3}, }; - List> device_disaster_dicts = new List>() + List> device_disaster_dicts = new List>() { { new Dictionary() { { "@device_guid", check_temp_replace.Device_guid }, { "@device_system_value", check_temp_replace.Device_disaster } } } }; - await deviceImportRepository.ReplaceOneDeviceInfo(check_temp_replace.Device_guid, device_replace, device_disaster_dicts); - } - - apiResult.Code = "0000"; - apiResult.Msg = "取代成功"; - } - catch (Exception exception) - { - apiResult.Code = "9999"; - apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; - Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); - } - - return apiResult; - } - - /// - /// 更新設備 3d坐標, forge_dbid - /// - /// - [HttpPost] - public async Task> ImportDevForCor([FromBody] List post) - { - ApiResult apiResult = new ApiResult(); - var device_guid_record = ""; - try - { - if (post != null) - { - if (post.Count > 0) - { - //清空device_node資料表 - await backendRepository.TruncateTable("device_node"); - - int node_priority = 1; - foreach (var idfc in post) - { - if (idfc.device_number.IndexOf("_LT_L1") > -1) - { - //取得device_guid - var sWhere = $@" deleted = 0 and device_number = '" + idfc.device_number + "'"; - var device_guid = await backendRepository.GetOneColAsync("device", sWhere, "device_guid"); - if (device_guid.ToString() != device_guid_record) - { - device_guid_record = device_guid.ToString(); - node_priority = 1; - Dictionary deviceForLight = new Dictionary(); - deviceForLight.Add("@device_coordinate_3d", idfc.device_coordinate_3d); - deviceForLight.Add("@forge_dbid", idfc.forge_dbid); - deviceForLight.Add("@room_name", idfc.room_name); - deviceForLight.Add("@updated_at", DateTime.Now); - await backendRepository.UpdateOneByCustomTable(deviceForLight, "device", $@" device_guid = '{device_guid}'"); + await deviceImportRepository.ReplaceOneDeviceInfo(check_temp_replace.Device_guid, device_replace, device_disaster_dicts); } - //燈具 - Dictionary device = new Dictionary(); - device.Add("@device_node_guid", Guid.NewGuid()); - device.Add("@deleted", 0); - device.Add("@device_guid", device_guid); - device.Add("@device_node_coordinate_3d", idfc.device_coordinate_3d); - device.Add("@forge_dbid", idfc.forge_dbid); - device.Add("@priority", node_priority); - device.Add("@created_by", myUserInfo.Userinfo_guid); - device.Add("@created_at", DateTime.Now); + apiResult.Code = "0000"; + apiResult.Msg = "取代成功"; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } - node_priority++; - await backendRepository.AddOneByCustomTableReturnId(device, "device_node", false); - } - else - { - Dictionary device = new Dictionary(); - device.Add("@device_coordinate_3d", idfc.device_coordinate_3d); - device.Add("@forge_dbid", idfc.forge_dbid); - device.Add("@room_name", idfc.room_name); - device.Add("@updated_at", DateTime.Now); - await backendRepository.UpdateOneByCustomTable(device, "device", $@" device_number = '{idfc.device_number}'"); - } - //更新device資料表 room_dbid 欄位 - string sql = @" + return apiResult; + } + + /// + /// 更新設備 3d坐標, forge_dbid + /// + /// + [HttpPost] + public async Task> ImportDevForCor([FromBody] List post) + { + ApiResult apiResult = new ApiResult(); + var device_guid_record = ""; + try + { + if (post != null) + { + if (post.Count > 0) + { + //清空device_node資料表 + await backendRepository.TruncateTable("device_node"); + + int node_priority = 1; + + foreach (var idfc in post) + { + if (idfc.device_number.IndexOf("_LT_L1") > -1) + { + //取得device_guid + var sWhere = $@" deleted = 0 and device_number = '" + idfc.device_number + "'"; + var device_guid = await backendRepository.GetOneColAsync("device", sWhere, "device_guid"); + if (device_guid == null) + { + Logger.LogError("【" + controllerName + "/" + actionName + "】" + "【ERROR:forge匯入不存在device設備】" + idfc.device_number); + continue; + } + + if (device_guid.ToString() != device_guid_record) + { + device_guid_record = device_guid.ToString(); + node_priority = 1; + Dictionary deviceForLight = new Dictionary(); + deviceForLight.Add("@device_coordinate_3d", idfc.device_coordinate_3d); + deviceForLight.Add("@forge_dbid", idfc.forge_dbid); + deviceForLight.Add("@room_name", idfc.room_name); + deviceForLight.Add("@updated_at", DateTime.Now); + await backendRepository.UpdateOneByCustomTable(deviceForLight, "device", $@" device_guid = '{device_guid}'"); + } + + Dictionary device = new Dictionary(); + device.Add("@device_node_guid", Guid.NewGuid()); + device.Add("@deleted", 0); + device.Add("@device_guid", device_guid); + device.Add("@device_node_coordinate_3d", (idfc.node == null) ? idfc.device_coordinate_3d: idfc.node.device_coordinate_3d); + device.Add("@forge_dbid", (idfc.node == null) ? idfc.forge_dbid: idfc.node.forge_dbid); + device.Add("@device_number", (idfc.node == null) ? idfc.device_number : idfc.node.device_number); + device.Add("@priority", node_priority); + device.Add("@created_by", myUserInfo.Userinfo_guid); + device.Add("@created_at", DateTime.Now); + + node_priority++; + await backendRepository.AddOneByCustomTableReturnId(device, "device_node", false); + } + else + { + Logger.LogError("測試設備匯入:" + idfc.device_number); + Dictionary device = new Dictionary(); + device.Add("@device_coordinate_3d", idfc.device_coordinate_3d); + device.Add("@forge_dbid", idfc.forge_dbid); + device.Add("@room_name", idfc.room_name); + device.Add("@updated_at", DateTime.Now); + await backendRepository.UpdateOneByCustomTable(device, "device", $@" device_number = '{idfc.device_number}'"); + } + } + //更新device資料表 room_dbid 欄位 + string sql = @" SET SQL_SAFE_UPDATES = 0; UPDATE device AS de, @@ -819,72 +828,71 @@ namespace Backend.Controllers ) AS re SET de.room_dbid = re.room_id WHERE de.room_name = re.room_name;"; - await backendRepository.ExecuteSql(sql); + await backendRepository.ExecuteSql(sql); + } + apiResult.Code = "0000"; + apiResult.Msg = "編輯成功"; + } + else + { + apiResult.Code = "0001"; + apiResult.Msg = "無資料輸入"; + } } - } - apiResult.Code = "0000"; - apiResult.Msg = "編輯成功"; - } - else - { - apiResult.Code = "0001"; - apiResult.Msg = "無資料輸入"; - } - } - catch (Exception exception) - { - apiResult.Code = "9999"; - apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; - Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); - } - - return apiResult; - } - - /// - /// 更新forge_room room_id(dbid), room_name - /// - /// - [HttpPost] - public async Task> ImportForgeRoom([FromBody] List post) - { - ApiResult apiResult = new ApiResult(); - //var device_guid_record = ""; - try - { - if (post != null) - { - if (post.Count > 0) - { - //清空device_node資料表 - await backendRepository.TruncateTable("forge_room"); - - foreach (var idfc in post) + catch (Exception exception) { - // var room_name_arr = idfc.room_name.Split('_'); - string full_name = idfc.room_name; - char first = full_name[0]; - if (first != 'B' && first != 'R' && first != 'U') - { - full_name = 'U' + full_name; - } - - //var param = new { floor_name = floor_name }; - - //房間 新增Data至forge_room資料表 - Dictionary room = new Dictionary(); - room.Add("@room_id", idfc.room_id); - room.Add("@deleted", 0); - room.Add("@room_name", full_name); - room.Add("@created_at", DateTime.Now); - - await backendRepository.AddOneByCustomTableReturnId(room, "forge_room", false); - - + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } - //更新forge_room資料表 building_tag, floor_guid欄位 - string sql = @" + return apiResult; + } + + /// + /// 更新forge_room room_id(dbid), room_name + /// + /// + [HttpPost] + public async Task> ImportForgeRoom([FromBody] List post) + { + ApiResult apiResult = new ApiResult(); + //var device_guid_record = ""; + try + { + if (post != null) + { + if (post.Count > 0) + { + //清空device_node資料表 + await backendRepository.TruncateTable("forge_room"); + + foreach (var idfc in post) + { + // var room_name_arr = idfc.room_name.Split('_'); + string full_name = idfc.room_name; + char first = full_name[0]; + if (first != 'B' && first != 'R' && first != 'U') + { + full_name = 'U' + full_name; + } + + //var param = new { floor_name = floor_name }; + + //房間 新增Data至forge_room資料表 + Dictionary room = new Dictionary(); + room.Add("@room_id", idfc.room_id); + room.Add("@deleted", 0); + room.Add("@room_name", full_name); + room.Add("@created_at", DateTime.Now); + + await backendRepository.AddOneByCustomTableReturnId(room, "forge_room", false); + + + } + + //更新forge_room資料表 building_tag, floor_guid欄位 + string sql = @" update forge_room a join ( select building_tag, floor_guid, @@ -906,25 +914,25 @@ namespace Backend.Controllers )x on SUBSTRING_INDEX(a.room_name, '_', 1) = x.floor_name set a.building_tag = x.building_tag, a.floor_guid = x.floor_guid"; - await backendRepository.ExecuteSql(sql); - } - apiResult.Code = "0000"; - apiResult.Msg = "編輯成功"; - } - else - { - apiResult.Code = "0001"; - apiResult.Msg = "無資料輸入"; - } - } - catch (Exception exception) - { - apiResult.Code = "9999"; - apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; - Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); - } + await backendRepository.ExecuteSql(sql); + } + apiResult.Code = "0000"; + apiResult.Msg = "編輯成功"; + } + else + { + apiResult.Code = "0001"; + apiResult.Msg = "無資料輸入"; + } + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } - return apiResult; + return apiResult; + } } - } } diff --git a/Backend/Controllers/MybaseController.cs b/Backend/Controllers/MybaseController.cs index d155cb1..f75c4e0 100644 --- a/Backend/Controllers/MybaseController.cs +++ b/Backend/Controllers/MybaseController.cs @@ -95,7 +95,8 @@ namespace Backend.Controllers { "@created_by", myUserInfo.Userinfo_guid} }; - if (actionName != "CompareData" && controllerName != "NiagaraDataSynchronize") //skip the log + if ((actionName != "CompareData" && controllerName != "NiagaraDataSynchronize") && + (actionName != "ImportDevForCor" && controllerName != "DeviceImport")) //skip the log backendRepository.InsertOperatorLog(operatorLog, "operation_back_log"); //operatorLogRepository.Add(operatorLog, properties); diff --git a/Backend/Controllers/NiagaraDataSynchronizeController.cs b/Backend/Controllers/NiagaraDataSynchronizeController.cs index 60e02b0..1933a14 100644 --- a/Backend/Controllers/NiagaraDataSynchronizeController.cs +++ b/Backend/Controllers/NiagaraDataSynchronizeController.cs @@ -11,6 +11,7 @@ using Repository.Models; using System.Linq; using Microsoft.Extensions.DependencyInjection; using NPOI.SS.Formula.Functions; +using Repository.Helper; namespace Backend.Controllers { @@ -19,11 +20,13 @@ namespace Backend.Controllers private readonly IBackendRepository backendRepository; //private readonly IDeviceImportRepository deviceImportRepository; private readonly INiagaraDataSynchronizeRepository niagaraDataSynchronizeRepository; - public NiagaraDataSynchronizeController(IBackendRepository backendRepository, INiagaraDataSynchronizeRepository niagaraDataSynchronizeRepository) + private readonly IBackEndConfigHelper backEndConfig; + public NiagaraDataSynchronizeController(IBackendRepository backendRepository, INiagaraDataSynchronizeRepository niagaraDataSynchronizeRepository,IBackEndConfigHelper backEndConfig) { this.backendRepository = backendRepository; //this.deviceImportRepository = deviceImportRepository; this.niagaraDataSynchronizeRepository = niagaraDataSynchronizeRepository; + this.backEndConfig = backEndConfig; } public IActionResult Index() @@ -43,16 +46,14 @@ namespace Backend.Controllers try { List ds; - string url_slot = "slot:/TPE/B1|";//三菱 - //string url_slot = "slot:/NTPC/B1|";//wsp + string url_slot = backEndConfig.GetUrlSlot(); string top100 = "";//" top 100 "; webRequestService svc = new webRequestService(); string bql = url_slot + "bql:select " + top100 + " * from baja:Folder "; //ds = svc.obixQuery("http://192.168.0.136:8080/obix/config/Arena/Program/ObixQuery/query/", bql); //ds = svc.obixQuery("http://localhost:8080/obix/config/Program/ObixQuery/query/", bql); - ds = svc.obixQuery("http://192.168.0.136:8080/obix/config/Program/ObixQuery/query/", bql);//三菱 - //ds = svc.obixQuery("http://192.168.0.136:8081/obix/config/Program/ObixQuery/query/", bql);//wsp + ds = svc.obixQuery(backEndConfig.GetobixQuery(), bql);//三菱 apiResult.Code = "0000"; apiResult.Data = ds; @@ -112,12 +113,10 @@ namespace Backend.Controllers try { List ds; - string url_slot = "slot:/TPE/B1|";//三菱 - //string url_slot = "slot:/NTPC/B1|";//wsp + string url_slot = backEndConfig.GetUrlSlot(); webRequestService svc = new webRequestService(); - ds = svc.obixHisQuery("http://192.168.0.136:8080/obix/config/Program/ObixQuery/query/", "http://192.168.0.136:8080/obix/histories", url_slot);//三菱 - //ds = svc.obixHisQuery("http://192.168.0.136:8081/obix/config/Program/ObixQuery/query/", "http://192.168.0.136:8081/obix/histories", url_slot);//wsp + ds = svc.obixHisQuery(backEndConfig.GetobixHisBqlQuery(), backEndConfig.GetobixHisUrlQuery(), url_slot);//三菱 apiResult.Code = "0000"; apiResult.Data = ds; diff --git a/Backend/Models/Device.cs b/Backend/Models/Device.cs index 8bf91bd..004d98a 100644 --- a/Backend/Models/Device.cs +++ b/Backend/Models/Device.cs @@ -265,6 +265,19 @@ namespace Backend.Models } public class ImportDevForCoo + { + public string device_number { get; set; } + public string? device_coordinate_3d { get; set; } + public int forge_dbid { get; set; } + public string room_name { get; set; } + + /// + /// 燈具放在子類別 node 中 + /// + public device_node? node { get; set; } +} + + public class device_node { public string device_number { get; set; } public string device_coordinate_3d { get; set; } diff --git a/Backend/Startup.cs b/Backend/Startup.cs index 7285fc6..37e1ba6 100644 --- a/Backend/Startup.cs +++ b/Backend/Startup.cs @@ -36,6 +36,10 @@ namespace Backend MySqlDBConfig = new MySqlDBConfig() }; + public BackEndConfig BackEndConfig = new BackEndConfig() + { + NiagaraDataSyncConfig=new NiagaraDataSyncConfig() + }; public Startup(IConfiguration configuration) { Configuration = configuration; @@ -56,6 +60,13 @@ namespace Backend dBConfig.MySqlDBConfig.Database = Configuration.GetValue("DBConfig:MySqlDBConfig:Database"); #endregion MySql DB Config + #region NiagaraDataSync Config + BackEndConfig.NiagaraDataSyncConfig.UrlSlot = Configuration.GetValue("BackEndConfig:NiagaraDataSyncConfig:UrlSlot"); + BackEndConfig.NiagaraDataSyncConfig.ObixQuery= Configuration.GetValue("BackEndConfig:NiagaraDataSyncConfig:ObixQuery"); + BackEndConfig.NiagaraDataSyncConfig.ObixHisBqlQuery = Configuration.GetValue("BackEndConfig:NiagaraDataSyncConfig:ObixHisBqlQuery"); + BackEndConfig.NiagaraDataSyncConfig.ObixHisUrlQuery = Configuration.GetValue("BackEndConfig:NiagaraDataSyncConfig:ObixHisUrlQuery"); + #endregion + } public IConfiguration Configuration { get; } @@ -89,6 +100,13 @@ namespace Backend services.AddTransient(); #endregion DBHelper `J + #region BackEndConfigHelper `J + services.Configure(Configuration.GetSection("BackEndConfig")); + services.AddTransient(); + #endregion DBHelper `J + + + #region Repository `J services.AddTransient(); services.AddTransient(); diff --git a/Backend/appsettings.Development.json b/Backend/appsettings.Development.json index e02e024..24e445c 100644 --- a/Backend/appsettings.Development.json +++ b/Backend/appsettings.Development.json @@ -42,5 +42,17 @@ // "Root": "+plVKQ+enAqt7BYV2uMQng==", // "Password": "0O24es2ZRF5uoJ4aU+YCdg==" //} + }, + "BackEndConfig": { + "NiagaraDataSyncConfig": { + "UrlSlot": "GbZ+gly0WQOx1PO+Y4T1/A==", //WSP + "ObixQuery": "7C/j7U8PmDqMxpb7f6gMpHNoRwKZ9K5QF8eWPaSWVNYQpjygWdccOOkHLWCOLi/+zCwsX2CcMhlAJ5082oeSiQ==", //WSP + "ObixHisBqlQuery": "7C/j7U8PmDqMxpb7f6gMpHNoRwKZ9K5QF8eWPaSWVNYQpjygWdccOOkHLWCOLi/+zCwsX2CcMhlAJ5082oeSiQ==", //WSP + "ObixHisUrlQuery": "7C/j7U8PmDqMxpb7f6gMpObRPTGh1jI6LBqMJk0hrp7UqBfP1mt4ADLSdmf4ubca" //WSP + //"UrlSlot": "+I/QBiWGAk/BQZOwiz16gw==", //三菱 + //"ObixQuery": "7C/j7U8PmDqMxpb7f6gMpHFicuOA83OZeuWHBFdi/xpfEIklxyQ/wP75bEKwrdh+fXXgjmpc9cLX9GqbBC7eGw==", //三菱 + //"ObixHisBqlQuery": "7C/j7U8PmDqMxpb7f6gMpHFicuOA83OZeuWHBFdi/xpfEIklxyQ/wP75bEKwrdh+fXXgjmpc9cLX9GqbBC7eGw==", //三菱 + //"ObixHisUrlQuery": "7C/j7U8PmDqMxpb7f6gMpD06cJcRzpVx0+IAssROlE4MlzSDPojSI17+XkQIL9Eu" //三菱 + } } } diff --git a/Backend/appsettings.json b/Backend/appsettings.json index 2034e27..8d796da 100644 --- a/Backend/appsettings.json +++ b/Backend/appsettings.json @@ -16,8 +16,8 @@ "MySqlDBConfig": { "Server": "FYlY+w0XDIz+jmF2rlZWJw==", //0.201 "Port": "js2LutKe+rdjzdxMPQUrvQ==", - "Database": "VJB2XC+lAtzuHObDGMVOAA==", //三菱 - //"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp + //"Database": "VJB2XC+lAtzuHObDGMVOAA==", //三菱 + "Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp "Root": "SzdxEgaJJ7tcTCrUl2zKsA==", "Password": "FVAPxztxpY4gJJKQ/se4bQ==" } @@ -28,5 +28,17 @@ // "Root": "+plVKQ+enAqt7BYV2uMQng==", // "Password": "0O24es2ZRF5uoJ4aU+YCdg==" //} + }, + "BackEndConfig": { + "NiagaraDataSyncConfig": { + "UrlSlot": "GbZ+gly0WQOx1PO+Y4T1/A==", //WSP + "ObixQuery": "7C/j7U8PmDqMxpb7f6gMpHNoRwKZ9K5QF8eWPaSWVNYQpjygWdccOOkHLWCOLi/+zCwsX2CcMhlAJ5082oeSiQ==", //WSP + "ObixHisBqlQuery": "7C/j7U8PmDqMxpb7f6gMpHNoRwKZ9K5QF8eWPaSWVNYQpjygWdccOOkHLWCOLi/+zCwsX2CcMhlAJ5082oeSiQ==", //WSP + "ObixHisUrlQuery": "7C/j7U8PmDqMxpb7f6gMpObRPTGh1jI6LBqMJk0hrp7UqBfP1mt4ADLSdmf4ubca" //WSP + //"UrlSlot": "+I/QBiWGAk/BQZOwiz16gw==", //三菱 + //"ObixQuery": "7C/j7U8PmDqMxpb7f6gMpHFicuOA83OZeuWHBFdi/xpfEIklxyQ/wP75bEKwrdh+fXXgjmpc9cLX9GqbBC7eGw==", //三菱 + //"ObixHisBqlQuery": "7C/j7U8PmDqMxpb7f6gMpHFicuOA83OZeuWHBFdi/xpfEIklxyQ/wP75bEKwrdh+fXXgjmpc9cLX9GqbBC7eGw==", //三菱 + //"ObixHisUrlQuery": "7C/j7U8PmDqMxpb7f6gMpD06cJcRzpVx0+IAssROlE4MlzSDPojSI17+XkQIL9Eu" //三菱 + } } } diff --git a/Backend/wwwroot/forgeDemo.html b/Backend/wwwroot/forgeDemo.html index 97a0caf..acb4db5 100644 --- a/Backend/wwwroot/forgeDemo.html +++ b/Backend/wwwroot/forgeDemo.html @@ -416,6 +416,7 @@ } function ImportDevForCor() {//callback = null + console.log(tagIdDevList) var url = "/DeviceImport/ImportDevForCor"; $.ajax({ diff --git a/Backend/wwwroot/js/forge/ForgeDemo.js b/Backend/wwwroot/js/forge/ForgeDemo.js index 3b6b44e..9f44759 100644 --- a/Backend/wwwroot/js/forge/ForgeDemo.js +++ b/Backend/wwwroot/js/forge/ForgeDemo.js @@ -354,7 +354,8 @@ function onDocumentLoadSuccess(doc) { device_number: item.displayValue, device_coordinate_3d: '{ "x": ' + (position.x).toFixed(2) + ', "y": ' + (position.y).toFixed(2) + ', "z": ' + (position.z).toFixed(2) + ' }', forge_dbid: e.dbId, - room_name: "" + room_name: "", + node: null }) } } diff --git a/BackendWorkerService/Program.cs b/BackendWorkerService/Program.cs index b076db2..d773820 100644 --- a/BackendWorkerService/Program.cs +++ b/BackendWorkerService/Program.cs @@ -73,6 +73,13 @@ namespace BackendWorkerService services.AddTransient(); #endregion DBHelper `J + + #region BackEndConfigHelper `J + services.Configure(configuration.GetSection("BackEndConfig")); + services.AddTransient(); + #endregion BackEndConfigHelper `J + + #region Repository `J services.AddTransient(); services.AddTransient(); diff --git a/FrontendWebApi/ApiControllers/DeviceManageController.cs b/FrontendWebApi/ApiControllers/DeviceManageController.cs index 5e19d8b..228f11a 100644 --- a/FrontendWebApi/ApiControllers/DeviceManageController.cs +++ b/FrontendWebApi/ApiControllers/DeviceManageController.cs @@ -75,7 +75,7 @@ namespace FrontendWebApi.ApiControllers left join device_kind dk on v1.system_value = dk.device_system_tag and v2.system_value = dk.device_name_tag and dk.device_building_tag = @building_tag -- left join device_item di on v2.system_value = di.device_name_tag and v1.system_value = di.device_system_tag and di.deleted = 0 join ( - select distinct main_system_tag, sub_system_tag from building_menu where building_tag = @building_tag + select distinct main_system_tag, sub_system_tag from building_menu where building_tag = @building_tag and is_link = 1 ) as bm on v2.system_value = bm.sub_system_tag and v1.system_value = bm.main_system_tag where c.account = @account order by v2.system_priority", new { @account = myUser.account, @sub_system_type = sub_system_type, @main_system_type = main_system_type, @building_tag = fd.building_tag }); diff --git a/Repository/Helper/BackEndConfigHelper.cs b/Repository/Helper/BackEndConfigHelper.cs new file mode 100644 index 0000000..d3fd62f --- /dev/null +++ b/Repository/Helper/BackEndConfigHelper.cs @@ -0,0 +1,57 @@ +using Microsoft.Extensions.Options; +using Repository.Models; + +namespace Repository.Helper +{ + public interface IBackEndConfigHelper + { + /// + /// 取得url_slot + /// + /// + string GetUrlSlot(); + + /// + /// 取得obixQuery + /// + /// + string GetobixQuery(); + + string GetobixHisBqlQuery(); + + string GetobixHisUrlQuery(); + } + + + public class BackEndConfigHelper : IBackEndConfigHelper + { + private NiagaraDataSyncConfig _NiagaraDataSyncConfig; + private EDFunction ed; + public BackEndConfigHelper(IOptions BackEndConfig) + { + _NiagaraDataSyncConfig = BackEndConfig.Value.NiagaraDataSyncConfig; + + ed = new EDFunction(); + } + public string GetUrlSlot() + { + return ed.AESDecrypt(_NiagaraDataSyncConfig.UrlSlot); + } + public string GetobixQuery() + { + return ed.AESDecrypt(_NiagaraDataSyncConfig.ObixQuery); + } + + public string GetobixHisBqlQuery() + { + return ed.AESDecrypt(_NiagaraDataSyncConfig.ObixHisBqlQuery); + } + public string GetobixHisUrlQuery() + { + return ed.AESDecrypt(_NiagaraDataSyncConfig.ObixHisUrlQuery); + } + + + } + +} diff --git a/Repository/Models/BackEndConfig.cs b/Repository/Models/BackEndConfig.cs new file mode 100644 index 0000000..f830321 --- /dev/null +++ b/Repository/Models/BackEndConfig.cs @@ -0,0 +1,17 @@ +namespace Repository.Models +{ + public class BackEndConfig + { + public NiagaraDataSyncConfig NiagaraDataSyncConfig { get; set; } + } + + public class NiagaraDataSyncConfig + { + public string UrlSlot { get; set; } + public string ObixQuery { get; set; } + public string ObixHisBqlQuery { get; set; } + public string ObixHisUrlQuery { get; set; } + } + + +}