This commit is contained in:
jiahao 2023-07-31 11:58:03 +08:00
commit 93f7b84701
41 changed files with 1280 additions and 502 deletions

View File

@ -120,6 +120,7 @@ namespace Backend.Controllers
await niagaraDataSynchronizeRepository.CheckFullNameEmptyReplaceByDeviceName();
await niagaraDataSynchronizeRepository.InsertBuildingMenu();
await niagaraDataSynchronizeRepository.InsertSubSystemFloor();
await niagaraDataSynchronizeRepository.InsertFloor();
await this.DeviceDisasterAsync();
result = true;

View File

@ -4,23 +4,9 @@ using System.Linq;
using System.Xml;
using Newtonsoft.Json;
using Repository.Models;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Linq;
using Repository.BackendRepository.Implement;
using Repository.BackendRepository;
using Ubiety.Dns.Core;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Repository.Models.CodeBeautify;
using NPOI.SS.Formula.Functions;
using Microsoft.AspNetCore.Localization;
using MySqlX.XDevAPI.Relational;
using Backend.Models;
using NPOI.OpenXmlFormats.Dml;
namespace Backend.Services.Implement
{
@ -151,6 +137,7 @@ namespace Backend.Services.Implement
#region get control point data
List<control_point> conPoint = new List<control_point>();
String cp_API_Url = bqlUrlString;
String building_tag = slot.Split("/")[2].Replace("|", "_").Trim(); //Ex: D2_, M_
HttpWebRequest cp_Postrequest = (HttpWebRequest)WebRequest.Create(cp_API_Url);
cp_Postrequest.Method = "POST";
@ -220,8 +207,14 @@ namespace Backend.Services.Implement
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.LoadXml(responseString2);
// Create a namespace manager to handle the XML namespace
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc2.NameTable);
string xmlns = xmlDoc2.DocumentElement.GetAttribute("xmlns") ?? "http://obix.org/ns/schema/1.0";
namespaceManager.AddNamespace("obix", xmlns);
foreach (XmlNode node2 in xmlDoc2.DocumentElement.ChildNodes)
// Select all "ref" nodes using an XPath expression
XmlNodeList refNodes = xmlDoc2.SelectNodes($"//obix:ref[starts-with(@name, '{building_tag}')]", namespaceManager);
foreach (XmlNode node2 in refNodes)
{
string tagName = node2.Attributes["name"].InnerText;
if (tagName.Split('_').Length == 9)
@ -241,8 +234,8 @@ namespace Backend.Services.Implement
row.isHistory = true;
result.Add(row);
} else if (tagName.Split('_').Length == 6)
}
else if (tagName.Split('_').Length == 6)
{ //巨蛋 tag 5 段版本
ImpNiaItem row = new ImpNiaItem();
if (tagName.Split('_')[1] == "S") //for security system

View File

@ -762,11 +762,14 @@
return;
}
else {
$('#floor-modal').modal();
$("#BuildName").html(selected_build_guid_top_name);
$("#floor_name_modal").val(rel.data.full_name);
@*$("#map_file_preview_modal").attr("data-original", rel.data.mapUrl);*@
$('#floor-modal').modal();
if (rel.data.mapUrl)
loadURLToInputFiled(rel.data.mapUrl, rel.data.initMapName + ".svg");
else
$('#floor_map_file_modal')[0].value = "";
}
}, 'json');
});
@ -977,6 +980,27 @@
}
//#endregion
function loadURLToInputFiled(url, filesName){
getImgURL(url, (imgBlob)=>{
// Load img blob to input
// WIP: UTF8 character error
let fileName = filesName
let file = new File([imgBlob], fileName,{type:"image/svg+xml", lastModified:new Date().getTime()}, 'utf-8');
let container = new DataTransfer();
container.items.add(file);
$('#floor_map_file_modal')[0].files = container.files;
})
}
// xmlHTTP return blob respond
function getImgURL(url, callback){
var xhr = new XMLHttpRequest();
xhr.onload = function() {
callback(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
</script>
}

View File

@ -509,7 +509,7 @@
{
"data": null,
"render": function (data, type, row, meta){
return '<button bg-guid="'+row.building_tag+'" ms-guid="'+row.main_system_tag+'" ss-guid="'+row.sub_system_tag+'" class="btn btn-primary edit-btn">修改</button> <button class="btn btn-danger del-btn">刪除</button>';
return '<button bg-guid="'+row.building_tag+'" ms-guid="'+row.main_system_tag+'" ss-guid="'+row.sub_system_tag+'" class="btn btn-primary edit-btn">修改</button> <button class="btn btn-danger del-btn" bg-guid="'+row.building_tag+'" ms-guid="'+row.main_system_tag+'" ss-guid="'+row.sub_system_tag+'" >刪除</button>';
}
}
],

View File

@ -140,8 +140,9 @@
//#endregion
function SynchronizeData() {
document.getElementById('loadDataText').innerText = "同步中...";
if (ds.length > 0) {
document.getElementById('loadDataText').innerText = "同步中...";
showSpinner();
//比對資料有差異的話再同步到device等資料表
var url_synchronize_data = "/NiagaraDataSynchronize/CompareData/";
@ -154,20 +155,25 @@
url: url_synchronize_data,
data: JSON.stringify(ds),
cache: false,
async: false,
async: true,
contentType: "application/json; charset=UTF-8",
dataType: 'json',
success: function (rel) {
if (rel.code != "0000") {
hideSpinner();
toast_error(rel.msg);
document.getElementById('loadDataText').innerText = "比對資料出錯了!";
return;
}
SyncDevItem();
//var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
//var dateTime = date + ' ' + time;
//document.getElementById('loadDataText').innerText = "比對完成 \n" + dateTime;
},
error: function () {
hideSpinner();
}
});
}
else {
@ -192,6 +198,7 @@
dataType: 'json',
success: function (rel) {
if (rel.code != "0000") {
hideSpinner();
toast_error(rel.msg);
document.getElementById('loadDataText').innerText = "比對資料出錯了!";
return;
@ -208,15 +215,20 @@
success: function (rel) {
if (rel.code != "0000") {
toast_error(rel.msg);
hideSpinner();
document.getElementById('loadDataText').innerText = "比對資料出錯了!";
return;
}
hideSpinner();
console.log(rel);
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date + ' ' + time;
document.getElementById('loadDataText').innerText = "比對完成 \n" + dateTime;
},
error: function () {
hideSpinner();
}
})
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date + ' ' + time;

View File

@ -27,6 +27,11 @@
</head>
<body class="mod-bg-1 mod-nav-link">
<!-- BEGIN Page Wrapper -->
<div id="spinner" class="justify-content-center text-center loading hide">
<div class="spinner-border" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>
<div class="page-wrapper">
<div class="page-inner">
<!-- BEGIN Left Aside -->

View File

@ -23,7 +23,7 @@
<th>#</th>
<th>角色</th>
<th>功能類型</th>
<th>區域</th>
<th>棟別</th>
<th>功能名稱</th>
<th>功能細項名稱</th>
<th>建立時間</th>

View File

@ -18,10 +18,10 @@
"Port": "js2LutKe+rdjzdxMPQUrvQ==",
//"Database": "VJB2XC+lAtzuHObDGMVOAA==", //30
//"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp
//"Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome
"Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome
//"Database": "siTUcDaC/g2yGTMFWD72Kg==", //tpe_dome_hotel
//"Database": "iuaY0h0+TWkir44/eZLDqw==", //tpe_dome_office
"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut
//"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut
//"Database": "2U+9jYGy0dCbMzLaguBXow==", //tpe_dome_mall
"Root": "SzdxEgaJJ7tcTCrUl2zKsA==",
"Password": "FVAPxztxpY4gJJKQ/se4bQ=="

View File

@ -47,3 +47,34 @@ label.error {
.t-gray {
color:var(--bims-gray) !important;
}
/* Absolute Center Spinner */
.loading {
position: fixed;
z-index: 999;
display: block;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 50px;
height: 50px;
}
/* Transparent Overlay */
.loading:before {
content: '';
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: radial-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5));
background: -webkit-radial-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5));
}
.loading.hide {
display: none;
}

View File

