This commit is contained in:
張家睿 2024-02-07 17:58:49 +08:00
commit f166793f04
2 changed files with 317 additions and 267 deletions

View File

@ -1,6 +1,7 @@
using Backend.Models; using Backend.Models;
using BackendWorkerService.Services.Implement; using BackendWorkerService.Services.Implement;
using Dapper; using Dapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
@ -345,160 +346,160 @@ namespace BackendWorkerService.Quartz.Jobs
row.TryGetValue("@start_timestamp", out var yyyymmData); row.TryGetValue("@start_timestamp", out var yyyymmData);
dbDateName = System.DateTime.Parse(yyyymmData.ToString()).ToString("yyyyMM"); dbDateName = System.DateTime.Parse(yyyymmData.ToString()).ToString("yyyyMM");
var sql = $@"CREATE TABLE IF NOT EXISTS `archive_electric_water_meter_day_{dbDateName}` ( 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, `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, `point` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`start_timestamp` datetime(6) NOT NULL, `start_timestamp` datetime(6) NOT NULL,
`end_timestamp` datetime(6) NULL DEFAULT NULL, `end_timestamp` datetime(6) NULL DEFAULT NULL,
`count_rawdata` int(11) NULL DEFAULT NULL, `count_rawdata` int(11) NULL DEFAULT NULL,
`min_rawdata` decimal(15, 3) NULL DEFAULT NULL, `min_rawdata` decimal(15, 3) NULL DEFAULT NULL,
`max_rawdata` decimal(15, 3) NULL DEFAULT NULL, `max_rawdata` decimal(15, 3) NULL DEFAULT NULL,
`sub_result` decimal(15, 3) NULL DEFAULT NULL, `sub_result` decimal(15, 3) NULL DEFAULT NULL,
`avg_rawdata` decimal(15, 3) NULL DEFAULT NULL, `avg_rawdata` decimal(15, 3) NULL DEFAULT NULL,
`sum_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:', `is_complete` tinyint(3) UNSIGNED NULL DEFAULT NULL COMMENT '0: 1:',
`repeat_times` int(11) NULL DEFAULT 0 COMMENT '', `repeat_times` int(11) NULL DEFAULT 0 COMMENT '',
`fail_reason` varchar(4000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '', `fail_reason` varchar(4000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime(6) NULL DEFAULT NULL, `updated_at` datetime(6) NULL DEFAULT NULL,
PRIMARY KEY (`device_number`, `point`, `start_timestamp`) USING BTREE PRIMARY KEY (`device_number`, `point`, `start_timestamp`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = DYNAMIC; ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = DYNAMIC;
SET FOREIGN_KEY_CHECKS = 1; SET FOREIGN_KEY_CHECKS = 1;
UPDATE archive_electric_water_meter_day_{dbDateName} SET UPDATE archive_electric_water_meter_day_{dbDateName} SET
count_rawdata = @count_rawdata, count_rawdata = @count_rawdata,
min_rawdata = @min_rawdata, min_rawdata = @min_rawdata,
max_rawdata = @max_rawdata, max_rawdata = @max_rawdata,
sub_result = @max_rawdata - @min_rawdata, sub_result = @max_rawdata - @min_rawdata,
avg_rawdata = @avg_rawdata, avg_rawdata = @avg_rawdata,
sum_rawdata = @sum_rawdata, sum_rawdata = @sum_rawdata,
is_complete = @is_complete, is_complete = @is_complete,
repeat_times = @repeat_times, repeat_times = @repeat_times,
fail_reason = @fail_reason, fail_reason = @fail_reason,
updated_at = @updated_at updated_at = @updated_at
WHERE device_number = @device_number WHERE device_number = @device_number
AND point = @point AND point = @point
AND start_timestamp = @start_timestamp; AND start_timestamp = @start_timestamp;
INSERT INTO archive_electric_water_meter_day_{dbDateName} ( INSERT INTO archive_electric_water_meter_day_{dbDateName} (
device_number, device_number,
point, point,
start_timestamp, start_timestamp,
end_timestamp, end_timestamp,
count_rawdata, count_rawdata,
min_rawdata, min_rawdata,
max_rawdata, max_rawdata,
sub_result, sub_result,
avg_rawdata, avg_rawdata,
sum_rawdata, sum_rawdata,
is_complete, is_complete,
repeat_times, repeat_times,
fail_reason) fail_reason)
SELECT SELECT
@device_number, @device_number,
@point, @point,
@start_timestamp, @start_timestamp,
@end_timestamp, @end_timestamp,
@count_rawdata, @count_rawdata,
@min_rawdata, @min_rawdata,
@max_rawdata, @max_rawdata,
@max_rawdata - @min_rawdata, @max_rawdata - @min_rawdata,
@avg_rawdata, @avg_rawdata,
@sum_rawdata, @sum_rawdata,
@is_complete, @is_complete,
@repeat_times, @repeat_times,
@fail_reason @fail_reason
WHERE ROW_COUNT() = 0; WHERE ROW_COUNT() = 0;
update device set archive_lastDate = @start_timestamp, archive_lastActionDate = @updated_at update device set archive_lastDate = @start_timestamp, archive_lastActionDate = @updated_at
where device_number = @device_number;"; //archive_lastDate 前次完成時間 archive_lastActionDate 本次作業時間 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 IF OBJECT_ID(N'dbo.archive_electric_water_meter_day_{dbDateName}', N'U') is null
BEGIN BEGIN
CREATE TABLE [dbo].[archive_electric_water_meter_day_{dbDateName}]( CREATE TABLE [dbo].[archive_electric_water_meter_day_{dbDateName}](
[device_number] [varchar](50) NOT NULL, [device_number] [varchar](50) NOT NULL,
[point] [varchar](20) NOT NULL, [point] [varchar](20) NOT NULL,
[start_timestamp] [datetime] NOT NULL, [start_timestamp] [datetime] NOT NULL,
[end_timestamp] [datetime] NULL, [end_timestamp] [datetime] NULL,
[count_rawdata] [int] NULL, [count_rawdata] [int] NULL,
[min_rawdata] [decimal](15, 3) NULL, [min_rawdata] [decimal](15, 3) NULL,
[max_rawdata] [decimal](15, 3) NULL, [max_rawdata] [decimal](15, 3) NULL,
[sub_result] [decimal](15, 3) NULL, [sub_result] [decimal](15, 3) NULL,
[avg_rawdata] [decimal](15, 3) NULL, [avg_rawdata] [decimal](15, 3) NULL,
[sum_rawdata] [decimal](15, 3) NULL, [sum_rawdata] [decimal](15, 3) NULL,
[is_complete] [tinyint] NULL, [is_complete] [tinyint] NULL,
[repeat_times] [int] NULL, [repeat_times] [int] NULL,
[fail_reason] [nvarchar](max) NULL, [fail_reason] [nvarchar](max) NULL,
[created_at] [datetime] NULL, [created_at] [datetime] NULL,
[updated_at] [datetime] NULL, [updated_at] [datetime] NULL,
CONSTRAINT [PK_archive_electric_water_meter_day_{dbDateName}] PRIMARY KEY CLUSTERED CONSTRAINT [PK_archive_electric_water_meter_day_{dbDateName}] PRIMARY KEY CLUSTERED
( (
[device_number] ASC, [device_number] ASC,
[point] ASC, [point] ASC,
[start_timestamp] 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] )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] ) 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' 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 END
UPDATE archive_electric_water_meter_day_{dbDateName} SET UPDATE archive_electric_water_meter_day_{dbDateName} SET
count_rawdata = @count_rawdata, count_rawdata = @count_rawdata,
min_rawdata = @min_rawdata, min_rawdata = @min_rawdata,
max_rawdata = @max_rawdata, max_rawdata = @max_rawdata,
sub_result = @max_rawdata - @min_rawdata, sub_result = @max_rawdata - @min_rawdata,
avg_rawdata = @avg_rawdata, avg_rawdata = @avg_rawdata,
sum_rawdata = @sum_rawdata, sum_rawdata = @sum_rawdata,
is_complete = @is_complete, is_complete = @is_complete,
repeat_times = @repeat_times, repeat_times = @repeat_times,
fail_reason = @fail_reason, fail_reason = @fail_reason,
updated_at = @updated_at updated_at = @updated_at
WHERE device_number = @device_number WHERE device_number = @device_number
AND point = @point AND point = @point
AND start_timestamp = @start_timestamp; AND start_timestamp = @start_timestamp;
IF @@ROWCOUNT = 0 IF @@ROWCOUNT = 0
BEGIN BEGIN
INSERT INTO archive_electric_water_meter_day_{dbDateName} ( INSERT INTO archive_electric_water_meter_day_{dbDateName} (
device_number, device_number,
point, point,
start_timestamp, start_timestamp,
end_timestamp, end_timestamp,
count_rawdata, count_rawdata,
min_rawdata, min_rawdata,
max_rawdata, max_rawdata,
sub_result, sub_result,
avg_rawdata, avg_rawdata,
sum_rawdata, sum_rawdata,
is_complete, is_complete,
repeat_times, repeat_times,
fail_reason) fail_reason)
VALUES ( VALUES (
@device_number, @device_number,
@point, @point,
@start_timestamp, @start_timestamp,
@end_timestamp, @end_timestamp,
@count_rawdata, @count_rawdata,
@min_rawdata, @min_rawdata,
@max_rawdata, @max_rawdata,
@max_rawdata - @min_rawdata, @max_rawdata - @min_rawdata,
@avg_rawdata, @avg_rawdata,
@sum_rawdata, @sum_rawdata,
@is_complete, @is_complete,
@repeat_times, @repeat_times,
@fail_reason) @fail_reason)
END END
COMMIT TRANSACTION;"; COMMIT TRANSACTION;";
await backgroundServiceRepository.ExecuteSql(sql, row); await backgroundServiceRepository.ExecuteSql(sql, row);
if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1") if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1")
{ {
@ -1725,15 +1726,15 @@ namespace BackendWorkerService.Quartz.Jobs
switch (name) switch (name)
{ {
case "min": 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); arrangeRawData.Add("@min_rawdata", min);
break; break;
case "max": 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); arrangeRawData.Add("@max_rawdata", max);
break; break;
case "avg": 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); arrangeRawData.Add("@avg_rawdata", avg);
break; break;
case "sum": case "sum":
@ -1793,15 +1794,15 @@ namespace BackendWorkerService.Quartz.Jobs
switch (name) switch (name)
{ {
case "min": 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); arrangeRawData.Add("@min_rawdata", min);
break; break;
case "max": 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); arrangeRawData.Add("@max_rawdata", max);
break; break;
case "avg": 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); arrangeRawData.Add("@avg_rawdata", avg);
break; break;
case "sum": case "sum":

View File

@ -20,6 +20,7 @@ using Serilog.Core;
using static FrontendWebApi.ApiControllers.TenantBillController; using static FrontendWebApi.ApiControllers.TenantBillController;
using System.Reflection; using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Data.SqlTypes;
@ -102,7 +103,7 @@ namespace FrontendWebApi.ApiControllers
await backendRepository.ExecuteSql(sqlString); await backendRepository.ExecuteSql(sqlString);
apiResult.Code = "0000"; apiResult.Code = "0000";
apiResult.Data = "新增成功"; apiResult.Msg = "新增成功";
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -137,7 +138,7 @@ namespace FrontendWebApi.ApiControllers
await backendRepository.ExecuteSql(sqlString); await backendRepository.ExecuteSql(sqlString);
apiResult.Code = "0000"; apiResult.Code = "0000";
apiResult.Data = "修改用戶成功"; apiResult.Msg = "修改用戶成功";
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -165,7 +166,7 @@ namespace FrontendWebApi.ApiControllers
await backendRepository.ExecuteSql(sqlString); await backendRepository.ExecuteSql(sqlString);
apiResult.Code = "0000"; apiResult.Code = "0000";
apiResult.Data = "刪除成功"; apiResult.Msg = "刪除成功";
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -209,7 +210,7 @@ namespace FrontendWebApi.ApiControllers
$"where device_building_tag = '{building_tag}' and a.device_name_tag = '{ElecOrWater}' "; $"where device_building_tag = '{building_tag}' and a.device_name_tag = '{ElecOrWater}' ";
} }
tenantBill = await backendRepository.GetAllAsync<TenantBill>(sqlString); tenantBill = await backendRepository.GetAllAsync<TenantBill>(sqlString);
@ -238,151 +239,195 @@ namespace FrontendWebApi.ApiControllers
var start_timestamp = tb.start_timestamp; var start_timestamp = tb.start_timestamp;
var end_timestamp = tb.end_timestamp; var end_timestamp = tb.end_timestamp;
string sqlString = null; string sqlString = null;
string startMonth = ""; string result = "0";
string endMonth = "";
if (start_timestamp != "" && end_timestamp != "") 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]; sqlString = $@"UPDATE {TenantBilltable}
endMonth = tb.end_timestamp.Split("-")[0] + tb.end_timestamp.Split("-")[1]; 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}' ,
else result= 0,
{ bill = 0,
sqlString = updated_at = '{updated_at}',
$@"UPDATE {TenantBilltable} tenant_guid = '{tb.tenant_guid}'
set tenant_name = (SELECT tenant_name from archive_electric_meter_tenant_list WHERE tenant_guid = '{tb.tenant_guid}'), WHERE device_number = '{tb.device_number}'";
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); await backendRepository.ExecuteSql(sqlString);
apiResult.Code = "0000"; apiResult.Code = "0000";
apiResult.Data = "修改成功"; apiResult.Msg = "資料填寫不完整";
return apiResult; 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 else
{ {
if (startMonth == endMonth) List<string> howManyMonth = new List<string>();
List<string> existMonth = new List<string>();
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<string>(checkTabelSql);
for (var i = 0; i <= monthsApart; i++)
{ {
sqlString = howManyMonth.Add($@"archive_electric_water_meter_day_{date1.AddMonths(i).ToString("yyyyMM")}");
$"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}' , " + foreach (var item in existTable)
$"result= " + {
$"(select sum(sub_result) " + foreach (var data in howManyMonth)
$"from archive_electric_water_meter_day_{startMonth} " + {
$"WHERE device_number = '{tb.device_number}' and start_timestamp BETWEEN '{start_timestamp}' and '{end_timestamp}' " + if (item == data)
$"GROUP BY device_number) , " + {
$"bill = 0 ," + existMonth.Add(data);
$"updated_at = '{updated_at}', " + }
$"tenant_guid = '{tb.tenant_guid}' " + }
$"WHERE device_number = '{tb.device_number}'"; }
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 else
{ {
string month = ""; string month = $@"
DateTime date1 = DateTime.Parse(start_timestamp); SELECT start_timestamp,device_number, sub_result
DateTime date2 = DateTime.Parse(end_timestamp); FROM {existMonth[0]}
int monthsApart = ((date2.Year - date1.Year) * 12) + date2.Month - date1.Month; WHERE device_number = '{tb.device_number}'";
for (var i = 1; i <= monthsApart; i++) for (var i = 1; i < existMonth.Count; i++)
{ {
month += $@"UNION ALL month += $@"UNION ALL
SELECT start_timestamp,device_number, sub_result 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}' "; 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<string>(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 = sqlString =
$@"UPDATE {TenantBilltable} $@"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}' , 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= result= {result},
(SELECT sum(sub_result) bill = ROUND(result *(SELECT {bill_per} from {TenantListtable} WHERE tenant_guid = '{tb.tenant_guid}') ),
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}', updated_at = '{updated_at}',
tenant_guid = '{tb.tenant_guid}' tenant_guid = '{tb.tenant_guid}'
WHERE device_number = '{tb.device_number}'"; WHERE device_number = '{tb.device_number}'";
} }
await backendRepository.ExecuteSql(sqlString);
} }
await backendRepository.ExecuteSql(sqlString);
apiResult.Code = "0000";
apiResult.Data = "修改成功";
} }
catch (Exception exception) catch (Exception exception)
{ {
apiResult.Code = "9999"; apiResult.Code = "9999";
apiResult.Msg = "修改水電參考報表失敗。"; 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<ApiResult<string>> CheckDay([FromBody] TenantBill tb)
{
ApiResult<string> apiResult = new ApiResult<string>();
if (tb.start_timestamp != "" && tb.end_timestamp != "" && tb.tenant_guid != "")
{
List<TenantBill> tenantBill = new List<TenantBill>();
try
{ {
apiResult.Code = "0001"; string sqlString = $@"select * from {TenantBilltable} WHERE tenant_guid= '{tb.tenant_guid}'";
apiResult.Msg = "選取的區間有部分無資料。";
tenantBill = await backendRepository.GetAllAsync<TenantBill>(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<ApiResult<string>> ChangeDay([FromBody] TenantBill tb)
{
ApiResult<string> apiResult = new ApiResult<string>();
List<TenantBill> tenantBill = new List<TenantBill>();
try
{
string sqlString = $@"select * from {TenantBilltable} WHERE tenant_guid= '{tb.tenant_guid}'";
tenantBill = await backendRepository.GetAllAsync<TenantBill>(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); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
} }
@ -399,14 +444,18 @@ namespace FrontendWebApi.ApiControllers
{ {
string sqlString = string sqlString =
$@"SELECT $@"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 = '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 = '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 = '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(CASE WHEN device_name_tag = 'W1' THEN bill ELSE 0 END) AS water_bill,
SUM(bill) AS total_bill SUM(bill) AS total_bill
FROM archive_electric_meter_tenant_bill a 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;"; GROUP BY a.tenant_name;";
outputBill = await backendRepository.GetAllAsync<OutputBill>(sqlString); outputBill = await backendRepository.GetAllAsync<OutputBill>(sqlString);
@ -550,12 +599,12 @@ namespace FrontendWebApi.ApiControllers
$" </div> " + $" </div> " +
$" </div> " + $" </div> " +
$" </div>"; $" </div>";
} }
htmlStr = htmlStr.Replace("{{bill}}", bill); htmlStr = htmlStr.Replace("{{bill}}", bill);
return htmlStr; return htmlStr;
} }