This commit is contained in:
張家睿 2024-02-06 07:35:04 +08:00
commit e6c134b47c
5 changed files with 313 additions and 100 deletions

View File

@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Haukcode.WkHtmlToPdfDotNet" Version="1.5.86" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.19" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.19" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.1.19" /> <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.1.19" />
<PackageReference Include="ncrontab" Version="3.3.1" /> <PackageReference Include="ncrontab" Version="3.3.1" />

View File

@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using Quartz; using Quartz;
using Repository.BackendRepository.Interface; using Repository.BackendRepository.Interface;
using Repository.Helper; using Repository.Helper;
@ -140,9 +141,10 @@ namespace BackendWorkerService.Quartz.Jobs
{ {
try try
{ {
await task_Detail.InsertWorkTime("ArchiveElectricMeterDayJob", "Day", "水電表天任務開始"); await task_Detail.InsertWorkTime("ArchiveElectricMeterDayJob", "Day", "水電表天任務開始");
//var preDay = now.AddDays(-1); //取得前一天 var preDay = now.AddDays(-1); //取得前一天
//var dbDateName = preDay.Year.ToString().PadLeft(4, '0') + preDay.Month.ToString().PadLeft(2, '0'); 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 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")); //var endTimestamp = string.Format("{0}T23:59:59.000+08:00", preDay.ToString("yyyy-MM-dd"));
@ -153,17 +155,11 @@ namespace BackendWorkerService.Quartz.Jobs
// <reltime name='interval' val = 'PT1D' /> // <reltime name='interval' val = 'PT1D' />
// </obj>"; // </obj>";
#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 stopWatch = new Stopwatch();
//stopWatch.Start(); //stopWatch.Start();
#region
//抓取每個設備的資料 //抓取每個設備的資料
List<Dictionary<string, object>> electericArchiveDayRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> electericArchiveDayRawDatas = new List<Dictionary<string, object>>();
List<Dictionary<string, object>> waterArchiveDayRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> waterArchiveDayRawDatas = new List<Dictionary<string, object>>();
@ -173,7 +169,9 @@ namespace BackendWorkerService.Quartz.Jobs
var endDay = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); var endDay = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
foreach (DateTime day in EachDay(startDay, endDay)) 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")); 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) foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{ {
var startDay = deviceNumberPoint.archive_lastDate.ToString("yyyy-MM-dd"); 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)) 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")); 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(); //stopWatch.Stop();
//logger.LogInformation("【ArchiveElectricMeterDayJob】【天歸檔】【效能檢驗】[取得資料花費時間]{0} 毫秒", stopWatch.ElapsedMilliseconds); //logger.LogInformation("【ArchiveElectricMeterDayJob】【天歸檔】【效能檢驗】[取得資料花費時間]{0} 毫秒", stopWatch.ElapsedMilliseconds);
if (electericArchiveDayRawDatas.Count() > 0) 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, `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,
@ -407,7 +411,7 @@ namespace BackendWorkerService.Quartz.Jobs
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}](
@ -495,15 +499,20 @@ namespace BackendWorkerService.Quartz.Jobs
END END
COMMIT TRANSACTION;"; COMMIT TRANSACTION;";
await backgroundServiceRepository.ExecuteSql(sql, electericArchiveDayRawDatas); await backgroundServiceRepository.ExecuteSql(sql, row);
if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1") if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1")
{ {
await backgroundServiceMsSqlRepository.ExecuteSql(mySql, electericArchiveDayRawDatas); await backgroundServiceMsSqlRepository.ExecuteSql(mySql, row);
}
} }
} }
if (waterArchiveDayRawDatas.Count() > 0) 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}` ( 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,
@ -571,7 +580,7 @@ namespace BackendWorkerService.Quartz.Jobs
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}](
@ -659,13 +668,14 @@ namespace BackendWorkerService.Quartz.Jobs
END END
COMMIT TRANSACTION;"; COMMIT TRANSACTION;";
await backgroundServiceRepository.ExecuteSql(sql, waterArchiveDayRawDatas); await backgroundServiceRepository.ExecuteSql(sql, row);
if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1") if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1")
{ {
await backgroundServiceMsSqlRepository.ExecuteSql(mySql, waterArchiveDayRawDatas); await backgroundServiceMsSqlRepository.ExecuteSql(mySql, row);
}
} }
} }
await task_Detail.InsertWorkTime_End("ArchiveElectricMeterDayJob", "Day", "任務完成"); await task_Detail.InsertWorkTime_End("ArchiveElectricMeterDayJob", "Day", "水電表天任務完成");
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -1090,14 +1100,18 @@ namespace BackendWorkerService.Quartz.Jobs
try try
{ {
await task_Detail.InsertWorkTime("ArchiveElectricMeterDayJob", "Month", "水電表月任務開始"); await task_Detail.InsertWorkTime("ArchiveElectricMeterDayJob", "Month", "水電表月任務開始");
var FirstDay = now.AddDays(-now.Day + 1); var preDay = now.AddDays(-1); //取得前一天
//var LastDay = now.AddMonths(1).AddDays(-now.AddMonths(1).Day);
var LastDay = FirstDay.AddMonths(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}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 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}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 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 = $@"<obj is='obix: HistoryFilter'> var historyQueryFilter = $@"<obj is='obix: HistoryFilter'>
<abstime name='start' val='{startTimestamp}' /> <abstime name='start' val='{startTimestamp}' />
<abstime name='end' val='{endTimestamp}' /> <abstime name='end' val='{endTimestamp}' />
<reltime name='interval' val = 'PT{dayInMonth}D' /> <reltime name='interval' val = 'PT{dayInMonth+1}D' />
</obj>"; </obj>";
//Stopwatch stopWatch = new Stopwatch(); //Stopwatch stopWatch = new Stopwatch();
@ -1258,7 +1272,29 @@ namespace BackendWorkerService.Quartz.Jobs
if (electricArchiveMonthRawDatas.Count() > 0) if (electricArchiveMonthRawDatas.Count() > 0)
{ {
var sql = $@" 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 UPDATE archive_electric_water_meter_month SET
start_timestamp = @start_timestamp,
end_timestamp = @end_timestamp,
count_rawdata = @count_rawdata, count_rawdata = @count_rawdata,
min_rawdata = @min_rawdata, min_rawdata = @min_rawdata,
max_rawdata = @max_rawdata, max_rawdata = @max_rawdata,
@ -1304,8 +1340,48 @@ namespace BackendWorkerService.Quartz.Jobs
WHERE ROW_COUNT() = 0;"; WHERE ROW_COUNT() = 0;";
var mySql = $@"BEGIN TRANSACTION; 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 UPDATE archive_electric_water_meter_month SET
start_timestamp = @start_timestamp,
end_timestamp = @end_timestamp,
count_rawdata = @count_rawdata, count_rawdata = @count_rawdata,
min_rawdata = @min_rawdata, min_rawdata = @min_rawdata,
max_rawdata = @max_rawdata, max_rawdata = @max_rawdata,
@ -1362,7 +1438,29 @@ namespace BackendWorkerService.Quartz.Jobs
if (waterArchiveMonthRawDatas.Count() > 0) if (waterArchiveMonthRawDatas.Count() > 0)
{ {
var sql = $@" 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 UPDATE archive_electric_water_meter_month SET
start_timestamp = @start_timestamp,
end_timestamp = @end_timestamp,
count_rawdata = @count_rawdata, count_rawdata = @count_rawdata,
min_rawdata = @min_rawdata, min_rawdata = @min_rawdata,
max_rawdata = @max_rawdata, max_rawdata = @max_rawdata,
@ -1408,8 +1506,48 @@ namespace BackendWorkerService.Quartz.Jobs
WHERE ROW_COUNT() = 0;"; WHERE ROW_COUNT() = 0;";
var mySql = $@"BEGIN TRANSACTION; 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 UPDATE archive_electric_water_meter_month SET
start_timestamp = @start_timestamp,
end_timestamp = @end_timestamp,
count_rawdata = @count_rawdata, count_rawdata = @count_rawdata,
min_rawdata = @min_rawdata, min_rawdata = @min_rawdata,
max_rawdata = @max_rawdata, max_rawdata = @max_rawdata,
@ -1463,7 +1601,7 @@ namespace BackendWorkerService.Quartz.Jobs
await backgroundServiceMsSqlRepository.ExecuteSql(mySql, waterArchiveMonthRawDatas); await backgroundServiceMsSqlRepository.ExecuteSql(mySql, waterArchiveMonthRawDatas);
} }
} }
await task_Detail.InsertWorkTime_End("ArchiveElectricMeterDayJob", "Month", "任務完成"); await task_Detail.InsertWorkTime_End("ArchiveElectricMeterDayJob", "Month", "水電表月任務完成");
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -1520,6 +1658,14 @@ namespace BackendWorkerService.Quartz.Jobs
for (var day = strtday.Date; day.Date <= endday.Date; day = day.AddDays(1)) for (var day = strtday.Date; day.Date <= endday.Date; day = day.AddDays(1))
yield return day; yield return day;
} }
public IEnumerable<DateTime> 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<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult) private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult)
{ {
List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>();

View File

@ -19,7 +19,7 @@
}, },
"DBConfig": { "DBConfig": {
"MySqlDBConfig": { "MySqlDBConfig": {
"Server": "CYGthbCeGtAXT4s1NOSJHQ==", //0.202 "Server": "CYGthbCeGtAXT4s1NOSJHQ==", //0.132
"Port": "mkF51jVbg40V5K5eTh2Ckw==", //3306 "Port": "mkF51jVbg40V5K5eTh2Ckw==", //3306
//"Database": "VJB2XC+lAtzuHObDGMVOAA==", //30 //"Database": "VJB2XC+lAtzuHObDGMVOAA==", //30
//"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp //"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp

View File

@ -19,6 +19,7 @@ using Microsoft.Extensions.Configuration;
using Serilog.Core; using Serilog.Core;
using static FrontendWebApi.ApiControllers.TenantBillController; using static FrontendWebApi.ApiControllers.TenantBillController;
using System.Reflection; using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@ -109,7 +110,8 @@ namespace FrontendWebApi.ApiControllers
apiResult.Msg = "新增用戶失敗。"; apiResult.Msg = "新增用戶失敗。";
if (exception.Message.Contains($" for key 'PRIMARY'")) if (exception.Message.Contains($" for key 'PRIMARY'"))
{ {
apiResult.Msg = "已有相同使用者。"; apiResult.Code = "0001";
apiResult.Msg = "已有相同用戶。";
} }
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
} }
@ -143,6 +145,7 @@ namespace FrontendWebApi.ApiControllers
apiResult.Msg = "修改失敗。"; apiResult.Msg = "修改失敗。";
if (exception.Message.Contains($"a foreign key constraint")) if (exception.Message.Contains($"a foreign key constraint"))
{ {
apiResult.Code = "0001";
apiResult.Msg = "水電報表仍有該用戶,無法修改名稱。"; apiResult.Msg = "水電報表仍有該用戶,無法修改名稱。";
} }
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
@ -170,6 +173,7 @@ namespace FrontendWebApi.ApiControllers
apiResult.Msg = "刪除用戶失敗。"; apiResult.Msg = "刪除用戶失敗。";
if (exception.Message.Contains($"a foreign key constraint")) if (exception.Message.Contains($"a foreign key constraint"))
{ {
apiResult.Code = "0001";
apiResult.Msg = "水電報表仍有該用戶,無法刪除。"; apiResult.Msg = "水電報表仍有該用戶,無法刪除。";
} }
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
@ -190,14 +194,7 @@ namespace FrontendWebApi.ApiControllers
string building_tag = tb.building_tag; string building_tag = tb.building_tag;
string ElecOrWater = tableType == "elec" ? "E4" : "W1"; string ElecOrWater = tableType == "elec" ? "E4" : "W1";
string sqlString = null; string sqlString = null;
if (building_tag == "ALL") if (building_tag == "D2")
{
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")
{ {
sqlString = sqlString =
$"SELECT bill_id,a.device_number,a.full_name,start_timestamp,end_timestamp,result,bill,tenant_name,tenant_guid " + $"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]; startMonth = tb.start_timestamp.Split("-")[0] + tb.start_timestamp.Split("-")[1];
endMonth = tb.end_timestamp.Split("-")[0] + tb.end_timestamp.Split("-")[1]; endMonth = tb.end_timestamp.Split("-")[0] + tb.end_timestamp.Split("-")[1];
} }
if (start_timestamp == "") else
{
apiResult.Code = "9999";
apiResult.Msg = "請選擇起始日期。";
return apiResult;
}
if (end_timestamp == "")
{
apiResult.Code = "9999";
apiResult.Msg = "請選擇結束日期。";
return apiResult;
}
if (startMonth == endMonth)
{ {
sqlString = 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} " + $"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= " +
@ -271,39 +328,44 @@ namespace FrontendWebApi.ApiControllers
$"from archive_electric_water_meter_day_{startMonth} " + $"from archive_electric_water_meter_day_{startMonth} " +
$"WHERE device_number = '{tb.device_number}' and start_timestamp BETWEEN '{start_timestamp}' and '{end_timestamp}' " + $"WHERE device_number = '{tb.device_number}' and start_timestamp BETWEEN '{start_timestamp}' and '{end_timestamp}' " +
$"GROUP BY device_number) , " + $"GROUP BY device_number) , " +
$"bill = " + $"bill = 0 ," +
$"ROUND(result *(SELECT {bill_per} from {TenantListtable} WHERE tenant_guid = '{tb.tenant_guid}') ), " +
$"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}'";
}
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); await backendRepository.ExecuteSql(sqlString);
@ -316,6 +378,11 @@ namespace FrontendWebApi.ApiControllers
{ {
apiResult.Code = "9999"; apiResult.Code = "9999";
apiResult.Msg = "修改水電參考報表失敗。"; apiResult.Msg = "修改水電參考報表失敗。";
if (exception.Message.Contains($"doesn't exist"))
{
apiResult.Code = "0001";
apiResult.Msg = "選取的區間有部分無資料。";
}
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
} }
@ -332,16 +399,15 @@ namespace FrontendWebApi.ApiControllers
{ {
string sqlString = string sqlString =
$@"SELECT $@"SELECT
a.tenant_name,a.start_timestamp,a.end_timestamp,bill_perKWH,bill_perRCV, 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 = '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;";
HAVING SUM(bill) != 0";
outputBill = await backendRepository.GetAllAsync<OutputBill>(sqlString); outputBill = await backendRepository.GetAllAsync<OutputBill>(sqlString);
string filePath = CreateOutputForm(outputBill); string filePath = CreateOutputForm(outputBill);

View File

@ -13,9 +13,9 @@
"JwtLifeSeconds": 3600 "JwtLifeSeconds": 3600
}, },
"FilePath": { "FilePath": {
"OutputForm": "D:\\jay.chang\\dome\\FrontendWebApi\\wwwroot\\upload\\OutputForm\\", // "OutputForm": "C:\\jay.chang\\ibms\\FrontendWebApi\\wwwroot\\upload\\OutputForm\\", //
"OutputFormTemplate": "D:\\jay.chang\\dome\\FrontendWebApi\\wwwroot\\upload\\OutputFormTemplate\\import.html", // "OutputFormTemplate": "C:\\jay.chang\\ibms\\FrontendWebApi\\wwwroot\\upload\\OutputFormTemplate\\import.html", //
"Image": "D:\\jay.chang\\dome\\FrontendWebApi\\wwwroot\\upload\\OutputFormTemplate\\dome.png" // "Image": "C:\\jay.chang\\ibms\\FrontendWebApi\\wwwroot\\img\\dome.png" //
}, },
"DBConfig": { "DBConfig": {
"MySqlDBConfig": { "MySqlDBConfig": {