diff --git a/BackendWorkerService/BackendWorkerService.csproj b/BackendWorkerService/BackendWorkerService.csproj index 0bcb027..06a89c1 100644 --- a/BackendWorkerService/BackendWorkerService.csproj +++ b/BackendWorkerService/BackendWorkerService.csproj @@ -7,6 +7,7 @@ + diff --git a/BackendWorkerService/Quartz/Jobs/ArchiveElectricMeterDayJob.cs b/BackendWorkerService/Quartz/Jobs/ArchiveElectricMeterDayJob.cs index aeb8626..39c05fc 100644 --- a/BackendWorkerService/Quartz/Jobs/ArchiveElectricMeterDayJob.cs +++ b/BackendWorkerService/Quartz/Jobs/ArchiveElectricMeterDayJob.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using NPOI.SS.Formula.Functions; using Quartz; using Repository.BackendRepository.Interface; using Repository.Helper; @@ -140,9 +141,10 @@ namespace BackendWorkerService.Quartz.Jobs { try { + await task_Detail.InsertWorkTime("ArchiveElectricMeterDayJob", "Day", "水電表天任務開始"); - //var preDay = now.AddDays(-1); //取得前一天 - //var dbDateName = preDay.Year.ToString().PadLeft(4, '0') + preDay.Month.ToString().PadLeft(2, '0'); + var preDay = now.AddDays(-1); //取得前一天 + var dbDateName = preDay.Year.ToString().PadLeft(4, '0') + preDay.Month.ToString().PadLeft(2, '0'); //var startTimestamp = string.Format("{0}T00:00:00.000+08:00", preDay.ToString("yyyy-MM-dd")); //var endTimestamp = string.Format("{0}T23:59:59.000+08:00", preDay.ToString("yyyy-MM-dd")); @@ -153,17 +155,11 @@ namespace BackendWorkerService.Quartz.Jobs // // "; - #region 從前次 成功日期到昨天為止 - - var preDay = now.AddDays(-1); //取得前一天 - - var dbDateName = preDay.Year.ToString().PadLeft(4, '0') + preDay.Month.ToString().PadLeft(2, '0'); - - #endregion - //Stopwatch stopWatch = new Stopwatch(); //stopWatch.Start(); + #region 從前次 成功日期到昨天為止 + //抓取每個設備的資料 List> electericArchiveDayRawDatas = new List>(); List> waterArchiveDayRawDatas = new List>(); @@ -173,7 +169,9 @@ namespace BackendWorkerService.Quartz.Jobs var endDay = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); foreach (DateTime day in EachDay(startDay, endDay)) { - var sDay = string.Format("{0}T00:00:00.000+08:00", day.ToString("yyyy-MM-dd").Replace(" ", "T")); + var sDay = string.Format("{0}T00:00:00.000+08:00", day.ToString("yyyy-MM-dd").Replace(" ", "T")); // 巨蛋用此時間抓到的實際是T00:15:00的資料 + //var sDay = string.Format("{0}T23:59:59.000+08:00", day.AddDays(-1).ToString("yyyy-MM-dd").Replace(" ", "T")); // 巨蛋用此時間抓到的實際是T00:00:00的資料 + var eDay = string.Format("{0}T00:15:00.000+08:00", day.AddDays(1).ToString("yyyy-MM-dd").Replace(" ", "T")); @@ -252,10 +250,12 @@ namespace BackendWorkerService.Quartz.Jobs foreach (var deviceNumberPoint in waterDeviceNumberPoints) { var startDay = deviceNumberPoint.archive_lastDate.ToString("yyyy-MM-dd"); - var endDay = System.DateTime.Now.ToString("yyyy-MM-dd"); + var endDay = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); foreach (DateTime day in EachDay(startDay, endDay)) { - var sDay = string.Format("{0}T00:00:00.000+08:00", day.ToString("yyyy-MM-dd").Replace(" ", "T")); + var sDay = string.Format("{0}T00:00:00.000+08:00", day.ToString("yyyy-MM-dd").Replace(" ", "T")); // 巨蛋用此時間抓到的實際是T00:15:00的資料 + //var sDay = string.Format("{0}T23:59:59.000+08:00", day.AddDays(-1).ToString("yyyy-MM-dd").Replace(" ", "T")); // 巨蛋用此時間抓到的實際是T00:00:00的資料 + var eDay = string.Format("{0}T00:15:00.000+08:00", day.AddDays(1).ToString("yyyy-MM-dd").Replace(" ", "T")); @@ -334,13 +334,17 @@ namespace BackendWorkerService.Quartz.Jobs } } - + #endregion //stopWatch.Stop(); //logger.LogInformation("【ArchiveElectricMeterDayJob】【天歸檔】【效能檢驗】[取得資料花費時間]{0} 毫秒", stopWatch.ElapsedMilliseconds); if (electericArchiveDayRawDatas.Count() > 0) { - var sql = $@"CREATE TABLE IF NOT EXISTS `archive_electric_water_meter_day_{dbDateName}` ( + foreach (var row in electericArchiveDayRawDatas) + { + row.TryGetValue("@start_timestamp", out var yyyymmData); + dbDateName = System.DateTime.Parse(yyyymmData.ToString()).ToString("yyyyMM"); + var sql = $@"CREATE TABLE IF NOT EXISTS `archive_electric_water_meter_day_{dbDateName}` ( `device_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `point` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `start_timestamp` datetime(6) NOT NULL, @@ -407,7 +411,7 @@ namespace BackendWorkerService.Quartz.Jobs update device set archive_lastDate = @start_timestamp, archive_lastActionDate = @updated_at where device_number = @device_number;"; //archive_lastDate 前次完成時間 ,archive_lastActionDate 本次作業時間 - var mySql = $@"BEGIN TRANSACTION; + var mySql = $@"BEGIN TRANSACTION; IF OBJECT_ID(N'dbo.archive_electric_water_meter_day_{dbDateName}', N'U') is null BEGIN CREATE TABLE [dbo].[archive_electric_water_meter_day_{dbDateName}]( @@ -495,15 +499,20 @@ namespace BackendWorkerService.Quartz.Jobs END COMMIT TRANSACTION;"; - await backgroundServiceRepository.ExecuteSql(sql, electericArchiveDayRawDatas); - if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1") - { - await backgroundServiceMsSqlRepository.ExecuteSql(mySql, electericArchiveDayRawDatas); + await backgroundServiceRepository.ExecuteSql(sql, row); + if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1") + { + await backgroundServiceMsSqlRepository.ExecuteSql(mySql, row); + } } } if (waterArchiveDayRawDatas.Count() > 0) { - var sql = $@" + foreach (var row in waterArchiveDayRawDatas) + { + row.TryGetValue("@start_timestamp", out var yyyymmData); + dbDateName = System.DateTime.Parse(yyyymmData.ToString()).ToString("yyyyMM"); + var sql = $@" CREATE TABLE IF NOT EXISTS `archive_electric_water_meter_day_{dbDateName}` ( `device_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `point` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, @@ -571,7 +580,7 @@ namespace BackendWorkerService.Quartz.Jobs update device set archive_lastDate = @start_timestamp, archive_lastActionDate = @updated_at where device_number = @device_number;"; //archive_lastDate 前次完成時間 ,archive_lastActionDate 本次作業時間 - var mySql = $@"BEGIN TRANSACTION; + var mySql = $@"BEGIN TRANSACTION; IF OBJECT_ID(N'dbo.archive_electric_water_meter_day_{dbDateName}', N'U') is null BEGIN CREATE TABLE [dbo].[archive_electric_water_meter_day_{dbDateName}]( @@ -659,13 +668,14 @@ namespace BackendWorkerService.Quartz.Jobs END COMMIT TRANSACTION;"; - await backgroundServiceRepository.ExecuteSql(sql, waterArchiveDayRawDatas); - if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1") - { - await backgroundServiceMsSqlRepository.ExecuteSql(mySql, waterArchiveDayRawDatas); + await backgroundServiceRepository.ExecuteSql(sql, row); + if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1") + { + await backgroundServiceMsSqlRepository.ExecuteSql(mySql, row); + } } } - await task_Detail.InsertWorkTime_End("ArchiveElectricMeterDayJob", "Day", "任務完成"); + await task_Detail.InsertWorkTime_End("ArchiveElectricMeterDayJob", "Day", "水電表天任務完成"); } catch (Exception exception) { @@ -1090,14 +1100,18 @@ namespace BackendWorkerService.Quartz.Jobs try { await task_Detail.InsertWorkTime("ArchiveElectricMeterDayJob", "Month", "水電表月任務開始"); - var FirstDay = now.AddDays(-now.Day + 1); - //var LastDay = now.AddMonths(1).AddDays(-now.AddMonths(1).Day); - var LastDay = FirstDay.AddMonths(1); + var preDay = now.AddDays(-1); //取得前一天 + + var dayInMonth = DateTime.DaysInMonth(preDay.Year, preDay.Month); + var FirstDay = new DateTime(preDay.Year, preDay.Month, 1); + //var LastDay = now.AddMonths(1).AddDays(-now.AddMonths(1).Day); // 這是抓到該月最後一天 + var LastDay = now; - var dayInMonth = DateTime.DaysInMonth(now.Year, now.Month); - var startTimestamp = string.Format("{0}T00:00:00.000+08:00", FirstDay.ToString("yyyy-MM-dd")); + //var startTimestamp = string.Format("{0}T23:59:59.000+08:00", FirstDay.AddDays(-1).ToString("yyyy-MM-dd")); // 巨蛋要這樣抓數據才是對的 + var startTimestamp = string.Format("{0}T00:00:00.000+08:00", FirstDay.ToString("yyyy-MM-dd")); + //var endTimestamp = string.Format("{0}T23:59:59.000+08:00", LastDay.ToString("yyyy-MM-dd")); var endTimestamp = string.Format("{0}T00:15:00.000+08:00", LastDay.ToString("yyyy-MM-dd")); // 240131 jay for dome @@ -1105,7 +1119,7 @@ namespace BackendWorkerService.Quartz.Jobs var historyQueryFilter = $@" - + "; //Stopwatch stopWatch = new Stopwatch(); @@ -1258,7 +1272,29 @@ namespace BackendWorkerService.Quartz.Jobs if (electricArchiveMonthRawDatas.Count() > 0) { var sql = $@" + CREATE TABLE IF NOT EXISTS `archive_electric_water_meter_month` ( + `device_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, + `point` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, + `start_timestamp` datetime(6) NOT NULL, + `end_timestamp` datetime(6) NULL DEFAULT NULL, + `count_rawdata` int(11) NULL DEFAULT NULL, + `min_rawdata` decimal(15, 3) NULL DEFAULT NULL, + `max_rawdata` decimal(15, 3) NULL DEFAULT NULL, + `sub_result` decimal(15, 3) NULL DEFAULT NULL, + `avg_rawdata` decimal(15, 3) NULL DEFAULT NULL, + `sum_rawdata` decimal(15, 3) NULL DEFAULT NULL, + `is_complete` tinyint(3) UNSIGNED NULL DEFAULT NULL COMMENT '是否完成,0:未完成 1:完成', + `repeat_times` int(11) NULL DEFAULT 0 COMMENT '重複次數', + `fail_reason` varchar(4000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '失敗原因', + `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `updated_at` datetime(6) NULL DEFAULT NULL, + PRIMARY KEY (`device_number`, `point`, `start_timestamp`) USING BTREE + ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = DYNAMIC; + + SET FOREIGN_KEY_CHECKS = 1; UPDATE archive_electric_water_meter_month SET + start_timestamp = @start_timestamp, + end_timestamp = @end_timestamp, count_rawdata = @count_rawdata, min_rawdata = @min_rawdata, max_rawdata = @max_rawdata, @@ -1304,8 +1340,48 @@ namespace BackendWorkerService.Quartz.Jobs WHERE ROW_COUNT() = 0;"; var mySql = $@"BEGIN TRANSACTION; + IF OBJECT_ID(N'dbo.archive_electric_water_meter_month', N'U') is null + BEGIN + CREATE TABLE [dbo].[archive_electric_water_meter_month]( + [device_number] [varchar](50) NOT NULL, + [point] [varchar](20) NOT NULL, + [start_timestamp] [datetime] NOT NULL, + [end_timestamp] [datetime] NULL, + [count_rawdata] [int] NULL, + [min_rawdata] [decimal](15, 3) NULL, + [max_rawdata] [decimal](15, 3) NULL, + [sub_result] [decimal](15, 3) NULL, + [avg_rawdata] [decimal](15, 3) NULL, + [sum_rawdata] [decimal](15, 3) NULL, + [is_complete] [tinyint] NULL, + [repeat_times] [int] NULL, + [fail_reason] [nvarchar](max) NULL, + [created_at] [datetime] NULL, + [updated_at] [datetime] NULL, + CONSTRAINT [PK_archive_electric_water_meter_month] PRIMARY KEY CLUSTERED + ( + [device_number] ASC, + [point] ASC, + [start_timestamp] ASC + )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] + ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] + + ALTER TABLE [dbo].[archive_electric_water_meter_month] ADD CONSTRAINT [DF_archive_electric_water_meter_month_repeat_times] DEFAULT ((0)) FOR [repeat_times] + + ALTER TABLE [dbo].[archive_electric_water_meter_month] ADD CONSTRAINT [DF_archive_electric_water_meter_month_created_at] DEFAULT (getdate()) FOR [created_at] + + ALTER TABLE [dbo].[archive_electric_water_meter_month] ADD CONSTRAINT [DF_archive_electric_water_meter_month_updated_at] DEFAULT (NULL) FOR [updated_at] + + EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否完成,0:未完成 1:完成' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'archive_electric_water_meter_month', @level2type=N'COLUMN',@level2name=N'is_complete' + + EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'重複次數' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'archive_electric_water_meter_month', @level2type=N'COLUMN',@level2name=N'repeat_times' + + EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'失敗原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'archive_electric_water_meter_month', @level2type=N'COLUMN',@level2name=N'fail_reason' + END UPDATE archive_electric_water_meter_month SET + start_timestamp = @start_timestamp, + end_timestamp = @end_timestamp, count_rawdata = @count_rawdata, min_rawdata = @min_rawdata, max_rawdata = @max_rawdata, @@ -1362,7 +1438,29 @@ namespace BackendWorkerService.Quartz.Jobs if (waterArchiveMonthRawDatas.Count() > 0) { var sql = $@" + CREATE TABLE IF NOT EXISTS `archive_electric_water_meter_month` ( + `device_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, + `point` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, + `start_timestamp` datetime(6) NOT NULL, + `end_timestamp` datetime(6) NULL DEFAULT NULL, + `count_rawdata` int(11) NULL DEFAULT NULL, + `min_rawdata` decimal(15, 3) NULL DEFAULT NULL, + `max_rawdata` decimal(15, 3) NULL DEFAULT NULL, + `sub_result` decimal(15, 3) NULL DEFAULT NULL, + `avg_rawdata` decimal(15, 3) NULL DEFAULT NULL, + `sum_rawdata` decimal(15, 3) NULL DEFAULT NULL, + `is_complete` tinyint(3) UNSIGNED NULL DEFAULT NULL COMMENT '是否完成,0:未完成 1:完成', + `repeat_times` int(11) NULL DEFAULT 0 COMMENT '重複次數', + `fail_reason` varchar(4000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '失敗原因', + `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `updated_at` datetime(6) NULL DEFAULT NULL, + PRIMARY KEY (`device_number`, `point`, `start_timestamp`) USING BTREE + ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = DYNAMIC; + + SET FOREIGN_KEY_CHECKS = 1; UPDATE archive_electric_water_meter_month SET + start_timestamp = @start_timestamp, + end_timestamp = @end_timestamp, count_rawdata = @count_rawdata, min_rawdata = @min_rawdata, max_rawdata = @max_rawdata, @@ -1408,8 +1506,48 @@ namespace BackendWorkerService.Quartz.Jobs WHERE ROW_COUNT() = 0;"; var mySql = $@"BEGIN TRANSACTION; + IF OBJECT_ID(N'dbo.archive_electric_water_meter_month', N'U') is null + BEGIN + CREATE TABLE [dbo].[archive_electric_water_meter_month]( + [device_number] [varchar](50) NOT NULL, + [point] [varchar](20) NOT NULL, + [start_timestamp] [datetime] NOT NULL, + [end_timestamp] [datetime] NULL, + [count_rawdata] [int] NULL, + [min_rawdata] [decimal](15, 3) NULL, + [max_rawdata] [decimal](15, 3) NULL, + [sub_result] [decimal](15, 3) NULL, + [avg_rawdata] [decimal](15, 3) NULL, + [sum_rawdata] [decimal](15, 3) NULL, + [is_complete] [tinyint] NULL, + [repeat_times] [int] NULL, + [fail_reason] [nvarchar](max) NULL, + [created_at] [datetime] NULL, + [updated_at] [datetime] NULL, + CONSTRAINT [PK_archive_electric_water_meter_month] PRIMARY KEY CLUSTERED + ( + [device_number] ASC, + [point] ASC, + [start_timestamp] ASC + )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] + ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] + + ALTER TABLE [dbo].[archive_electric_water_meter_month] ADD CONSTRAINT [DF_archive_electric_water_meter_month_repeat_times] DEFAULT ((0)) FOR [repeat_times] + + ALTER TABLE [dbo].[archive_electric_water_meter_month] ADD CONSTRAINT [DF_archive_electric_water_meter_month_created_at] DEFAULT (getdate()) FOR [created_at] + + ALTER TABLE [dbo].[archive_electric_water_meter_month] ADD CONSTRAINT [DF_archive_electric_water_meter_month_updated_at] DEFAULT (NULL) FOR [updated_at] + + EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否完成,0:未完成 1:完成' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'archive_electric_water_meter_month', @level2type=N'COLUMN',@level2name=N'is_complete' + + EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'重複次數' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'archive_electric_water_meter_month', @level2type=N'COLUMN',@level2name=N'repeat_times' + + EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'失敗原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'archive_electric_water_meter_month', @level2type=N'COLUMN',@level2name=N'fail_reason' + END UPDATE archive_electric_water_meter_month SET + start_timestamp = @start_timestamp, + end_timestamp = @end_timestamp, count_rawdata = @count_rawdata, min_rawdata = @min_rawdata, max_rawdata = @max_rawdata, @@ -1463,7 +1601,7 @@ namespace BackendWorkerService.Quartz.Jobs await backgroundServiceMsSqlRepository.ExecuteSql(mySql, waterArchiveMonthRawDatas); } } - await task_Detail.InsertWorkTime_End("ArchiveElectricMeterDayJob", "Month", "任務完成"); + await task_Detail.InsertWorkTime_End("ArchiveElectricMeterDayJob", "Month", "水電表月任務完成"); } catch (Exception exception) { @@ -1520,6 +1658,14 @@ namespace BackendWorkerService.Quartz.Jobs for (var day = strtday.Date; day.Date <= endday.Date; day = day.AddDays(1)) yield return day; } + public IEnumerable EachMonth(string from, string thru) + { + var strtday = DateTime.Parse(from); + var endday = DateTime.Parse(thru); + for (var _month = strtday.Date; _month.Month <= endday.Month; _month = _month.AddDays(1)) + yield return _month; + + } private List> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult) { List> arrangeRawDatas = new List>(); diff --git a/BackendWorkerService/appsettings.Development.json b/BackendWorkerService/appsettings.Development.json index 1a5d4fd..9dd0d11 100644 --- a/BackendWorkerService/appsettings.Development.json +++ b/BackendWorkerService/appsettings.Development.json @@ -19,7 +19,7 @@ }, "DBConfig": { "MySqlDBConfig": { - "Server": "CYGthbCeGtAXT4s1NOSJHQ==", //0.202 + "Server": "CYGthbCeGtAXT4s1NOSJHQ==", //0.132 "Port": "mkF51jVbg40V5K5eTh2Ckw==", //3306 //"Database": "VJB2XC+lAtzuHObDGMVOAA==", //30 //"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp diff --git a/FrontendWebApi/ApiControllers/TenantBillController.cs b/FrontendWebApi/ApiControllers/TenantBillController.cs index b78f3a8..0ced42d 100644 --- a/FrontendWebApi/ApiControllers/TenantBillController.cs +++ b/FrontendWebApi/ApiControllers/TenantBillController.cs @@ -19,6 +19,7 @@ using Microsoft.Extensions.Configuration; using Serilog.Core; using static FrontendWebApi.ApiControllers.TenantBillController; using System.Reflection; +using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -109,7 +110,8 @@ namespace FrontendWebApi.ApiControllers apiResult.Msg = "新增用戶失敗。"; if (exception.Message.Contains($" for key 'PRIMARY'")) { - apiResult.Msg = "已有相同使用者。"; + apiResult.Code = "0001"; + apiResult.Msg = "已有相同用戶。"; } Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } @@ -143,6 +145,7 @@ namespace FrontendWebApi.ApiControllers apiResult.Msg = "修改失敗。"; if (exception.Message.Contains($"a foreign key constraint")) { + apiResult.Code = "0001"; apiResult.Msg = "水電報表仍有該用戶,無法修改名稱。"; } Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); @@ -170,6 +173,7 @@ namespace FrontendWebApi.ApiControllers apiResult.Msg = "刪除用戶失敗。"; if (exception.Message.Contains($"a foreign key constraint")) { + apiResult.Code = "0001"; apiResult.Msg = "水電報表仍有該用戶,無法刪除。"; } Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); @@ -190,14 +194,7 @@ namespace FrontendWebApi.ApiControllers string building_tag = tb.building_tag; string ElecOrWater = tableType == "elec" ? "E4" : "W1"; string sqlString = null; - if (building_tag == "ALL") - { - sqlString = - $"SELECT bill_id,a.device_number,a.full_name,start_timestamp,end_timestamp,result,bill,tenant_name,tenant_guid " + - $"from {TenantBilltable} a join device b on a.device_number =b.device_number" + - $"where a.device_name_tag = '{ElecOrWater}' "; - } - else if (building_tag == "D2") + if (building_tag == "D2") { sqlString = $"SELECT bill_id,a.device_number,a.full_name,start_timestamp,end_timestamp,result,bill,tenant_name,tenant_guid " + @@ -248,22 +245,82 @@ namespace FrontendWebApi.ApiControllers startMonth = tb.start_timestamp.Split("-")[0] + tb.start_timestamp.Split("-")[1]; endMonth = tb.end_timestamp.Split("-")[0] + tb.end_timestamp.Split("-")[1]; } - if (start_timestamp == "") - { - apiResult.Code = "9999"; - apiResult.Msg = "請選擇起始日期。"; - return apiResult; - } - if (end_timestamp == "") - { - apiResult.Code = "9999"; - apiResult.Msg = "請選擇結束日期。"; - return apiResult; - } - - if (startMonth == endMonth) + else { sqlString = + $@"UPDATE {TenantBilltable} + set tenant_name = (SELECT tenant_name from archive_electric_meter_tenant_list WHERE tenant_guid = '{tb.tenant_guid}'), + result = 0, + bill= 0, + start_timestamp = '{start_timestamp}', + end_timestamp = '{end_timestamp}', + updated_at = '{updated_at}', + tenant_guid = '{tb.tenant_guid}' + WHERE device_number = '{tb.device_number}'"; + + await backendRepository.ExecuteSql(sqlString); + + + apiResult.Code = "0000"; + apiResult.Data = "修改成功"; + return apiResult; + } + if (tb.tenant_guid != "" && tb.tenant_guid != null) + { + if (startMonth == endMonth) + { + sqlString = + $"UPDATE {TenantBilltable} " + + $"set tenant_name = (SELECT tenant_name from archive_electric_meter_tenant_list WHERE tenant_guid = '{tb.tenant_guid}'), start_timestamp = '{start_timestamp}',end_timestamp = '{end_timestamp}' , " + + $"result= " + + $"(select sum(sub_result) " + + $"from archive_electric_water_meter_day_{startMonth} " + + $"WHERE device_number = '{tb.device_number}' and start_timestamp BETWEEN '{start_timestamp}' and '{end_timestamp}' " + + $"GROUP BY device_number) , " + + $"bill = " + + $"ROUND(result *(SELECT {bill_per} from {TenantListtable} WHERE tenant_guid = '{tb.tenant_guid}') ), " + + $"updated_at = '{updated_at}', " + + $"tenant_guid = '{tb.tenant_guid}' " + + $"WHERE device_number = '{tb.device_number}'"; + } + else + { + string month = ""; + DateTime date1 = DateTime.Parse(start_timestamp); + DateTime date2 = DateTime.Parse(end_timestamp); + int monthsApart = ((date2.Year - date1.Year) * 12) + date2.Month - date1.Month; + for (var i = 1; i <= monthsApart; i++) + { + month += $@"UNION ALL + SELECT start_timestamp,device_number, sub_result + FROM archive_electric_water_meter_day_{date1.AddMonths(i).ToString("yyyyMM")} + WHERE device_number = '{tb.device_number}' "; + } + sqlString = + $@"UPDATE {TenantBilltable} + set tenant_name = (SELECT tenant_name from archive_electric_meter_tenant_list WHERE tenant_guid = '{tb.tenant_guid}'), start_timestamp = '{start_timestamp}',end_timestamp = '{end_timestamp}' , + result= + (SELECT sum(sub_result) + FROM ( + SELECT start_timestamp,device_number, sub_result + FROM archive_electric_water_meter_day_{startMonth} + WHERE device_number = '{tb.device_number}' "+ + $@"{month}" + + $@" ) combined_result + WHERE start_timestamp BETWEEN '{start_timestamp}' and '{end_timestamp}' + GROUP BY device_number) , + bill = + ROUND(result *(SELECT {bill_per} from {TenantListtable} WHERE tenant_guid = '{tb.tenant_guid}') ), + updated_at = '{updated_at}', + tenant_guid = '{tb.tenant_guid}' + WHERE device_number = '{tb.device_number}'"; + } + } + else + { + if (startMonth == endMonth) + { + sqlString = $"UPDATE {TenantBilltable} " + $"set tenant_name = (SELECT tenant_name from archive_electric_meter_tenant_list WHERE tenant_guid = '{tb.tenant_guid}'), start_timestamp = '{start_timestamp}',end_timestamp = '{end_timestamp}' , " + $"result= " + @@ -271,39 +328,44 @@ namespace FrontendWebApi.ApiControllers $"from archive_electric_water_meter_day_{startMonth} " + $"WHERE device_number = '{tb.device_number}' and start_timestamp BETWEEN '{start_timestamp}' and '{end_timestamp}' " + $"GROUP BY device_number) , " + - $"bill = " + - $"ROUND(result *(SELECT {bill_per} from {TenantListtable} WHERE tenant_guid = '{tb.tenant_guid}') ), " + + $"bill = 0 ," + $"updated_at = '{updated_at}', " + $"tenant_guid = '{tb.tenant_guid}' " + $"WHERE device_number = '{tb.device_number}'"; + } + else + { + string month = ""; + DateTime date1 = DateTime.Parse(start_timestamp); + DateTime date2 = DateTime.Parse(end_timestamp); + int monthsApart = ((date2.Year - date1.Year) * 12) + date2.Month - date1.Month; + for (var i = 1; i <= monthsApart; i++) + { + month += $@"UNION ALL + SELECT start_timestamp,device_number, sub_result + FROM archive_electric_water_meter_day_{date1.AddMonths(i).ToString("yyyyMM")} + WHERE device_number = '{tb.device_number}' "; + } + sqlString = + $@"UPDATE {TenantBilltable} + set tenant_name = (SELECT tenant_name from archive_electric_meter_tenant_list WHERE tenant_guid = '{tb.tenant_guid}'), start_timestamp = '{start_timestamp}',end_timestamp = '{end_timestamp}' , + result= + (SELECT sum(sub_result) + FROM ( + SELECT start_timestamp,device_number, sub_result + FROM archive_electric_water_meter_day_{startMonth} + WHERE device_number = '{tb.device_number}' " + + $@"{month}" + + $@" ) combined_result + WHERE start_timestamp BETWEEN '{start_timestamp}' and '{end_timestamp}' + GROUP BY device_number) , + bill = 0, + updated_at = '{updated_at}', + tenant_guid = '{tb.tenant_guid}' + WHERE device_number = '{tb.device_number}'"; + } } - else - { - //sqlString = - // $"UPDATE {TenantBilltable} " + - // $"set tenant_name = (SELECT tenant_name from archive_electric_meter_tenant_list WHERE tenant_guid = '{tb.tenant_guid}'), start_timestamp = '{start_timestamp}',end_timestamp = '{end_timestamp}' , " + - // $"result= " + - // $"(SELECT sum(sub_result) " + - // $"FROM ( " + - // $" SELECT start_timestamp,device_number, sub_result " + - // $" FROM archive_electric_water_meter_day_{startMonth} " + - // $" WHERE device_number = '{tb.device_number}' " + - // $" UNION ALL " + - // $" SELECT start_timestamp,device_number, sub_result " + - // $" FROM archive_electric_water_meter_day_{endMonth} " + - // $" WHERE device_number = '{tb.device_number}' " + - // $") combined_result " + - // $"WHERE start_timestamp BETWEEN '{start_timestamp}' and '{end_timestamp}' " + - // $"GROUP BY device_number) ," + - // $"bill = " + - // $"ROUND(result *(SELECT {bill_per} from {TenantListtable} WHERE tenant_guid = '{tb.tenant_guid}') ), " + - // $"updated_at = '{updated_at}', " + - // $"tenant_guid = '{tb.tenant_guid}' " + - // $"WHERE device_number = '{tb.device_number}'"; - apiResult.Code = "9999"; - apiResult.Msg = "請選擇同一個月份"; - return apiResult; - } + await backendRepository.ExecuteSql(sqlString); @@ -316,6 +378,11 @@ namespace FrontendWebApi.ApiControllers { apiResult.Code = "9999"; apiResult.Msg = "修改水電參考報表失敗。"; + if (exception.Message.Contains($"doesn't exist")) + { + apiResult.Code = "0001"; + apiResult.Msg = "選取的區間有部分無資料。"; + } Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } @@ -332,16 +399,15 @@ namespace FrontendWebApi.ApiControllers { string sqlString = $@"SELECT - a.tenant_name,a.start_timestamp,a.end_timestamp,bill_perKWH,bill_perRCV, - SUM(CASE WHEN device_name_tag = 'E4' THEN result ELSE 0 END) AS elec_result, - SUM(CASE WHEN device_name_tag = 'W1' THEN result ELSE 0 END) AS water_result, - SUM(CASE WHEN device_name_tag = 'E4' THEN bill ELSE 0 END) AS elec_bill, - SUM(CASE WHEN device_name_tag = 'W1' THEN bill ELSE 0 END) AS water_bill, - SUM(bill) AS total_bill - FROM archive_electric_meter_tenant_bill a - JOIN archive_electric_meter_tenant_list b on a.tenant_guid = b.tenant_guid - GROUP BY a.tenant_name - HAVING SUM(bill) != 0"; + a.tenant_name,min(a.start_timestamp)as start_timestamp,max(a.end_timestamp) as end_timestamp,bill_perKWH,bill_perRCV, + SUM(CASE WHEN device_name_tag = 'E4' THEN result ELSE 0 END) AS elec_result, + SUM(CASE WHEN device_name_tag = 'W1' THEN result ELSE 0 END) AS water_result, + SUM(CASE WHEN device_name_tag = 'E4' THEN bill ELSE 0 END) AS elec_bill, + SUM(CASE WHEN device_name_tag = 'W1' THEN bill ELSE 0 END) AS water_bill, + SUM(bill) AS total_bill + FROM archive_electric_meter_tenant_bill a + JOIN archive_electric_meter_tenant_list b on a.tenant_guid = b.tenant_guid + GROUP BY a.tenant_name;"; outputBill = await backendRepository.GetAllAsync(sqlString); string filePath = CreateOutputForm(outputBill); diff --git a/FrontendWebApi/appsettings.Development.json b/FrontendWebApi/appsettings.Development.json index d3bc4e5..cee86db 100644 --- a/FrontendWebApi/appsettings.Development.json +++ b/FrontendWebApi/appsettings.Development.json @@ -13,9 +13,9 @@ "JwtLifeSeconds": 3600 }, "FilePath": { - "OutputForm": "D:\\jay.chang\\dome\\FrontendWebApi\\wwwroot\\upload\\OutputForm\\", //水電報表 檔案儲存位置 - "OutputFormTemplate": "D:\\jay.chang\\dome\\FrontendWebApi\\wwwroot\\upload\\OutputFormTemplate\\import.html", // 水電報表範本檔位置 - "Image": "D:\\jay.chang\\dome\\FrontendWebApi\\wwwroot\\upload\\OutputFormTemplate\\dome.png" // 明細的圖片 + "OutputForm": "C:\\jay.chang\\ibms\\FrontendWebApi\\wwwroot\\upload\\OutputForm\\", //水電報表 檔案儲存位置 + "OutputFormTemplate": "C:\\jay.chang\\ibms\\FrontendWebApi\\wwwroot\\upload\\OutputFormTemplate\\import.html", // 水電報表範本檔位置 + "Image": "C:\\jay.chang\\ibms\\FrontendWebApi\\wwwroot\\img\\dome.png" // 明細的圖片 }, "DBConfig": { "MySqlDBConfig": {