@ -222,3 +222,11 @@ function SaveSpinner(status) { //1:Spinner 0:還原儲存
$(document).ready(function () {
});
function showSpinner() {
$("#spinner").removeClass("hide");
}
function hideSpinner() {
$("#spinner").addClass("hide");
}

View File

@ -47,6 +47,7 @@ namespace BackendWorkerService.Quartz.Jobs
public async Task Execute(IJobExecutionContext context)
{
Task_Detail task_Detail = new Task_Detail(loggers, backgroundServiceRepository);
string device_number = string.Empty;
try
{
if(await task_Detail.GetNeedWorkTask("ArchiveElectricMeterDayJob", "All"))
@ -159,8 +160,8 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveDayRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
device_number = deviceNumberPoint.FullDeviceNumberPoint;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -216,8 +217,8 @@ namespace BackendWorkerService.Quartz.Jobs
}
foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
device_number = deviceNumberPoint.FullDeviceNumberPoint;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -628,7 +629,8 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveWeekRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
device_number = deviceNumberPoint.FullDeviceNumberPoint;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -685,7 +687,8 @@ namespace BackendWorkerService.Quartz.Jobs
}
foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
device_number = deviceNumberPoint.FullDeviceNumberPoint;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -993,7 +996,8 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveMonthRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
device_number = deviceNumberPoint.FullDeviceNumberPoint;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -1049,7 +1053,8 @@ namespace BackendWorkerService.Quartz.Jobs
}
foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
device_number = deviceNumberPoint.FullDeviceNumberPoint;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -1337,8 +1342,6 @@ namespace BackendWorkerService.Quartz.Jobs
catch(Exception ex)
{
await task_Detail.WorkFail("ArchiveElectricMeterDayJob", "Compensate", ex.ToString());
logger.LogError("【ArchiveElectricMeterDayJob】【補償機制】【任務失敗】");
logger.LogError("【ArchiveElectricMeterDayJob】【補償機制】【任務失敗】[Exception]{0}", ex.ToString());
}
}
#endregion
@ -1350,35 +1353,105 @@ namespace BackendWorkerService.Quartz.Jobs
{
await task_Detail.WorkFail("ArchiveElectricMeterDayJob", "All", exception.ToString());
logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】");
logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】[Exception]{0}", exception.ToString());
logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】[Exception]{0}, {1}", exception.ToString(), "device_number = " + device_number);
}
}
private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult)
{
List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>();
var histories = jsonResult["obj"]["list"];
var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
if(rawdateCount == 0)
try
{
return null;
}
var histories = jsonResult["obj"]["list"];
var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
if (histories != null && histories.HasValues)
{
if (rawdateCount > 1)
{ //多筆資料
foreach (var history in histories)
{
if (rawdateCount == 0)
{
return null;
}
if (histories != null && histories.HasValues)
{
if (rawdateCount > 1)
{ //多筆資料
foreach (var history in histories)
{
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (history["abstime"] != null && history["abstime"].HasValues)
{
foreach (var abstime in history["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
{
case "start":
var startTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@start_timestamp", startTimstamp);
break;
case "end":
var endTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@end_timestamp", endTimstamp);
break;
}
}
}
//區間內資料筆數
if (history["int"] != null && history["int"].HasValues)
{
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (history["real"] != null && history["real"].HasValues)
{
foreach (var real in history["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@min_rawdata", min);
break;
case "max":
var max = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@max_rawdata", max);
break;
case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum);
break;
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
arrangeRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
arrangeRawDatas.Add(arrangeRawData);
}
}
else
{ //單筆資料
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (history["abstime"] != null && history["abstime"].HasValues)
if (histories["obj"]["abstime"] != null && histories["obj"]["abstime"].HasValues)
{
foreach (var abstime in history["abstime"])
foreach (var abstime in histories["obj"]["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
@ -1396,16 +1469,16 @@ namespace BackendWorkerService.Quartz.Jobs
}
//區間內資料筆數
if (history["int"] != null && history["int"].HasValues)
if (histories["obj"]["int"] != null && histories["obj"]["int"].HasValues)
{
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (history["real"] != null && history["real"].HasValues)
if (histories["obj"]["real"] != null && histories["obj"]["real"].HasValues)
{
foreach (var real in history["real"])
foreach (var real in histories["obj"]["real"])
{
var name = real["@name"].ToString();
switch (name)
@ -1437,76 +1510,13 @@ namespace BackendWorkerService.Quartz.Jobs
arrangeRawDatas.Add(arrangeRawData);
}
}
else
{ //單筆資料
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (histories["obj"]["abstime"] != null && histories["obj"]["abstime"].HasValues)
{
foreach (var abstime in histories["obj"]["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
{
case "start":
var startTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@start_timestamp", startTimstamp);
break;
case "end":
var endTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@end_timestamp", endTimstamp);
break;
}
}
}
//區間內資料筆數
if (histories["obj"]["int"] != null && histories["obj"]["int"].HasValues)
{
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (histories["obj"]["real"] != null && histories["obj"]["real"].HasValues)
{
foreach (var real in histories["obj"]["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@min_rawdata", min);
break;
case "max":
var max = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@max_rawdata", max);
break;
case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum);
break;
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
arrangeRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
arrangeRawDatas.Add(arrangeRawData);
}
return arrangeRawDatas;
}
catch (Exception ex)
{
return arrangeRawDatas;
}
return arrangeRawDatas;
}
}
}

View File

@ -786,6 +786,7 @@ namespace BackendWorkerService.Services.Implement
}
catch (Exception exception)
{
throw exception;
}
@ -795,28 +796,98 @@ namespace BackendWorkerService.Services.Implement
private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult)
{
List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>();
var histories = jsonResult["obj"]["list"];
var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
if (rawdateCount == 0)
try
{
return null;
}
var histories = jsonResult["obj"]["list"];
var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
if (histories != null && histories.HasValues)
{
if (rawdateCount > 1)
{ //多筆資料
foreach (var history in histories)
{
if (rawdateCount == 0)
{
return null;
}
if (histories != null && histories.HasValues)
{
if (rawdateCount > 1)
{ //多筆資料
foreach (var history in histories)
{
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (history["abstime"] != null && history["abstime"].HasValues)
{
foreach (var abstime in history["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
{
case "start":
var startTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@start_timestamp", startTimstamp);
break;
case "end":
var endTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@end_timestamp", endTimstamp);
break;
}
}
}
//區間內資料筆數
if (history["int"] != null && history["int"].HasValues)
{
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (history["real"] != null && history["real"].HasValues)
{
foreach (var real in history["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@min_rawdata", min);
break;
case "max":
var max = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@max_rawdata", max);
break;
case "avg":
var avg = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum);
break;
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
arrangeRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
arrangeRawDatas.Add(arrangeRawData);
}
}
else
{ //單筆資料
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (history["abstime"] != null && history["abstime"].HasValues)
if (histories["obj"]["abstime"] != null && histories["obj"]["abstime"].HasValues)
{
foreach (var abstime in history["abstime"])
foreach (var abstime in histories["obj"]["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
@ -834,30 +905,30 @@ namespace BackendWorkerService.Services.Implement
}
//區間內資料筆數
if (history["int"] != null && history["int"].HasValues)
if (histories["obj"]["int"] != null && histories["obj"]["int"].HasValues)
{
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (history["real"] != null && history["real"].HasValues)
if (histories["obj"]["real"] != null && histories["obj"]["real"].HasValues)
{
foreach (var real in history["real"])
foreach (var real in histories["obj"]["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = Convert.ToDecimal(real["@val"].ToString());
var min = real["@val"].ToString() == "NaN" ? -1 : 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 = real["@val"].ToString() == "NaN" ? -1 : 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 = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
@ -867,6 +938,7 @@ namespace BackendWorkerService.Services.Implement
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
@ -875,77 +947,13 @@ namespace BackendWorkerService.Services.Implement
arrangeRawDatas.Add(arrangeRawData);
}
}
else
{ //單筆資料
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (histories["obj"]["abstime"] != null && histories["obj"]["abstime"].HasValues)
{
foreach (var abstime in histories["obj"]["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
{
case "start":
var startTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@start_timestamp", startTimstamp);
break;
case "end":
var endTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@end_timestamp", endTimstamp);
break;
}
}
}
//區間內資料筆數
if (histories["obj"]["int"] != null && histories["obj"]["int"].HasValues)
{
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (histories["obj"]["real"] != null && histories["obj"]["real"].HasValues)
{
foreach (var real in histories["obj"]["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@min_rawdata", min);
break;
case "max":
var max = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@max_rawdata", max);
break;
case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum);
break;
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
arrangeRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
arrangeRawDatas.Add(arrangeRawData);
}
return arrangeRawDatas;
}
catch (Exception ex)
{
return arrangeRawDatas;
}
return arrangeRawDatas;
}
}
}

View File

@ -655,7 +655,7 @@
pointColor: color.success._500,
pointBackgroundColor: color.main1,
data: todayData?.data.map((x) => x.sum),
order: 1,
order: 2,
},
{
id: "yesterday",
@ -667,7 +667,7 @@
pointColor: color.info._100,
pointBackgroundColor: color.info._100,
data: yesData?.data.map((x) => x.sum),
order: 2,
order: 1,
},
],
};
@ -743,7 +743,7 @@
pointColor: color.success._500,
pointBackgroundColor: color.success._500,
data: curWeekData.map((x) => x.sum),
order: 1,
order: 2,
},
{
id: "yesterday",
@ -755,7 +755,7 @@
pointColor: color.info._100,
pointBackgroundColor: color.info._100,
data: prevWeekData.map((x) => x.sum),
order: 2,
order: 1,
},
],
};

View File

@ -70,6 +70,7 @@
<script>
var historyTable = null;
hisFirst = true;
$(function () {
initList();
@ -250,48 +251,61 @@
pageAct.deviceItem = val.points;
pageAct.devicePoiName = val.full_name + ' ' + val.points;
pageAct.deviceComName = val.parent_path;
getData();
} else {
strHtml += `<button onClick="setValue(null, null, '${val.points}', this)" type="button" class="btn btn-secondary waves-effect waves-themed">${val.full_name || val.points}</button>`;
}
});
$('#devPointsList').html(strHtml);
if (!hisFirst) {
let start = new Date($('#his_startdate').val());
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd")
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val());
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 30));
}
else if (pageAct.dateType != "range")
return;
getData(formatDate(start, "date", true), formatDate(end, "date", true));
}
}
ytAjax = new YourTeam.Ajax(url, objSendData, success, null, "POST").send();
}
function getData(start = null, end = null) {
var sdt = new Date();
var edt = new Date(new Date().setDate(sdt.getDate() + 1));
$(loadEle).Loading("start");
start = start ?? sdt.toLocaleDateString();
end = end ?? edt.toLocaleDateString();
callBackFromHistory()
getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem,
new Date(start).getTime(),
new Date(end).getTime(),
pageAct.deviceName,
pageAct.deviceComName,
callBackFromHistory);
$(loadEle).Loading("start");
var sdt = new Date();
var edt = new Date(new Date().setDate(sdt.getDate() + 1));
start = start ?? sdt.toLocaleDateString();
end = end ?? edt.toLocaleDateString();
// callBackFromHistory();
getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem,
new Date(start).getTime(),
new Date(end).getTime(),
pageAct.deviceName,
pageAct.deviceComName,
callBackFromHistory);
}
function callBackFromHistory(res = '{"count":0,"data":[]}') {
// console.log("@H1",res)
res = JSON.parse(res);
// console.log("@history",res.data)
loadTable(res.data);
if (historyTable != null) {
let t = $('#historyTable').dataTable();
t.fnClearTable();
if (res.data.length > 0)
t.fnAddData(res.data);
}
$(loadEle).Loading("close");
res = JSON.parse(res);
loadTable(res.data);
if (historyTable != null) {
let t = $('#historyTable').dataTable();
t.fnClearTable();
if (res.data.length > 0)
t.fnAddData(res.data);
}
}
function setValue(deviceNumber, deviceName, deviceItem, elem) {
hisFirst = false;
btnSelCss(elem);
if ((deviceNumber != null && deviceNumber != undefined) && (deviceName != null && deviceName != undefined)) {
@ -302,7 +316,20 @@
else if (deviceItem != null && deviceItem != undefined) {
pageAct.devicePoiName = $(elem).text();
pageAct.deviceItem = deviceItem;
getData();
let start = new Date($('#his_startdate').val());
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd")
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val());
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 30));
}
else if (pageAct.dateType != "range")
return;
getData(formatDate(start, "date", true), formatDate(end, "date", true));
}
}
@ -314,7 +341,7 @@
let ytd = formatDate(new Date(new Date().setDate(new Date().getDate() - 1)), "date");
let tmr = formatDate(new Date(new Date().setDate(new Date().getDate() + 1)), "date");
if (type == "day" || type == "today" || type == "ytd") {
if (type == "day" || type == "today" || type == "ytd") {
let date = type == "ytd" ? ytd : now;
$('#his_startdate').css('display', 'block');
$('#his_enddate').css('display', 'none');
@ -359,21 +386,23 @@
}
}
function searchDate() {
let start = new Date($('#his_startdate').val());
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
function searchDate() {
let start = new Date($('#his_startdate').val());
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd")
end = new Date(new Date().setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val());
end = new Date(new Date().setDate(start.getDate() + 30));
}
else if (pageAct.dateType != "range")
return;
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val());
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 30));
}
else if (pageAct.dateType != "range")
return;
getData(formatDate(start, "date", true), formatDate(end, "date", true));
}
pageAct.hisStartDate = start;
pageAct.hisEndDate = end;
getData(formatDate(start, "date", true), formatDate(end, "date", true));
}
function formatDate(date, type, send = false) {
if (!send)
@ -390,7 +419,6 @@
function loadTable(data) {
if (data) {
$.each(data, function (i, v) {
// console.log("loadTable",pageAct.devicePoiName.split(" ")[0])
v.type = pageAct.devicePoiName.split(" ")[0];
});
@ -425,31 +453,61 @@
"title": "紀錄時間",
"data": "timestamp",
"render": function (data) {
// console.log(data)
return displayDate(data, "datetime");
}
}
];
historyTable = new YourTeam.JqDataTables.getTableByStatic(tag, data, columns, column_defs, null, null, null, null, "tpi");
$(tag).DataTable().order([3, 'desc']);
}
}
function exportExcel() {
$(loadEle).Loading("start");
let url = baseApiUrl + "/History/OpeExportExcel";
objSendData.Data = $('#historyTable').dataTable().fnGetData();
function exportExcel() {
$(loadEle).Loading("start");
let token = cookies.get("JWT-Authorization");
let url = baseApiUrl + "/api/ExportHistory";
let v = {};
$.each(objSendData.Data, function (i, v) {
v.starttime = (pageAct.dateType == "month" ? new Date($('#getmonth').val()) : new Date($('#his_startdate').val()));
v.endtime = $('#his_enddate input').val() === "" ? null : new Date($('#his_enddate input').val());
v.dateType = pageAct.dateType;
});
ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) {
if (rel.code == "0000") {
location.href = baseApiUrl + "/api/df?path=" + rel.data.split('/')[0] + "&fileName=" + rel.data.split('/')[1] + "&token=" + cookies.get("JWT-Authorization");
}
}, null, "POST").send();
$(loadEle).Loading("close");
}
v.starttime = pageAct.hisStartDate;
v.endtime = pageAct.hisEndDate;
v.dateType = pageAct.dateType;
v.device_number = pageAct.deviceNumber;
objSendData.Data = v;
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(objSendData.Data),
aysnc: true,
headers: {
Authorization: "Bearer " + token,
},
contentType: "application/json; charset=utf-8",
xhrFields: {
responseType: "blob", // to avoid binary data being mangled on charset conversion
},
success: function (rel, text, xhr) {
if (rel) {
downloadByBlob(xhr, rel);
}
$(loadEle).Loading("close");
},
error: function () {
$(loadEle).Loading("close");
},
complete: (xhr) => {
setLoading(false);
},
});
// ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) {
// $(loadEle).Loading("close");
// }, function (rel) {
// if (rel) {
// downloadByBlob(xhr, rel);
// }
// $(loadEle).Loading("close");
// }, "POST",true).send();
}
</script>

