diff --git a/BackendWorkerService/Quartz/Jobs/ArchiveElectricMeterDayJob.cs b/BackendWorkerService/Quartz/Jobs/ArchiveElectricMeterDayJob.cs index 39c05fc..619d5c3 100644 --- a/BackendWorkerService/Quartz/Jobs/ArchiveElectricMeterDayJob.cs +++ b/BackendWorkerService/Quartz/Jobs/ArchiveElectricMeterDayJob.cs @@ -1,6 +1,7 @@ using Backend.Models; using BackendWorkerService.Services.Implement; using Dapper; +using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -345,160 +346,160 @@ namespace BackendWorkerService.Quartz.Jobs 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, - `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; + `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_day_{dbDateName} SET - count_rawdata = @count_rawdata, - min_rawdata = @min_rawdata, - max_rawdata = @max_rawdata, - sub_result = @max_rawdata - @min_rawdata, - avg_rawdata = @avg_rawdata, - sum_rawdata = @sum_rawdata, - is_complete = @is_complete, - repeat_times = @repeat_times, - fail_reason = @fail_reason, - updated_at = @updated_at - WHERE device_number = @device_number - AND point = @point - AND start_timestamp = @start_timestamp; + SET FOREIGN_KEY_CHECKS = 1; + UPDATE archive_electric_water_meter_day_{dbDateName} SET + count_rawdata = @count_rawdata, + min_rawdata = @min_rawdata, + max_rawdata = @max_rawdata, + sub_result = @max_rawdata - @min_rawdata, + avg_rawdata = @avg_rawdata, + sum_rawdata = @sum_rawdata, + is_complete = @is_complete, + repeat_times = @repeat_times, + fail_reason = @fail_reason, + updated_at = @updated_at + WHERE device_number = @device_number + AND point = @point + AND start_timestamp = @start_timestamp; - INSERT INTO archive_electric_water_meter_day_{dbDateName} ( - device_number, - point, - start_timestamp, - end_timestamp, - count_rawdata, - min_rawdata, - max_rawdata, - sub_result, - avg_rawdata, - sum_rawdata, - is_complete, - repeat_times, - fail_reason) - SELECT - @device_number, - @point, - @start_timestamp, - @end_timestamp, - @count_rawdata, - @min_rawdata, - @max_rawdata, - @max_rawdata - @min_rawdata, - @avg_rawdata, - @sum_rawdata, - @is_complete, - @repeat_times, - @fail_reason - WHERE ROW_COUNT() = 0; - update device set archive_lastDate = @start_timestamp, archive_lastActionDate = @updated_at - where device_number = @device_number;"; //archive_lastDate 前次完成時間 ,archive_lastActionDate 本次作業時間 + INSERT INTO archive_electric_water_meter_day_{dbDateName} ( + device_number, + point, + start_timestamp, + end_timestamp, + count_rawdata, + min_rawdata, + max_rawdata, + sub_result, + avg_rawdata, + sum_rawdata, + is_complete, + repeat_times, + fail_reason) + SELECT + @device_number, + @point, + @start_timestamp, + @end_timestamp, + @count_rawdata, + @min_rawdata, + @max_rawdata, + @max_rawdata - @min_rawdata, + @avg_rawdata, + @sum_rawdata, + @is_complete, + @repeat_times, + @fail_reason + WHERE ROW_COUNT() = 0; + update device set archive_lastDate = @start_timestamp, archive_lastActionDate = @updated_at + where device_number = @device_number;"; //archive_lastDate 前次完成時間 ,archive_lastActionDate 本次作業時間 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}]( - [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_day_{dbDateName}] 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] + 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}]( + [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_day_{dbDateName}] 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_day_{dbDateName}] ADD CONSTRAINT [DF_archive_electric_water_meter_day_{dbDateName}_repeat_times] DEFAULT ((0)) FOR [repeat_times] + ALTER TABLE [dbo].[archive_electric_water_meter_day_{dbDateName}] ADD CONSTRAINT [DF_archive_electric_water_meter_day_{dbDateName}_repeat_times] DEFAULT ((0)) FOR [repeat_times] - ALTER TABLE [dbo].[archive_electric_water_meter_day_{dbDateName}] ADD CONSTRAINT [DF_archive_electric_water_meter_day_{dbDateName}_created_at] DEFAULT (getdate()) FOR [created_at] + ALTER TABLE [dbo].[archive_electric_water_meter_day_{dbDateName}] ADD CONSTRAINT [DF_archive_electric_water_meter_day_{dbDateName}_created_at] DEFAULT (getdate()) FOR [created_at] - ALTER TABLE [dbo].[archive_electric_water_meter_day_{dbDateName}] ADD CONSTRAINT [DF_archive_electric_water_meter_day_{dbDateName}_updated_at] DEFAULT (NULL) FOR [updated_at] + ALTER TABLE [dbo].[archive_electric_water_meter_day_{dbDateName}] ADD CONSTRAINT [DF_archive_electric_water_meter_day_{dbDateName}_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_day_{dbDateName}', @level2type=N'COLUMN',@level2name=N'is_complete' + 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_day_{dbDateName}', @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_day_{dbDateName}', @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_day_{dbDateName}', @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_day_{dbDateName}', @level2type=N'COLUMN',@level2name=N'fail_reason' - END + 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_day_{dbDateName}', @level2type=N'COLUMN',@level2name=N'fail_reason' + END - UPDATE archive_electric_water_meter_day_{dbDateName} SET - count_rawdata = @count_rawdata, - min_rawdata = @min_rawdata, - max_rawdata = @max_rawdata, - sub_result = @max_rawdata - @min_rawdata, - avg_rawdata = @avg_rawdata, - sum_rawdata = @sum_rawdata, - is_complete = @is_complete, - repeat_times = @repeat_times, - fail_reason = @fail_reason, - updated_at = @updated_at - WHERE device_number = @device_number - AND point = @point - AND start_timestamp = @start_timestamp; + UPDATE archive_electric_water_meter_day_{dbDateName} SET + count_rawdata = @count_rawdata, + min_rawdata = @min_rawdata, + max_rawdata = @max_rawdata, + sub_result = @max_rawdata - @min_rawdata, + avg_rawdata = @avg_rawdata, + sum_rawdata = @sum_rawdata, + is_complete = @is_complete, + repeat_times = @repeat_times, + fail_reason = @fail_reason, + updated_at = @updated_at + WHERE device_number = @device_number + AND point = @point + AND start_timestamp = @start_timestamp; - IF @@ROWCOUNT = 0 - BEGIN - INSERT INTO archive_electric_water_meter_day_{dbDateName} ( - device_number, - point, - start_timestamp, - end_timestamp, - count_rawdata, - min_rawdata, - max_rawdata, - sub_result, - avg_rawdata, - sum_rawdata, - is_complete, - repeat_times, - fail_reason) - VALUES ( - @device_number, - @point, - @start_timestamp, - @end_timestamp, - @count_rawdata, - @min_rawdata, - @max_rawdata, - @max_rawdata - @min_rawdata, - @avg_rawdata, - @sum_rawdata, - @is_complete, - @repeat_times, - @fail_reason) - END + IF @@ROWCOUNT = 0 + BEGIN + INSERT INTO archive_electric_water_meter_day_{dbDateName} ( + device_number, + point, + start_timestamp, + end_timestamp, + count_rawdata, + min_rawdata, + max_rawdata, + sub_result, + avg_rawdata, + sum_rawdata, + is_complete, + repeat_times, + fail_reason) + VALUES ( + @device_number, + @point, + @start_timestamp, + @end_timestamp, + @count_rawdata, + @min_rawdata, + @max_rawdata, + @max_rawdata - @min_rawdata, + @avg_rawdata, + @sum_rawdata, + @is_complete, + @repeat_times, + @fail_reason) + END - COMMIT TRANSACTION;"; + COMMIT TRANSACTION;"; await backgroundServiceRepository.ExecuteSql(sql, row); if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1") { @@ -1725,15 +1726,15 @@ namespace BackendWorkerService.Quartz.Jobs switch (name) { case "min": - var min = Convert.ToDecimal(real["@val"].ToString()); + var min = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float); arrangeRawData.Add("@min_rawdata", min); break; case "max": - var max = Convert.ToDecimal(real["@val"].ToString()); + var max = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float); arrangeRawData.Add("@max_rawdata", max); break; case "avg": - var avg = Convert.ToDecimal(real["@val"].ToString()); + var avg = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float); arrangeRawData.Add("@avg_rawdata", avg); break; case "sum": @@ -1793,15 +1794,15 @@ namespace BackendWorkerService.Quartz.Jobs switch (name) { case "min": - var min = Convert.ToDecimal(real["@val"].ToString()); + var min = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float); arrangeRawData.Add("@min_rawdata", min); break; case "max": - var max = Convert.ToDecimal(real["@val"].ToString()); + var max = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float); arrangeRawData.Add("@max_rawdata", max); break; case "avg": - var avg = Convert.ToDecimal(real["@val"].ToString()); + var avg = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float); arrangeRawData.Add("@avg_rawdata", avg); break; case "sum": diff --git a/FrontendWebApi/ApiControllers/TenantBillController.cs b/FrontendWebApi/ApiControllers/TenantBillController.cs index 0ced42d..ea83a74 100644 --- a/FrontendWebApi/ApiControllers/TenantBillController.cs +++ b/FrontendWebApi/ApiControllers/TenantBillController.cs @@ -20,6 +20,7 @@ using Serilog.Core; using static FrontendWebApi.ApiControllers.TenantBillController; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Syntax; +using System.Data.SqlTypes; @@ -102,7 +103,7 @@ namespace FrontendWebApi.ApiControllers await backendRepository.ExecuteSql(sqlString); apiResult.Code = "0000"; - apiResult.Data = "新增成功"; + apiResult.Msg = "新增成功"; } catch (Exception exception) { @@ -137,7 +138,7 @@ namespace FrontendWebApi.ApiControllers await backendRepository.ExecuteSql(sqlString); apiResult.Code = "0000"; - apiResult.Data = "修改用戶成功"; + apiResult.Msg = "修改用戶成功"; } catch (Exception exception) { @@ -165,7 +166,7 @@ namespace FrontendWebApi.ApiControllers await backendRepository.ExecuteSql(sqlString); apiResult.Code = "0000"; - apiResult.Data = "刪除成功"; + apiResult.Msg = "刪除成功"; } catch (Exception exception) { @@ -209,7 +210,7 @@ namespace FrontendWebApi.ApiControllers $"where device_building_tag = '{building_tag}' and a.device_name_tag = '{ElecOrWater}' "; } - + tenantBill = await backendRepository.GetAllAsync(sqlString); @@ -238,151 +239,195 @@ namespace FrontendWebApi.ApiControllers var start_timestamp = tb.start_timestamp; var end_timestamp = tb.end_timestamp; string sqlString = null; - string startMonth = ""; - string endMonth = ""; - if (start_timestamp != "" && end_timestamp != "") + string result = "0"; + + if (tb.start_timestamp == "" || tb.end_timestamp == "" || tb.tenant_guid == "" || tb.tenant_guid == null) { - startMonth = tb.start_timestamp.Split("-")[0] + tb.start_timestamp.Split("-")[1]; - endMonth = tb.end_timestamp.Split("-")[0] + tb.end_timestamp.Split("-")[1]; - } - 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}'"; + 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= 0, + bill = 0, + updated_at = '{updated_at}', + tenant_guid = '{tb.tenant_guid}' + WHERE device_number = '{tb.device_number}'"; await backendRepository.ExecuteSql(sqlString); - apiResult.Code = "0000"; - apiResult.Data = "修改成功"; + apiResult.Msg = "資料填寫不完整"; 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) + List howManyMonth = new List(); + List existMonth = new List(); + DateTime date1 = DateTime.Parse(start_timestamp); + DateTime date2 = DateTime.Parse(end_timestamp); + int monthsApart = ((date2.Year - date1.Year) * 12) + date2.Month - date1.Month; + + // 找出資料庫存在的水電月份表 + string checkTabelSql = $@"SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'ibms_dome_dome' and TABLE_NAME like 'archive_electric_water_meter_day_%'"; + var existTable = await backendRepository.GetAllAsync(checkTabelSql); + + for (var i = 0; i <= monthsApart; i++) { - 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 = 0 ," + - $"updated_at = '{updated_at}', " + - $"tenant_guid = '{tb.tenant_guid}' " + - $"WHERE device_number = '{tb.device_number}'"; + howManyMonth.Add($@"archive_electric_water_meter_day_{date1.AddMonths(i).ToString("yyyyMM")}"); + } + foreach (var item in existTable) + { + foreach (var data in howManyMonth) + { + if (item == data) + { + existMonth.Add(data); + } + } + } + if (existMonth.Count == 0) + { + 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= 0, + 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++) + string month = $@" + SELECT start_timestamp,device_number, sub_result + FROM {existMonth[0]} + WHERE device_number = '{tb.device_number}'"; + for (var i = 1; i < existMonth.Count; i++) { month += $@"UNION ALL SELECT start_timestamp,device_number, sub_result - FROM archive_electric_water_meter_day_{date1.AddMonths(i).ToString("yyyyMM")} + FROM {existMonth[i]} WHERE device_number = '{tb.device_number}' "; } + + string checkDataSql = $@"(SELECT sum(sub_result) + FROM ( {month} + ) combined_result + WHERE start_timestamp BETWEEN '{start_timestamp}' and '{end_timestamp}' + GROUP BY device_number) "; + var existData = await backendRepository.GetAllAsync(checkDataSql); + if (existData.Count != 0) + { + result = $@"(SELECT sum(sub_result) + FROM ( {month} + ) combined_result + WHERE start_timestamp BETWEEN '{start_timestamp}' and '{end_timestamp}' + GROUP BY 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, + result= {result}, + 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}'"; } + + await backendRepository.ExecuteSql(sqlString); + } - - - - await backendRepository.ExecuteSql(sqlString); - - - apiResult.Code = "0000"; - apiResult.Data = "修改成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = "修改水電參考報表失敗。"; - if (exception.Message.Contains($"doesn't exist")) + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + return apiResult; + + } + apiResult = await CheckDay(tb); + return apiResult; + } + [HttpPost] + public async Task> CheckDay([FromBody] TenantBill tb) + { + ApiResult apiResult = new ApiResult(); + if (tb.start_timestamp != "" && tb.end_timestamp != "" && tb.tenant_guid != "") + { + List tenantBill = new List(); + try { - apiResult.Code = "0001"; - apiResult.Msg = "選取的區間有部分無資料。"; + string sqlString = $@"select * from {TenantBilltable} WHERE tenant_guid= '{tb.tenant_guid}'"; + + tenantBill = await backendRepository.GetAllAsync(sqlString); + if (tenantBill.Count > 1) + { + foreach (TenantBill t in tenantBill) + { + if (t.start_timestamp == tb.start_timestamp && t.end_timestamp == tb.end_timestamp) + { + continue; + } + else + { + apiResult.Code = "0001"; + apiResult.Msg = "該用戶設備的起訖日期不一致,是否將所有設備起訖日期調為一致?"; + return apiResult; + + } + } + + apiResult.Code = "0000"; + apiResult.Msg = "修改成功且該用戶的所有設備日期一致"; + } } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "確認日期失敗。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } + + } + apiResult.Code = "0000"; + apiResult.Msg = "修改成功且不執行CheckDay"; + return apiResult; + } + [HttpPost] + public async Task> ChangeDay([FromBody] TenantBill tb) + { + ApiResult apiResult = new ApiResult(); + List tenantBill = new List(); + + try + { + string sqlString = $@"select * from {TenantBilltable} WHERE tenant_guid= '{tb.tenant_guid}'"; + + tenantBill = await backendRepository.GetAllAsync(sqlString); + foreach (TenantBill t in tenantBill) + { + if (t.start_timestamp == tb.start_timestamp && t.end_timestamp == tb.end_timestamp) + { + continue; + } + else + { + t.start_timestamp = tb.start_timestamp; + t.end_timestamp = tb.end_timestamp; + await UpdateTenantBill(t); + } + } + + + apiResult.Code = "0000"; + apiResult.Msg = "修改成功"; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "更換日期失敗。"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } @@ -399,14 +444,18 @@ namespace FrontendWebApi.ApiControllers { string sqlString = $@"SELECT - a.tenant_name,min(a.start_timestamp)as start_timestamp,max(a.end_timestamp) as end_timestamp,bill_perKWH,bill_perRCV, + a.tenant_name, + MIN(NULLIF(a.start_timestamp, '')) AS start_timestamp, + MAX(NULLIF(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 + JOIN archive_electric_meter_tenant_list b ON a.tenant_guid = b.tenant_guid GROUP BY a.tenant_name;"; outputBill = await backendRepository.GetAllAsync(sqlString); @@ -550,12 +599,12 @@ namespace FrontendWebApi.ApiControllers $" " + $" " + $" "; - + } htmlStr = htmlStr.Replace("{{bill}}", bill); - + return htmlStr; }