View File

@ -8,13 +8,22 @@
<div class="btn-group">
<button type="button" onclick="setType(2)" class="btn btn-secondary waves-effect waves-themed">維修</button>
<button type="button" onclick="setType(1)" class="btn btn-secondary waves-effect waves-themed">保養記錄</button>
<button type="button" onclick="setType(null)" class="btn btn-secondary waves-effect waves-themed">廠商資料</button>
<button type="button" onclick="setType(null)"
class="btn btn-secondary waves-effect waves-themed">
廠商資料
</button>
</div>
</div>
<div id="setDate" class="col-auto">
<div class="btn-group">
<button onclick="setDate('tdy')" type="button" class="btn btn-secondary waves-effect waves-themed">今天</button>
<button onclick="setDate('ytd')" type="button" class="btn btn-secondary waves-effect waves-themed">昨天</button>
<button onclick="setDate('tdy')" type="button"
class="btn btn-secondary waves-effect waves-themed">
今天
</button>
<button onclick="setDate('ytd')" type="button"
class="btn btn-secondary waves-effect waves-themed">
昨天
</button>
</div>
</div>
<div class="col-auto">
@ -60,7 +69,7 @@
<a href="#" id="newForm" class="btn btn-success" data-toggle="modal" data-target="#opeFirmModal">新增</a>
<a href="#" onclick="exportExcel()" class="btn btn-info waves-effect waves-themed">
<span class="fal fa-file-excel mr-1"></span>
匯出
<span>匯出</span>
</a>
</div>
<table id="opeFirmTable" class="table table-bordered table-striped text-center m-0 w-100">
@ -76,7 +85,8 @@
</main>
<!-- Modal center 廠商資料 -->
<div class="modal fade" id="opeFirmModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal fade" id="opeFirmModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static"
data-keyboard="false">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
@ -152,7 +162,8 @@
</div>
<!-- Modal center 維修-->
<div class="modal fade" id="opeRecModal_2" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal fade" id="opeRecModal_2" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static"
data-keyboard="false">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
@ -222,12 +233,14 @@
<div class="form-control" id="inpStatus_2">
<div class="row container">
<div class="">
<input class="custom-radio-input" type="radio" name="inpSta_2" id="inpSta_2_0" value="0" data-value="0" checked>
<input class="custom-radio-input" type="radio" name="inpSta_2" id="inpSta_2_0" value="0"
data-value="0" checked>
<label class="form-label" for="inpSta_0">未完成</label>
</div>
<div class="px-4">
<input class="custom-radio-input" type="radio" name="inpSta_2" id="inpSta_2_1" value="1" data-value="1">
<input class="custom-radio-input" type="radio" name="inpSta_2" id="inpSta_2_1" value="1"
data-value="1">
<label class="form-label" for="inpSta_1">完成</label>
</div>
</div>
@ -251,7 +264,8 @@
<div class="col-md-12">
<div class="form-group">
<label class="form-label" for="inpDescription_2">結果描述</label>
<textarea class="form-control" type="text" id="inpDescription_2" name="inpDescription_2" rows="7"></textarea>
<textarea class="form-control" type="text" id="inpDescription_2" name="inpDescription_2"
rows="7"></textarea>
</div>
</div>
<div class="col-md-12">
@ -288,7 +302,8 @@
</div>
<!-- Modal center 保養 -->
<div class="modal fade" id="opeRecModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal fade" id="opeRecModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static"
data-keyboard="false">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
@ -350,12 +365,14 @@
<div class="form-control" id="inpStatus">
<div class="row container">
<div class="">
<input class="custom-radio-input" type="radio" name="inpSta" id="inpSta_0" data-value="0" value="0" checked>
<input class="custom-radio-input" type="radio" name="inpSta" id="inpSta_0" data-value="0"
value="0" checked>
<label class="form-label" for="inpSta_0">未完成</label>
</div>
<div class="px-4">
<input class="custom-radio-input" type="radio" name="inpSta" id="inpSta_1" data-value="1" value="1">
<input class="custom-radio-input" type="radio" name="inpSta" id="inpSta_1" data-value="1"
value="1">
<label class="form-label" for="inpSta_1">完成</label>
</div>
</div>
@ -379,7 +396,8 @@
<div class="col-md-12">
<div class="form-group">
<label class="form-label" for="inpDescription">結果描述</label>
<textarea class="form-control" type="text" id="inpDescription" name="inpDescription" rows="7"></textarea>
<textarea class="form-control" type="text" id="inpDescription" name="inpDescription"
rows="7"></textarea>
</div>
</div>
<div class="col-md-12">
@ -416,7 +434,8 @@
</div>
<!-- Modal center 刪除 -->
<div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static"
data-keyboard="false">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
@ -517,7 +536,6 @@
});
function loadOpeFirmTable() {
$(loadEle).Loading("start");
$('#opeFirmTable_wrapper').css('display', 'block');
$('#opeRecTable_wrapper').css('display', 'none');
$('#opeRecTable_2_wrapper').css('display', 'none');
@ -583,11 +601,9 @@
];
opeFirmTable = new YourTeam.JqDataTables.getTableByAjax(ajaxObj, tag, null, columns, column_defs);
$(loadEle).Loading("close");
}
function loadOpeRecTable() {
$(loadEle).Loading("start");
$('#opeFirmTable_wrapper').css('display', 'none');
$('#serial_number').parent().parent().css('display', 'block');
@ -620,7 +636,7 @@
{ "targets": [7], "width": "6%", "sortable": true },
{ "targets": [8], "width": "15%", "sortable": false },
{ "targets": [9], "width": "6%", "sortable": false },
{ "targets": [10], "width": "8%", "sortable": false },
{ "targets": [10], "width": "8%", "sortable": true },
{ "targets": [11], "width": "8%", "sortable": false },
];
@ -637,7 +653,7 @@
"title": "異常代號",
"data": "error_code",
render: (data) => {
return data?.split('-')[0] || '';
return data?.split('-')[0] || '' == null ? '' : data?.split('-')[0] || '';
}
},
{
@ -739,7 +755,8 @@
{ "targets": [7], "width": "15%", "sortable": false },
{ "targets": [8], "width": "6%", "sortable": false },
{ "targets": [9], "width": "8%", "sortable": false },
{ "targets": [10], "width": "8%", "sortable": false },
{ "targets": [10], "width": "8%", "sortable": true },
{ "targets": [11], "width": "8%", "sortable": false },
];
columns = [
@ -755,7 +772,7 @@
"title": "異常代號",
"data": "error_code",
render: (data) => {
return data?.split('-')[0] || '';
return data?.split('-')[0] || '' == null ? '' : data?.split('-')[0] || '';
}
},
{
@ -844,7 +861,7 @@
}
opeRecTable = new YourTeam.JqDataTables.getTableByAjax(ajaxObj, tag, null, columns, column_defs);
$(loadEle).Loading("close");
$(tag).DataTable().order([10, 'desc']).draw();
}
function setType(wt) {
@ -866,6 +883,7 @@
pageAct.startdate = startdate;
pageAct.enddate = enddate;
if ($('#startdate').val() > $('#enddate').val()) {
$('#startdate').val($('#startdate').data('val'));
$('#enddate').val($('#enddate').data('val'));
@ -876,20 +894,23 @@
let ytd = displayDate(new Date(new Date().setDate(new Date().getDate() - 1)), 'date').replaceAll('/', '-')
if (dateType == 'tdy') {
pageAct.startdate = new Date(displayDate(new Date(new Date().setDate(new Date().getDate())), 'date'));
pageAct.startdate = displayDate(new Date(new Date().setDate(new Date().getDate() + 1)), 'datetime');
pageAct.enddate = new Date(displayDate(new Date(new Date().setDate(new Date().getDate() + 2)), 'date'));
$('#startdate').val(today);
$('#startdate').data('val', today);
$('#enddate').val(today);
$('#enddate').data('val', today);
}
else if (dateType == 'ytd') {
pageAct.startdate = new Date(displayDate(new Date(new Date().setDate(new Date().getDate() - 1)), 'date'));
pageAct.startdate = new Date(displayDate(new Date(new Date().setDate(new Date().getDate())), 'date'));
pageAct.enddate = new Date(displayDate(new Date(new Date().setDate(new Date().getDate() + 1)), 'date'));
$('#startdate').val(ytd);
$('#startdate').data('val', ytd);
$('#enddate').val(ytd);
$('#enddate').data('val', ytd);
}
else {
pageAct.enddate = new Date(displayDate(new Date(pageAct.enddate.valueOf()).setDate(pageAct.enddate.getDate() + 2), 'date'));
$(`[onclick^=setDate]`).removeClass('btn-info');
$(`[onclick^=setDate]`).addClass('btn-secondary');
if ($('#startdate').val() == $('#enddate').val()) {
@ -983,10 +1004,9 @@
loadOpeRecTable();
}
function exportExcel() {
$(loadEle).Loading("start");
let url = baseApiUrl + "/operation/OpeExportExcel";
function exportExcel(e) {
let url = baseApiUrl + "/operation/OpeExportExcel";
objSendData.Data = {
work_type: pageAct.work_type,
startdate: pageAct.startdate == undefined ? null : pageAct.startdate,
@ -997,7 +1017,6 @@
if (rel.code == "0000")
location.href = baseApiUrl + "/api/df?path=" + rel.data.split('/')[0] + "&fileName=" + rel.data.split('/')[1] + "&token=" + cookies.get("JWT-Authorization");
}, null, "POST").send();
$(loadEle).Loading("close");
}
function selSysMain() {
@ -1086,6 +1105,7 @@
}
function selAllSysVal(elem) {
$(loadEle).Loading("start");
if ($(elem).html() == '全選類別') {
$('#mainList input').map(function (i, v) {
if (!$(v).is(':checked')) {
@ -1112,6 +1132,7 @@
}
refTable();
$(loadEle).Loading("close");
}
function event() {
@ -1359,12 +1380,18 @@
if (!res || res.code != "0000" || !res.data) {
} else {
pageAct.sysMain = res.data.device_system_category_layer2;
pageAct.sysSub = res.data.device_system_category_layer3;
pageAct.number = res.data.fix_do_code;
selOpeFir();
errCodeList();
callbackForErr(JSON.stringify({
count: [res.data].length,
data: [{ uuid: res.data.error_code }]
}));
$(pageAct.work_type == "1" ? '#inpNumber' : '#inpNumber_2').val(res.data.formId);
$(pageAct.work_type == "1" ? '#inpWorTyp' : '#inpWorTyp_2').val(res.data.work_type);
$(pageAct.work_type == "1" ? '#inpErrCode' : '#inpErrCode_2').val(res.data.error_code);
$(pageAct.work_type == "1" ? '#inpFixDo' : '#inpFixDo_2').val(res.data.fix_do);
$(pageAct.work_type == "1" ? '#inpFixDoCode' : '#inpFixDoCode_2').val(res.data.fix_do_code);
$(pageAct.work_type == "1" ? '#inpFixFirm' : '#inpFixFirm_2').val(res.data.fix_firm);
@ -1373,6 +1400,9 @@
$(pageAct.work_type == "1" ? '#inpStaTime' : '#inpStaTime_2').val(displayDate(res.data.start_time, 'date').replaceAll('/', '-'));
$(pageAct.work_type == "1" ? '#inpNotice' : '#inpNotice_2').val(res.data.notice);
$(pageAct.work_type == "1" ? '#inpDescription' : '#inpDescription_2').val(res.data.description);
let elemSel = $(pageAct.work_type == "1" ? '#inpFixDoCode' : '#inpFixDoCode_2').find('option:selected');;
pageAct.number = elemSel.val();
selOpeFir();
ope_imgHtml = null;
$.each(res.data.lorf, function (i, v) {
@ -1468,17 +1498,18 @@
}
function callbackForErr(res) {
res = JSON.parse(res);
res = JSON.parse(res) || res;
console.log(res)
strHtml = ``;
$.each(res.data, function (i, v) {
msg = v.msgText != null ? ($.trim(v.msgText.toString()).length > 0 ? v.msgText.split(':')[0] : '') : '';
strHtml += `<option value=${v.uuid}>${v.uuid}</option>`;
strHtml += `<option value=${v.uuid}>${v.uuid.split("-")[0]}</option>`;
});
if (res.count > 0)
$(pageAct.work_type == '1' ? '#inpErrCode' : '#inpErrCode_2').html(strHtml);
else
$(pageAct.work_type == '1' ? '#inpErrCode' : '#inpErrCode_2').html("");
$(loadEle).Loading("close");
}

View File

@ -900,6 +900,7 @@ License: You must have a valid license purchased only from wrapbootstrap.com (li
"lib/dropzone/dropzone-min",
"lib/jstree-master/jstree.min",
"lib/notifications/sweetalert2/sweetalert2.bundle",
"baja!"
], loadedMasterPack);
}
/**

View File

@ -57,6 +57,7 @@ function getHistoryDataByBaja(devicePath, startDate_millisecond, endDate_millise
_index++;
},
after: function () {
$(loadEle).Loading("close");
_result={count: _index, data: _ss}
// _result += '{' + '"count": ' + _index + ', "data":[';
// _result += _ss;
@ -73,6 +74,7 @@ function getHistoryDataByBaja(devicePath, startDate_millisecond, endDate_millise
})
.catch(()=>{
console.log("error");
$(loadEle).Loading("close");
// const res = JSON.stringify({count:0, data:[]})
callback()
});

View File

@ -1652,3 +1652,36 @@ function btnSelCss(elem) {
$(elem).removeClass('btn-secondary');
$(elem).addClass('btn-info');
}
/**
* 下載檔案
* @param {any} url
* @param {any} filename
*/
async function downloadByBlob(res, blob, filename, fetchOption, callback = null) {
// 擷取回傳 header > content-disposition (後端定義檔案名稱)
let disposition = res.getResponseHeader("Content-Disposition");
let sDowName = "";
if (disposition) {
// 解析出名稱
sDowName = disposition.split(/filename\*=(?:utf-8'')?(.*)/gi)[1];
if (sDowName.toLowerCase().startsWith("utf-8''"))
sDowName = decodeURIComponent(sDowName.replace(/utf-8''/i, ""));
else sDowName = sDowName.replace(/['"]/g, "");
sDowName = decodeURIComponent(sDowName);
}
// 隱形a標籤
const a = document.createElement("a");
let href = URL.createObjectURL(blob);
if (href) {
a.href = href;
a.download = filename || sDowName || "";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
callback ? callback() : "";
return true;
} else {
return false;
}
}

View File

@ -180,7 +180,7 @@ namespace FrontendWebApi.ApiControllers
v2.system_key subfull_name,
v2.system_priority subpriority
from building_menu me
left join building b on b.building_tag = me.building_tag
left join building b on b.building_tag = me.building_tag and b.deleted = 0
left join variable v1 on me.main_system_tag = v1.system_value and v1.deleted = 0 and v1.system_type = 'device_system_category_layer2'
left join variable v2 on me.sub_system_tag = v2.system_value and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3'
inner join (
@ -257,7 +257,7 @@ namespace FrontendWebApi.ApiControllers
string name = sub.Select(s => s.subfull_name).FirstOrDefault();
bool check = true;
if (name == "人流計數")
check = sub.Select(s => s.sub_system_tag).FirstOrDefault().StartsWith(menu.Select(m => m.device_building_tag).FirstOrDefault());
check = sub.Select(s => s.sub_system_tag).FirstOrDefault().StartsWith(menu.Select(m => m.device_building_tag[0]).FirstOrDefault());
if (check)
{
@ -580,7 +580,7 @@ namespace FrontendWebApi.ApiControllers
{disasterjoinsql}
LEFT JOIN building_menu bm ON d.device_building_tag = bm.building_tag AND d.device_system_tag = bm.main_system_tag AND d.device_name_tag = bm.sub_system_tag
where d.deleted = 0 and d.device_building_tag = '{post.building_tag}' {sWhere}
order by d.priority ASC, d.device_number ASC";
order by d.priority ASC, left(device_serial_tag, LENGTH(device_serial_tag) - 1) ASC";
var devicelist = await backendRepository.GetAllAsync<DeviceFloor>(sql);

View File

@ -107,7 +107,7 @@ namespace FrontendWebApi.ApiControllers
[HttpPost]
[Route("api/EmergencyContact/PDF")]
public async Task<ActionResult<ApiResult<string>>> ExportPDF(export post)
public async Task<ActionResult<ApiResult<string>>> ExportPDF([FromBody] export post)
{
//var grouping = JsonConvert.DeserializeObject<export>(post);
ApiResult<string> apiResult = new ApiResult<string>();
@ -182,7 +182,7 @@ namespace FrontendWebApi.ApiControllers
[HttpPost]
[Route("api/EmergencyContact/Excel")]
public async Task<ActionResult<ApiResult<string>>> ExportExcel(export post)
public async Task<ActionResult<ApiResult<string>>> ExportExcel([FromBody] export post)
{
//var guid = Guid.NewGuid().ToString();
ApiResult<string> apiResult = new ApiResult<string>();

View File

@ -16,10 +16,6 @@ using System.Threading.Tasks;
using System.Xml;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.HPSF;
using Google.Protobuf.WellKnownTypes;
namespace FrontendWebApi.ApiControllers
{
@ -47,137 +43,199 @@ namespace FrontendWebApi.ApiControllers
/// <param name="lhe"></param>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult<ApiResult<string>>> OpeExportExcel([FromBody] List<HistoryExport> lhe)
[Route("api/ExportHistory")]
public FileResult OpeExportExcel([FromBody] HistoryExport lhe)
{
ApiResult<string> apiResult = new ApiResult<string>();
if (lhe == null)
{
apiResult.Code = "0001";
apiResult.Msg = "沒有資料匯入";
return apiResult;
}
//if (lhe == null)
//{
// apiResult.Code = "0001";
// apiResult.Msg = "沒有資料匯入";
// return apiResult;
//}
var fileDateName = lhe.dateType == "today" ? lhe.starttime.ToString("yyyy-MM-dd")
: lhe.dateType == "month" ? lhe.starttime.ToString("yyyy-MM")
: lhe.starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.endtime).ToString("yyyy-MM-dd");
var fileName = "歷史資料_" + fileDateName + ".xlsx";
IWorkbook workbook = new XSSFWorkbook();
try
{
var fileDateName = lhe.FirstOrDefault().dateType == "month" ? lhe.FirstOrDefault().starttime.ToString("yyyy-MM") : lhe.FirstOrDefault().endtime == null ? lhe.FirstOrDefault().starttime.ToString("yyyy-MM-dd") : lhe.FirstOrDefault().starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.FirstOrDefault().endtime).ToString("yyyy-MM-dd");
var fileName = "歷史資料_"+fileDateName+".xlsx";
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "excel", "history");
#region obix
EDFunction ed = new EDFunction();
var obixApiConfig = new ObixApiConfig();
var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'";
var variableObix = backendRepository.GetAllAsync<KeyValue>(sqlObix).Result;
obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault();
obixApiConfig.UserName = ed.AESDecrypt(variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault());
obixApiConfig.Password = ed.AESDecrypt(variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault());
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(obixApiConfig.UserName + ":" + obixApiConfig.Password));
#endregion obix
#region get device and device_item(point)
var device = backendRepository.GetAllAsync<Device>($"select * from device where deleted = 0 and is_link = 1 and device_number = '{lhe.device_number}'").Result;
var devicePoint = backendRepository.GetAllAsync<Device_item>($"select * from device_item where deleted = 0 and is_link = 1 and is_show_history = 1 and device_building_tag = '{lhe.building_tag}' and points = '{lhe.device_item}'").Result;
#endregion
#region get data from niagara
lhe.endtime = lhe.dateType == "today" ? lhe.starttime : lhe.dateType == "month" ? lhe.starttime.AddMonths(1) : lhe.endtime;
var startTimestamp = string.Format("{0}T00:00:00.000+08:00", lhe.starttime.ToString("yyyy-MM-dd"));
var endTimestamp = string.Format("{0}T23:59:59.000+08:00", lhe.endtime?.ToString("yyyy-MM-dd"));
var historyQueryFilter = $@"<obj is='obix: HistoryFilter'>
<abstime name='start' val='{startTimestamp}' />
<abstime name='end' val='{endTimestamp}' />
<reltime name='interval' val='PT15M' />
</obj>";
if (!System.IO.Directory.Exists(filePath))
System.IO.Directory.CreateDirectory(filePath);
List<HistoryExport> he = new List<HistoryExport>();
using (var fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create, FileAccess.Write))
var archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{lhe.deviceComName}/{lhe.device_number.Replace("$3", "")}_{lhe.device_item}/~historyRollup/");
archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
archiveRequest.PreAuthenticate = true;
byte[] byteArray = Encoding.UTF8.GetBytes(historyQueryFilter);
using (Stream reqStream = archiveRequest.GetRequestStream())
{
IWorkbook workbook = new XSSFWorkbook();
#region excel設定
IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體";
font12.FontHeightInPoints = 12;
ICellStyle style12 = workbook.CreateCellStyle();
style12.SetFont(font12);
style12.Alignment = HorizontalAlignment.Center;
style12.VerticalAlignment = VerticalAlignment.Center;
IFont font12Times = workbook.CreateFont();
font12Times.FontName = "Times New Roman";
font12Times.FontHeightInPoints = 12;
IFont font18 = workbook.CreateFont();
font18.FontName = "新細明體";
font18.FontHeightInPoints = 18;
font18.IsBold = true;
ICellStyle styleTitle18 = workbook.CreateCellStyle();
styleTitle18.SetFont(font18);
styleTitle18.Alignment = HorizontalAlignment.Center;
styleTitle18.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLeft12 = workbook.CreateCellStyle();
styleLeft12.SetFont(font12);
styleLeft12.Alignment = HorizontalAlignment.Left;
styleLeft12.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLine12 = workbook.CreateCellStyle();
styleLine12.SetFont(font12);
styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
styleLine12.VerticalAlignment = VerticalAlignment.Center;
styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
ICellStyle stylein12 = workbook.CreateCellStyle();
stylein12.SetFont(font12Times);
stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
stylein12.VerticalAlignment = VerticalAlignment.Center;
stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.WrapText = true;
#endregion
ISheet sheet = workbook.CreateSheet("歷史資料");
int RowPosition = 0;
#region set cell
IRow row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12);
sheet.SetColumnWidth(1, 4 * 160 * 12);
sheet.SetColumnWidth(2, 4 * 160 * 12);
sheet.SetColumnWidth(3, 4 * 160 * 12);
ICell cell = row.CreateCell(0);
cell.SetCellValue("類型");
cell.CellStyle = styleLine12;
cell = row.CreateCell(1);
cell.SetCellValue("設備名稱");
cell.CellStyle = styleLine12;
cell = row.CreateCell(2);
cell.SetCellValue("數值");
cell = row.CreateCell(3);
cell.SetCellValue("記錄時間");
cell.CellStyle = styleLine12;
#endregion
if (lhe.Count > 0)
{
foreach (var he in lhe)
{
RowPosition += 1;
row = sheet.CreateRow(RowPosition);
for (var i = 0; i < 4; i++)
{
cell = row.CreateCell(i);
if (i == 0)
{
cell.SetCellValue(he.type);
}
if (i == 1)
{
cell.SetCellValue(he.deviceName);
}
if (i == 2)
{
cell.SetCellValue(he.value);
}
if (i == 3)
{
cell.SetCellValue(he.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
}
cell.CellStyle = style12;
}
}
}
workbook.Write(fs);
reqStream.Write(byteArray, 0, byteArray.Length);
}
apiResult.Code = "0000";
apiResult.Data = "history/" + fileName;
var archiveResponse = (HttpWebResponse)archiveRequest.GetResponse();
var archiveResponseContent = new StreamReader(archiveResponse.GetResponseStream()).ReadToEnd();
archiveResponse.Dispose();
archiveResponse.Close();
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(archiveResponseContent);
var archiveJson = JsonConvert.SerializeXmlNode(xmlDocument);
var archiveJsonResult = (JObject)JsonConvert.DeserializeObject(archiveJson);
if (!archiveJsonResult.ContainsKey("err"))
{
var ArrangeRawDatas = ArrangeRawData(new DeviceNumberPoint() { DeviceNumber = lhe.device_number, Point = lhe.device_item, FullDeviceNumberPoint = lhe.device_number + "_" + lhe.device_item}, archiveJsonResult);
if (ArrangeRawDatas != null && ArrangeRawDatas.Count > 0)
{
foreach (var ard in ArrangeRawDatas)
{
HistoryExport hed = new HistoryExport();
hed.type = devicePoint.Where(x => x.device_building_tag == lhe.building_tag && x.points == ard["@point"].ToString()).Select(x => x.full_name).FirstOrDefault();
hed.deviceName = device.Where(x => x.device_number == ard["@device_number"].ToString()).Select(x => x.full_name).FirstOrDefault();
hed.value = ard["@avg_rawdata"].ToString() == "-1" ? "NaN" : Math.Round(Decimal.Parse(ard["@avg_rawdata"].ToString(), System.Globalization.NumberStyles.Float), 2).ToString();
hed.timestamp = Convert.ToDateTime(ard["@start_timestamp"].ToString());
hed.building_tag = lhe.building_tag;
he.Add(hed);
}
}
}
#endregion
#region excel設定
IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體";
font12.FontHeightInPoints = 12;
ICellStyle style12 = workbook.CreateCellStyle();
style12.SetFont(font12);
style12.Alignment = HorizontalAlignment.Center;
style12.VerticalAlignment = VerticalAlignment.Center;
IFont font12Times = workbook.CreateFont();
font12Times.FontName = "Times New Roman";
font12Times.FontHeightInPoints = 12;
IFont font18 = workbook.CreateFont();
font18.FontName = "新細明體";
font18.FontHeightInPoints = 18;
font18.IsBold = true;
ICellStyle styleTitle18 = workbook.CreateCellStyle();
styleTitle18.SetFont(font18);
styleTitle18.Alignment = HorizontalAlignment.Center;
styleTitle18.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLeft12 = workbook.CreateCellStyle();
styleLeft12.SetFont(font12);
styleLeft12.Alignment = HorizontalAlignment.Left;
styleLeft12.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLine12 = workbook.CreateCellStyle();
styleLine12.SetFont(font12);
styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
styleLine12.VerticalAlignment = VerticalAlignment.Center;
styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
ICellStyle stylein12 = workbook.CreateCellStyle();
stylein12.SetFont(font12Times);
stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
stylein12.VerticalAlignment = VerticalAlignment.Center;
stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.WrapText = true;
#endregion
ISheet sheet = workbook.CreateSheet("歷史資料");
int RowPosition = 0;
#region set cell
IRow row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12);
sheet.SetColumnWidth(1, 4 * 160 * 12);
sheet.SetColumnWidth(2, 4 * 160 * 12);
sheet.SetColumnWidth(3, 4 * 160 * 12);
ICell cell = row.CreateCell(0);
cell.SetCellValue("類型");
cell.CellStyle = styleLine12;
cell = row.CreateCell(1);
cell.SetCellValue("設備名稱");
cell.CellStyle = styleLine12;
cell = row.CreateCell(2);
cell.SetCellValue("數值");
cell = row.CreateCell(3);
cell.SetCellValue("記錄時間");
cell.CellStyle = styleLine12;
#endregion
foreach (var d in he)
{
RowPosition += 1;
row = sheet.CreateRow(RowPosition);
for (var i = 0; i < 4; i++)
{
cell = row.CreateCell(i);
if (i == 0)
{
cell.SetCellValue(d.type);
}
if (i == 1)
{
cell.SetCellValue(d.deviceName);
}
if (i == 2)
{
cell.SetCellValue(d.value);
}
if (i == 3)
{
cell.SetCellValue(d.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
}
cell.CellStyle = style12;
}
}
}
catch (Exception exception)
{
apiResult.Code = "9999";
apiResult.Msg = "系統內部錯誤,請聯絡管理者。 Msg: " + exception.Message;
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
throw exception;
}
return Ok(apiResult);
var ms = new NpoiMemoryStream
{
AllowClose = false
};
workbook.Write(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
return File(ms, "application/vnd.ms-excel", fileName);
}
/// <summary>
@ -1204,5 +1262,167 @@ namespace FrontendWebApi.ApiControllers
}
return Ok(apiResult);
}
private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult)
{
List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>();
try
{
var histories = jsonResult["obj"]["list"]["obj"];
var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
if (rawdateCount == 0)
{
return null;
}
if (histories != null && histories.HasValues)
{
if (rawdateCount > 1)
{ //多筆資料
foreach (var history in histories)
{
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (history["abstime"] != null && history["abstime"].HasValues)
{
foreach (var abstime in history["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
{
case "start":
var startTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@start_timestamp", startTimstamp);
break;
case "end":
var endTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@end_timestamp", endTimstamp);
break;
}
}
}
//區間內資料筆數
if (history["int"] != null && history["int"].HasValues)
{
var count = Convert.ToInt32(history["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (history["real"] != null && history["real"].HasValues)
{
foreach (var real in history["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@min_rawdata", min);
break;
case "max":
var max = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@max_rawdata", max);
break;
case "avg":
var avg = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
var sum = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum);
break;
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
arrangeRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
arrangeRawDatas.Add(arrangeRawData);
}
}
else
{ //單筆資料
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (histories["obj"]["abstime"] != null && histories["obj"]["abstime"].HasValues)
{
foreach (var abstime in histories["obj"]["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
{
case "start":
var startTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@start_timestamp", startTimstamp);
break;
case "end":
var endTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@end_timestamp", endTimstamp);
break;
}
}
}
//區間內資料筆數
if (histories["obj"]["int"] != null && histories["obj"]["int"].HasValues)
{
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (histories["obj"]["real"] != null && histories["obj"]["real"].HasValues)
{
foreach (var real in histories["obj"]["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@min_rawdata", min);
break;
case "max":
var max = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@max_rawdata", max);
break;
case "avg":
var avg = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
var sum = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum);
break;
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
arrangeRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
arrangeRawDatas.Add(arrangeRawData);
}
}
return arrangeRawDatas;
}
catch (Exception ex)
{
return arrangeRawDatas;
}
}
}
}

View File

@ -114,7 +114,7 @@ namespace FrontendWebApi.ApiControllers
var aemmEndDate = input.tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {input.tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {input.tableType})";
var aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date";
var sql = $@"set @i = -1;
select fd.device_number, aemm.avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp
select fd.device_number, case when aemm.avg_rawdata = -1 then 'NaN' when aemm.avg_rawdata is null then '0' else aemm.avg_rawdata end as avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp
from (
select *
from (
@ -161,7 +161,7 @@ namespace FrontendWebApi.ApiControllers
foreach (var l in list)
{
l.rawData = new List<HydroMeterRawDataOutput>();
l.device_full_name = await backendRepository.GetOneAsync<string>($"select full_name from device where device_number = '{l.device_number}' and deleted = 0");
l.device_full_name = await backendRepository.GetOneAsync<string>($"select full_name from device where device_number = '{l.device_number}'");
if (tag_quantity == "5")
{
l.rawData.AddRange(
@ -176,7 +176,7 @@ namespace FrontendWebApi.ApiControllers
}
l.building_name = await backendRepository.GetOneAsync<string>("select full_name from building where building_tag = @building_tag and deleted = 0",
new { building_tag = l.building_tag });
l.total = l.rawData.Sum(x => x.avg_rawdata).ToString();
l.total = l.rawData.Where(x => x.avg_rawdata != "NaN").Sum(x => Decimal.Parse(x.avg_rawdata, System.Globalization.NumberStyles.Float)).ToString();
l.price = input.price.HasValue
? (Math.Round(input.price.Value, 2)).ToString()
: Math.Round((await backendRepository.GetOneAsync<decimal>("select system_value from variable where system_type = 'ElectricPrice' and deleted = 0")), 2).ToString();
@ -244,10 +244,10 @@ namespace FrontendWebApi.ApiControllers
: input.tableType == "month" ? (Int32.Parse(input.startTime.Split("-")[0]) + 1) + "-01-01"
: input.tableType == "year" ? (Int32.Parse(input.endTime) + 1).ToString() + "-01-01"
: null;
string dbDateName = startTime.Split("-")[0].ToString().PadLeft(4, '0') + startTime.Split("-")[1].ToString().PadLeft(2, '0');
string sqlWhere = "";
string sqlGroup = "";
string sqlAvgRawData = "";
string dbDateName = startTime.Split("-")[0].ToString().PadLeft(4, '0') + startTime.Split("-")[1].ToString().PadLeft(2, '0');
string buildingSql = "";
string tag_quantity = await backendRepository.GetOneAsync<string>("select system_value from variable where system_type = 'obixConfig' and system_key = 'tag_quantity' and deleted = 0");
@ -272,7 +272,7 @@ namespace FrontendWebApi.ApiControllers
else
sqlAvgRawData = " round(avg_rawdata, 2) as avg_rawdata, start_timestamp, end_timestamp ";
var table = input.tableType == "year" ? "archive_electric_meter_month" : "archive_electric_meter_" + input.tableType + (input.tableType == "day" ? "_" + dbDateName : "");
var table = input.tableType == "year" ? "archive_water_meter_month" : "archive_water_meter_" + input.tableType + (input.tableType == "day" ? "_" + dbDateName : "");
var schema = await backendRepository.GetOneAsync<string>($"select system_value from variable where system_type = 'project_name'");
var isTable = await backendRepository.GetOneAsync<string>($"select table_name from information_schema.tables where table_name = '{table}' and table_schema = '{schema.Split('/')[0]}'");
if (string.IsNullOrEmpty(isTable)) //check for has table or not
@ -286,7 +286,7 @@ namespace FrontendWebApi.ApiControllers
var aemmEndDate = input.tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {input.tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {input.tableType})";
var aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date";
var sql = $@"set @i = -1;
select fd.device_number, aemm.avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp
select fd.device_number, case when aemm.avg_rawdata = -1 then 'NaN' when aemm.avg_rawdata is null then '0' else aemm.avg_rawdata end as avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp
from (
select *
from (
@ -307,9 +307,9 @@ namespace FrontendWebApi.ApiControllers
left join (
select device_number, {sqlAvgRawData}
from {table}
where start_timestamp >= {aemmStaDate} and end_timestamp < {aemmEndDate} and point = 'RCV' {buildingSql}
where start_timestamp >= @startTime and end_timestamp < @endTime and point = 'RCV' {buildingSql}
{sqlWhere} {sqlGroup}
) aemm on aemm.start_timestamp >= fd.date and aemm.end_timestamp < DATE_ADD(fd.date, INTERVAL +1 {input.tableType}) and aemm.device_number = fd.device_number
) aemm on aemm.start_timestamp >= {aemmStaDate} and aemm.end_timestamp < {aemmEndDate} and aemm.device_number = fd.device_number
order by fd.device_number, fd.date";
var rawData = await backendRepository.GetAllAsync<HydroMeterRawDataOutput>(sql,
@ -334,7 +334,7 @@ namespace FrontendWebApi.ApiControllers
foreach (var l in list)
{
l.rawData = new List<HydroMeterRawDataOutput>();
l.device_full_name = await backendRepository.GetOneAsync<string>($"select full_name from device where device_number = '{l.device_number}' and deleted = 0");
l.device_full_name = await backendRepository.GetOneAsync<string>($"select full_name from device where device_number = '{l.device_number}'");
if (tag_quantity == "5")
{
l.rawData.AddRange(
@ -349,7 +349,7 @@ namespace FrontendWebApi.ApiControllers
}
l.building_name = await backendRepository.GetOneAsync<string>("select full_name from building where building_tag = @building_tag and deleted = 0",
new { building_tag = l.building_tag });
l.total = l.rawData.Sum(x => x.avg_rawdata).ToString();
l.total = l.rawData.Where(x => x.avg_rawdata != "NaN").Sum(x => Decimal.Parse(x.avg_rawdata, System.Globalization.NumberStyles.Float)).ToString();
l.price = input.price.HasValue
? (Math.Round(input.price.Value, 2)).ToString()
: Math.Round((await backendRepository.GetOneAsync<decimal>("select system_value from variable where system_type = 'WaterPrice' and deleted = 0")), 2).ToString();
@ -766,7 +766,157 @@ namespace FrontendWebApi.ApiControllers
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
return File(ms, "application/vnd.ms-excel", "電表報表.xlsx");
}
[HttpPost]
[Route("api/ExportWaterList")]
public FileResult OpeExportExcelWater([FromBody] HydroMeterInput input)
{
var result = this.WaterList(input).Result.Value.Data.ToList();
var workbook = new XSSFWorkbook();
#region excel設定
IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體";
font12.FontHeightInPoints = 12;
ICellStyle style12 = workbook.CreateCellStyle();
style12.SetFont(font12);
style12.Alignment = HorizontalAlignment.Center;
style12.VerticalAlignment = VerticalAlignment.Center;
IFont font12Times = workbook.CreateFont();
font12Times.FontName = "Times New Roman";
font12Times.FontHeightInPoints = 12;
IFont font18 = workbook.CreateFont();
font18.FontName = "新細明體";
font18.FontHeightInPoints = 18;
font18.IsBold = true;
ICellStyle styleTitle18 = workbook.CreateCellStyle();
styleTitle18.SetFont(font18);
styleTitle18.Alignment = HorizontalAlignment.Center;
styleTitle18.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLeft12 = workbook.CreateCellStyle();
styleLeft12.SetFont(font12);
styleLeft12.Alignment = HorizontalAlignment.Left;
styleLeft12.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLine12 = workbook.CreateCellStyle();
styleLine12.SetFont(font12);
styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
styleLine12.VerticalAlignment = VerticalAlignment.Center;
styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
ICellStyle stylein12 = workbook.CreateCellStyle();
stylein12.SetFont(font12Times);
stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
stylein12.VerticalAlignment = VerticalAlignment.Center;
stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.WrapText = true;
#endregion
var sheet = workbook.CreateSheet("電表報表");
int RowPosition = 0;
if (result.Count > 0)
{
#region set cell
IRow row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12);
sheet.SetColumnWidth(1, 4 * 160 * 12);
sheet.SetColumnWidth(2, 4 * 160 * 12);
int i = 0;
ICell cell = row.CreateCell(i++);
cell.SetCellValue("東別");
cell.CellStyle = styleLine12;
cell = row.CreateCell(i++);
cell.SetCellValue("樓層");
cell.CellStyle = styleLine12;
cell = row.CreateCell(i++);
cell.SetCellValue("設備");
cell.CellStyle = styleLine12;
foreach (var rr in result.FirstOrDefault().rawData)
{
cell = row.CreateCell(i++);
cell.SetCellValue(rr.timeStamp);
cell.CellStyle = styleLine12;
}
cell = row.CreateCell(i++);
cell.SetCellValue("小計");
cell.CellStyle = styleLine12;
cell = row.CreateCell(i++);
cell.SetCellValue("單價");
cell.CellStyle = styleLine12;
cell = row.CreateCell(i++);
cell.SetCellValue("金額總計");
cell.CellStyle = styleLine12;
#endregion
foreach (var r in result)
{
RowPosition += 1;
int k = 3;
row = sheet.CreateRow(RowPosition);
for (int j = 0; j <= i; j++)
{
cell = row.CreateCell(j);
if (j == 0)
{
cell.SetCellValue(r.building_name);
}
if (j == 1)
{
cell.SetCellValue(r.floor_tag);
}
if (j == 2)
{
cell.SetCellValue(r.device_serial_tag);
}
if (j == 3)
{
foreach (var rr in r.rawData)
{
cell.SetCellValue(rr.avg_rawdata.ToString());
j++;
k++;
cell = row.CreateCell(j);
}
}
if (j == k)
{
cell.SetCellValue(r.total);
}
if (j == k + 1)
{
cell.SetCellValue(r.price);
}
if (j == k + 2)
{
cell.SetCellValue(r.total_price);
}
cell.CellStyle = style12;
}
}
}
var ms = new NpoiMemoryStream
{
AllowClose = false
};
workbook.Write(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
return File(ms, "application/vnd.ms-excel", "水表報表.xlsx");
}
public static int GetDayInMonth(string yearMonth)
{
List<string> datesList = new List<string>();

View File

@ -289,13 +289,41 @@ namespace FrontendWebApi.Models
public class HistoryExport
{
public string deviceName { get; set; }
public double value { get; set; }
public string value { get; set; }
public DateTime timestamp { get; set; }
public DateTime starttime { get; set; }
public DateTime? endtime { get; set; }
public string dateType { get; set; }
public string type { get; set; }
public string device_number { get; set; }
public string device_item { get; set; }
public string deviceComName { get; set; }
public string building_tag { get; set; }
}
public class DeviceNumberPoint
{
public string DeviceNumber { get; set; }
public string Point { get; set; }
public string FullDeviceNumberPoint { get; set; }
}
public class Device_item : Actor
{
public int id { get; set; }
public string device_item_guid { get; set; }
public string device_area_tag { get; set; }
public string device_building_tag { get; set; }
public string device_system_tag { get; set; }
public string device_name_tag { get; set; }
public string full_name { get; set; }
public string points { get; set; }
public string unit { get; set; }
public byte is_show { get; set; }
public byte is_show_riserDiagram { get; set; }
public byte is_controll { get; set; }
public byte is_bool { get; set; }
public byte is_link { get; set; }
public int is_show_history { get; set; }
}
}

View File

@ -37,7 +37,7 @@ namespace FrontendWebApi.Models
{
public string timeStamp { get; set; }
public string device_number { get; set; }
public decimal avg_rawdata { get; set; }
public string avg_rawdata { get; set; }
}
public class HydroMeterPriceInput

View File

@ -32,8 +32,6 @@
</div>
<div class="pr-3 row col">
<div class="frame-wrap" id="groupinglist">
</div>
</div>
<div class="card border mb-g w-100 mb-5" id="emergency_setting_card">
@ -201,8 +199,7 @@
}
//選擇組別
function SelectGrouping(grouping, e)
{
function SelectGrouping(grouping, e) {
if ($(e).hasClass("btn-outline-success")) {
$(e).removeClass("btn-outline-success").addClass("btn-success");
selectgroupidlist.push(grouping);
@ -218,8 +215,7 @@
}
//全選所有組別
function Allgroupingselect()
{
function Allgroupingselect() {
if (Allgroupingbool) {
$('#groupinglist').find(".btn-success").removeClass("btn-success").addClass("btn-outline-success");
selectgroupidlist = [];
@ -249,7 +245,27 @@
disaster: $('#Disasterlist').find('.btn-success').html(),
groupidlist: selectgroupidlist
}
window.location = "/EmergencyContact/ExportPDF?post=" + JSON.stringify(send_data);
var url = "/api/EmergencyContact/PDF";
$.ajax({
method: "POST",
contentType:"application/json; chatset='utf-8'",
headers: { "Authorization": "Bearer " + localStorage.getItem('JWT-Authorization') },
url: url,
data: JSON.stringify(send_data),
success: (res, text, xhr) => {
if (res.code == "9999") {
toast_error(res.msg);
return;
}
if(res.data && res.code == "0000"){
window.open(location.origin + "/" + res.data)
} else {
toast_error("系統發生錯誤,請再重新嘗試");
}
}
})
}
}
@ -269,7 +285,25 @@
disaster: $('#Disasterlist').find('.btn-success').html(),
groupidlist: selectgroupidlist
}
window.location = "/EmergencyContact/ExportExcel?post=" + JSON.stringify(send_data);
var url = "/api/EmergencyContact/Excel";
$.ajax({
method: "POST",
contentType: "application/json; chatset='utf-8'",
headers: { "Authorization": "Bearer " + localStorage.getItem('JWT-Authorization') },
url: url,
data: JSON.stringify(send_data),
success: (res, text, xhr) => {
if (res.code == "9999") {
toast_error(res.msg);
return;
}
if(res.data && res.code == "0000"){
window.open(location.origin + "/" + res.data)
} else {
toast_error("系統發生錯誤,請再重新嘗試");
}
}
})
}
}

View File

@ -18,10 +18,10 @@
"Port": "js2LutKe+rdjzdxMPQUrvQ==",
//"Database": "VJB2XC+lAtzuHObDGMVOAA==", //30
//"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp
//"Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome
"Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome
//"Database": "siTUcDaC/g2yGTMFWD72Kg==", //tpe_dome_hotel
//"Database": "iuaY0h0+TWkir44/eZLDqw==", //tpe_dome_office
"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //MCUT
//"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //MCUT
"Root": "SzdxEgaJJ7tcTCrUl2zKsA==",
"Password": "FVAPxztxpY4gJJKQ/se4bQ=="
}

View File

@ -13,6 +13,7 @@ using System.Data.SqlTypes;
using Microsoft.Extensions.Primitives;
using System.Web;
using Org.BouncyCastle.Utilities.Collections;
using System.Reflection;
namespace Repository.BackendRepository.Implement
{
@ -56,7 +57,7 @@ namespace Repository.BackendRepository.Implement
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
await conn.ExecuteAsync(sql);
sql = "delete from import_niagara_tag where device_building_tag = '" + b + "'";
sql = "delete from import_niagara_tag where device_building_tag = '" + b + "' limit 10000";
await conn.ExecuteAsync(sql);
}
@ -199,7 +200,7 @@ namespace Repository.BackendRepository.Implement
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
await conn.ExecuteAsync(sql);
sql = "delete from import_niagara_item where device_building_tag = '" + b + "'";
sql = "delete from import_niagara_item where device_building_tag = '" + b + "' limit 10000;";
await conn.ExecuteAsync(sql);
}
#endregion
@ -279,18 +280,20 @@ namespace Repository.BackendRepository.Implement
using (IDbConnection conn = GetDbConnection())
{
conn.Open();
using (TransactionScope scope = new TransactionScope((TransactionScopeOption)TransactionScopeAsyncFlowOption.Enabled, new TimeSpan(0, 0, 200)))
using (TransactionScope scope = new TransactionScope((TransactionScopeOption)TransactionScopeAsyncFlowOption.Enabled))
{
try
{
List<NiagaraTags> result;
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
sb.Append($@" SELECT m.*
FROM import_niagara_tag m
LEFT JOIN device d
ON m.niagara_tags = d.device_number
WHERE d.device_number IS NULL");
sb.Append($@"SELECT m.*
FROM import_niagara_tag m
WHERE NOT EXISTS (
SELECT 1
FROM device d
WHERE m.niagara_tags = d.device_number
);");
result = (await conn.QueryAsync<NiagaraTags>(sb.ToString())).ToList<NiagaraTags>();
sb.Clear();
@ -365,9 +368,13 @@ namespace Repository.BackendRepository.Implement
#endregion
#region device_node
sb.Append($@" SELECT m.* FROM import_niagara_tag m
LEFT JOIN device_node d ON m.niagara_tags = d.device_number
WHERE d.device_number IS NULL");
sb.Append($@" SELECT m.*
FROM import_niagara_tag m
WHERE NOT EXISTS (
SELECT 1
FROM device_node d
WHERE m.niagara_tags = d.device_number
);");
result = (await conn.QueryAsync<NiagaraTags>(sb.ToString())).ToList<NiagaraTags>();
sb.Clear();
@ -409,19 +416,19 @@ namespace Repository.BackendRepository.Implement
//device有niagara沒有is_link 更新成 0
sb.Append($@" SET SQL_SAFE_UPDATES = 0;
UPDATE device d
SET d.is_link = 0
WHERE d.is_link = 1 and not exists (select niagara_tags from import_niagara_tag where niagara_tags = d.device_number);");
await conn.ExecuteAsync(sb.ToString(), commandTimeout: 100);
UPDATE device
SET is_link = 0
WHERE is_link = 1 AND device_number NOT IN (SELECT niagara_tags FROM import_niagara_tag);");
await conn.ExecuteAsync(sb.ToString());
sb.Clear();
// device_node 有, niagara沒有, is_link 更新成 0
sb.Append($@" SET SQL_SAFE_UPDATES = 0;
UPDATE device_node d
SET d.is_link = 0
WHERE d.is_link = 1 and not exists (select niagara_tags from import_niagara_tag where niagara_tags = d.device_number);");
await conn.ExecuteAsync(sb.ToString(), commandTimeout: 100);
UPDATE device_node
SET is_link = 0
WHERE is_link = 1 AND device_number NOT IN (SELECT niagara_tags FROM import_niagara_tag);");
await conn.ExecuteAsync(sb.ToString());
}
catch (Exception exception)
{
@ -453,8 +460,8 @@ namespace Repository.BackendRepository.Implement
sb.Append($@" SELECT m.*
FROM import_niagara_item m
LEFT JOIN device_item d
ON m.device_system_tag = d.device_system_tag and m.device_name_tag = d.device_name_tag and m.device_point_name = d.points
WHERE d.points IS NULL");
ON m.device_system_tag = d.device_system_tag and m.device_name_tag = d.device_name_tag and m.device_point_name = d.points and m.device_building_tag collate utf8mb4_0900_ai_ci = d.device_building_tag
WHERE d.points IS NULL;");
result = (await conn.QueryAsync<NiagaraTagsForItem>(sb.ToString())).ToList<NiagaraTagsForItem>();
sb.Clear();
@ -581,14 +588,12 @@ namespace Repository.BackendRepository.Implement
#region insert building_menu
if (bm.Count == 0)
{
sb.Append(@"insert building_menu(building_tag, main_system_tag, sub_system_tag, device_building_tag, device_system_tag,
sb.Append(@$"insert building_menu(building_tag, main_system_tag, sub_system_tag, device_building_tag, device_system_tag,
left_drawing, left_icon_click, left_icon_click_url_width, left_icon_click_url_height, left_planimetric_click,
is_link, created_by, created_at, updated_by, updated_at)
VALUES ('" + data.device_building_tag + "', '" +
data.device_system_tag + "', '" +
data.device_name_tag + "', '" +
data.device_building_tag + "', '" +
data.device_system_tag + "', " +
"1, 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now(), 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now() );");
values('{data.device_building_tag}', '{data.device_system_tag}', '{data.device_name_tag}', '{data.device_building_tag}', '{data.device_system_tag}',
4, 1, 0, 0, 1,
1, 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now(), 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now());");
}
#endregion
}
@ -769,10 +774,16 @@ namespace Repository.BackendRepository.Implement
try
{
StringBuilder sb = new StringBuilder();
sb.Append("update device d inner JOIN import_niagara_tag m ON m.niagara_tags = d.device_number " +
"set d.full_name=m.device_full_name " +
"where m.device_full_name<>d.full_name;");
await conn.ExecuteAsync(sb.ToString(), commandTimeout: 200);
sb.Append(@"UPDATE device d
INNER JOIN import_niagara_tag m ON m.niagara_tags = d.device_number
SET d.full_name = m.device_full_name
WHERE NOT EXISTS (
SELECT 1
FROM import_niagara_tag m2
WHERE m2.niagara_tags = d.device_number
AND m2.device_full_name = d.full_name
);");
await conn.ExecuteAsync(sb.ToString());
}
catch (Exception exception)
{
@ -865,43 +876,155 @@ namespace Repository.BackendRepository.Implement
using (IDbConnection conn = GetDbConnection())
{
conn.Open();
using (TransactionScope scope = new TransactionScope((TransactionScopeOption)TransactionScopeAsyncFlowOption.Enabled, new TimeSpan(0, 5, 0)))
StringBuilder sb = new StringBuilder();
List<DeviceDisasterOutput> deviceDisaster = new List<DeviceDisasterOutput>();
List<DeviceDisasterOutput> device = new List<DeviceDisasterOutput>();
using (TransactionScope scope = new TransactionScope((TransactionScopeOption)TransactionScopeAsyncFlowOption.Enabled))
{
try
{
StringBuilder sb = new StringBuilder();
sb.Append("select * from device_disaster;");
var deviceDisaster = (await conn.QueryAsync<DeviceDisasterOutput>(sb.ToString())).ToList();
deviceDisaster = (await conn.QueryAsync<DeviceDisasterOutput>(sb.ToString())).ToList();
sb.Clear();
sb.Append("select * from device where deleted = 0;");
var device = (await conn.QueryAsync<DeviceDisasterOutput>(sb.ToString())).ToList();
dv = dv.Where(x => device.Any(d => d.device_number == x.value.Split('/')[6])).ToList();
device = (await conn.QueryAsync<DeviceDisasterOutput>(sb.ToString())).ToList();
}
catch (Exception exception)
{
throw exception;
}
finally
{
conn.Close();
}
}
sb.Clear();
var updateList = dv.Where(x => deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6] && dd.device_system_value != x.disasterValue));
foreach (var d in updateList)
{
string device_number = d.value.Split('/')[6];
sb.Append($"update device_disaster set device_system_value = '{d.disasterValue}' where device_number = '{device_number}'; ");
}
dv = dv.Where(x => device.Any(d => d.device_number == x.value.Split('/')[6])).ToList();
sb.Clear();
var updateList = dv.Where(x => deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6] && dd.device_system_value != x.disasterValue)).ToList();
foreach (var d in updateList)
{
string device_number = d.value.Split('/')[6];
sb.Append($"update device_disaster set device_system_value = '{d.disasterValue}' where device_number = '{device_number}'; ");
}
var insertList = dv.Where(x => !deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6]));
foreach (var d in insertList)
{
string device_number = d.value.Split('/')[6];
string device_guid = device.Where(x => x.device_number == device_number).Select(x => x.device_guid).FirstOrDefault();
string device_system_tag = device.Where(x => x.device_number == device_number).Select(x => x.device_system_tag).FirstOrDefault();
string device_name_tag = device.Where(x => x.device_number == device_number).Select(x => x.device_name_tag).FirstOrDefault();
sb.Append($@"
var insertList = dv.Where(x => !deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6])).ToList();
foreach (var d in insertList)
{
string device_number = d.value.Split('/')[6];
string device_guid = device.Where(x => x.device_number == device_number).Select(x => x.device_guid).FirstOrDefault();
string device_system_tag = device.Where(x => x.device_number == device_number).Select(x => x.device_system_tag).FirstOrDefault();
string device_name_tag = device.Where(x => x.device_number == device_number).Select(x => x.device_name_tag).FirstOrDefault();
sb.Append($@"
insert into device_disaster
(device_guid, device_system_value, device_building_tag, device_system_tag, device_name_tag, device_floor_tag, device_serial_tag, device_number)
values ('{device_guid}', '{d.disasterValue}', '{device_number.Split('_')[0]}', '{device_system_tag}', '{device_name_tag}', '{device_number.Split('_')[2]}',
'{device_number.Split('_')[4]}', '{device_number}'); ");
}
}
using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
try
{
if (!string.IsNullOrEmpty(sb.ToString()))
await conn.ExecuteAsync(sb.ToString());
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
}
}
/// <summary>
/// InsertFloor
/// </summary>
/// <returns></returns>
public async Task InsertFloor()
{
using (IDbConnection conn = GetDbConnection())
{
conn.Open();
using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
try
{
List<NiagaraTags> result;
StringBuilder sb = new StringBuilder();
#region comparison floor and sub_system_floor
sb.Append($@" select tag.*
from (
select device_building_tag, device_floor_tag
from import_niagara_tag
group by device_building_tag, device_floor_tag
) AS tag
LEFT JOIN floor f
ON tag.device_building_tag = f.building_tag and tag.device_floor_tag = f.full_name and f.deleted = 0
WHERE f.building_tag IS NULL;");
result = (await conn.QueryAsync<NiagaraTags>(sb.ToString())).ToList<NiagaraTags>();
#endregion
sb.Clear();
#region insert floor
if (result.Count > 0)
{
Dictionary<string, int> floorPriority = new Dictionary<string, int>();
foreach (var data in result)
{
FloorPriority fp = (await conn.QueryAsync<FloorPriority>($@"select building_tag, max(priority) as priority from floor
where building_tag = '{data.device_building_tag}' and deleted = 0 group by building_tag;")).FirstOrDefault();
int priority = 0;
if (fp == null && floorPriority.GetValueOrDefault(data.device_building_tag) == 0)
floorPriority.Add(data.device_building_tag, 0);
else if (fp != null && floorPriority.GetValueOrDefault(fp.building_tag) == 0)
floorPriority.Add(fp.building_tag, fp.Priority);
priority = ++floorPriority[data.device_building_tag];
sb.Append($@"insert into floor(floor_guid, building_tag, deleted, status, full_name, priority, created_by, created_at)
VALUES (uuid(), '{data.device_building_tag}', 0, 1, '{data.device_floor_tag}', {priority}, 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now());");
}
if (sb.Length > 0)
{
await conn.ExecuteAsync(sb.ToString());
sb.Clear();
}
}
#endregion
#region update unuse floor with niagara data
var floor = (await conn.QueryAsync<BuildFloor>($@"select f1.*
from floor as f1
left join (
select f.floor_guid
from (
select device_building_tag, device_floor_tag
from import_niagara_tag
group by device_building_tag, device_floor_tag
) AS tag
LEFT JOIN floor f
ON tag.device_building_tag = f.building_tag and tag.device_floor_tag = f.full_name and f.deleted = 0
) as f2 on f1.floor_guid = f2.floor_guid
where f2.floor_guid is null and f1.deleted = 0;")).ToList<BuildFloor>();
if (floor.Count > 0)
{
sb.Clear();
foreach (var f in floor)
{
sb.Append($"update floor set deleted = 1 where floor_guid = '{f.Floor_guid}';");
}
await conn.ExecuteAsync(sb.ToString());
}
#endregion
}
catch (Exception exception)
{
throw exception;

View File

@ -71,5 +71,10 @@ namespace Repository.BackendRepository.Interface
/// <returns></returns>
Task InsertSubSystemFloor();
Task DeviceDisasterAysnc(List<Device_value_disaster> dv);
/// <summary>
/// InsertFloor
/// </summary>
/// <returns></returns>
Task InsertFloor();
}
}

View File

@ -65,5 +65,6 @@ namespace Repository.Models
{
public string Floor_guid { get; set; } //樓層GUID
public int Priority { get; set; }
public string building_tag { get; set; }
}
}