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.CheckFullNameEmptyReplaceByDeviceName();
await niagaraDataSynchronizeRepository.InsertBuildingMenu(); await niagaraDataSynchronizeRepository.InsertBuildingMenu();
await niagaraDataSynchronizeRepository.InsertSubSystemFloor(); await niagaraDataSynchronizeRepository.InsertSubSystemFloor();
await niagaraDataSynchronizeRepository.InsertFloor();
await this.DeviceDisasterAsync(); await this.DeviceDisasterAsync();
result = true; result = true;

View File

@ -4,23 +4,9 @@ using System.Linq;
using System.Xml; using System.Xml;
using Newtonsoft.Json; using Newtonsoft.Json;
using Repository.Models; using Repository.Models;
using Newtonsoft.Json.Linq;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Text;
using System.Xml.Linq; 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 namespace Backend.Services.Implement
{ {
@ -151,6 +137,7 @@ namespace Backend.Services.Implement
#region get control point data #region get control point data
List<control_point> conPoint = new List<control_point>(); List<control_point> conPoint = new List<control_point>();
String cp_API_Url = bqlUrlString; 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); HttpWebRequest cp_Postrequest = (HttpWebRequest)WebRequest.Create(cp_API_Url);
cp_Postrequest.Method = "POST"; cp_Postrequest.Method = "POST";
@ -220,8 +207,14 @@ namespace Backend.Services.Implement
XmlDocument xmlDoc2 = new XmlDocument(); XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.LoadXml(responseString2); 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; string tagName = node2.Attributes["name"].InnerText;
if (tagName.Split('_').Length == 9) if (tagName.Split('_').Length == 9)
@ -241,8 +234,8 @@ namespace Backend.Services.Implement
row.isHistory = true; row.isHistory = true;
result.Add(row); result.Add(row);
}
} else if (tagName.Split('_').Length == 6) else if (tagName.Split('_').Length == 6)
{ //巨蛋 tag 5 段版本 { //巨蛋 tag 5 段版本
ImpNiaItem row = new ImpNiaItem(); ImpNiaItem row = new ImpNiaItem();
if (tagName.Split('_')[1] == "S") //for security system if (tagName.Split('_')[1] == "S") //for security system

View File

@ -762,11 +762,14 @@
return; return;
} }
else { else {
$('#floor-modal').modal();
$("#BuildName").html(selected_build_guid_top_name); $("#BuildName").html(selected_build_guid_top_name);
$("#floor_name_modal").val(rel.data.full_name); $("#floor_name_modal").val(rel.data.full_name);
@*$("#map_file_preview_modal").attr("data-original", rel.data.mapUrl);*@ if (rel.data.mapUrl)
loadURLToInputFiled(rel.data.mapUrl, rel.data.initMapName + ".svg");
$('#floor-modal').modal(); else
$('#floor_map_file_modal')[0].value = "";
} }
}, 'json'); }, 'json');
}); });
@ -977,6 +980,27 @@
} }
//#endregion //#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> </script>
} }

View File

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

View File

@ -27,6 +27,11 @@
</head> </head>
<body class="mod-bg-1 mod-nav-link"> <body class="mod-bg-1 mod-nav-link">
<!-- BEGIN Page Wrapper --> <!-- 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-wrapper">
<div class="page-inner"> <div class="page-inner">
<!-- BEGIN Left Aside --> <!-- 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>
<th>功能名稱</th> <th>功能名稱</th>
<th>功能細項名稱</th> <th>功能細項名稱</th>
<th>建立時間</th> <th>建立時間</th>

View File

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

View File

@ -47,3 +47,34 @@ label.error {
.t-gray { .t-gray {
color:var(--bims-gray) !important; 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 () { $(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) public async Task Execute(IJobExecutionContext context)
{ {
Task_Detail task_Detail = new Task_Detail(loggers, backgroundServiceRepository); Task_Detail task_Detail = new Task_Detail(loggers, backgroundServiceRepository);
string device_number = string.Empty;
try try
{ {
if(await task_Detail.GetNeedWorkTask("ArchiveElectricMeterDayJob", "All")) 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>>(); List<Dictionary<string, object>> waterArchiveDayRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints) foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{ {
device_number = deviceNumberPoint.FullDeviceNumberPoint;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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/"); //HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -216,8 +217,8 @@ namespace BackendWorkerService.Quartz.Jobs
} }
foreach (var deviceNumberPoint in waterDeviceNumberPoints) foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{ {
device_number = deviceNumberPoint.FullDeviceNumberPoint;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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/"); //HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -628,7 +629,8 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveWeekRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> waterArchiveWeekRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints) 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/"); //HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -685,7 +687,8 @@ namespace BackendWorkerService.Quartz.Jobs
} }
foreach (var deviceNumberPoint in waterDeviceNumberPoints) 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/"); //HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -993,7 +996,8 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveMonthRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> waterArchiveMonthRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints) 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/"); //HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -1049,7 +1053,8 @@ namespace BackendWorkerService.Quartz.Jobs
} }
foreach (var deviceNumberPoint in waterDeviceNumberPoints) 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/"); //HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -1337,8 +1342,6 @@ namespace BackendWorkerService.Quartz.Jobs
catch(Exception ex) catch(Exception ex)
{ {
await task_Detail.WorkFail("ArchiveElectricMeterDayJob", "Compensate", ex.ToString()); await task_Detail.WorkFail("ArchiveElectricMeterDayJob", "Compensate", ex.ToString());
logger.LogError("【ArchiveElectricMeterDayJob】【補償機制】【任務失敗】");
logger.LogError("【ArchiveElectricMeterDayJob】【補償機制】【任務失敗】[Exception]{0}", ex.ToString());
} }
} }
#endregion #endregion
@ -1350,17 +1353,19 @@ namespace BackendWorkerService.Quartz.Jobs
{ {
await task_Detail.WorkFail("ArchiveElectricMeterDayJob", "All", exception.ToString()); await task_Detail.WorkFail("ArchiveElectricMeterDayJob", "All", exception.ToString());
logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】"); 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) private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult)
{ {
List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>();
try
{
var histories = jsonResult["obj"]["list"]; var histories = jsonResult["obj"]["list"];
var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString()); var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
if(rawdateCount == 0) if (rawdateCount == 0)
{ {
return null; return null;
} }
@ -1508,5 +1513,10 @@ namespace BackendWorkerService.Quartz.Jobs
return arrangeRawDatas; return arrangeRawDatas;
} }
catch (Exception ex)
{
return arrangeRawDatas;
}
}
} }
} }

View File

@ -786,6 +786,7 @@ namespace BackendWorkerService.Services.Implement
} }
catch (Exception exception) catch (Exception exception)
{ {
throw exception; throw exception;
} }
@ -795,6 +796,8 @@ namespace BackendWorkerService.Services.Implement
private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult) private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult)
{ {
List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>();
try
{
var histories = jsonResult["obj"]["list"]; var histories = jsonResult["obj"]["list"];
var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString()); var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
@ -849,15 +852,15 @@ namespace BackendWorkerService.Services.Implement
switch (name) switch (name)
{ {
case "min": 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); arrangeRawData.Add("@min_rawdata", min);
break; break;
case "max": 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); arrangeRawData.Add("@max_rawdata", max);
break; break;
case "avg": 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); arrangeRawData.Add("@avg_rawdata", avg);
break; break;
case "sum": case "sum":
@ -917,15 +920,15 @@ namespace BackendWorkerService.Services.Implement
switch (name) switch (name)
{ {
case "min": 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); arrangeRawData.Add("@min_rawdata", min);
break; break;
case "max": 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); arrangeRawData.Add("@max_rawdata", max);
break; break;
case "avg": 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); arrangeRawData.Add("@avg_rawdata", avg);
break; break;
case "sum": case "sum":
@ -947,5 +950,10 @@ namespace BackendWorkerService.Services.Implement
return arrangeRawDatas; return arrangeRawDatas;
} }
catch (Exception ex)
{
return arrangeRawDatas;
}
}
} }
} }

View File

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

View File

@ -70,6 +70,7 @@
<script> <script>
var historyTable = null; var historyTable = null;
hisFirst = true;
$(function () { $(function () {
initList(); initList();
@ -250,24 +251,40 @@
pageAct.deviceItem = val.points; pageAct.deviceItem = val.points;
pageAct.devicePoiName = val.full_name + ' ' + val.points; pageAct.devicePoiName = val.full_name + ' ' + val.points;
pageAct.deviceComName = val.parent_path; pageAct.deviceComName = val.parent_path;
getData();
} else { } 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>`; 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); $('#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(); ytAjax = new YourTeam.Ajax(url, objSendData, success, null, "POST").send();
} }
function getData(start = null, end = null) { function getData(start = null, end = null) {
$(loadEle).Loading("start");
var sdt = new Date(); var sdt = new Date();
var edt = new Date(new Date().setDate(sdt.getDate() + 1)); var edt = new Date(new Date().setDate(sdt.getDate() + 1));
$(loadEle).Loading("start");
start = start ?? sdt.toLocaleDateString(); start = start ?? sdt.toLocaleDateString();
end = end ?? edt.toLocaleDateString(); end = end ?? edt.toLocaleDateString();
callBackFromHistory() // callBackFromHistory();
getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem, getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem,
new Date(start).getTime(), new Date(start).getTime(),
new Date(end).getTime(), new Date(end).getTime(),
@ -277,21 +294,18 @@
} }
function callBackFromHistory(res = '{"count":0,"data":[]}') { function callBackFromHistory(res = '{"count":0,"data":[]}') {
// console.log("@H1",res)
res = JSON.parse(res); res = JSON.parse(res);
// console.log("@history",res.data)
loadTable(res.data); loadTable(res.data);
if (historyTable != null) { if (historyTable != null) {
let t = $('#historyTable').dataTable(); let t = $('#historyTable').dataTable();
t.fnClearTable(); t.fnClearTable();
if (res.data.length > 0) if (res.data.length > 0)
t.fnAddData(res.data); t.fnAddData(res.data);
} }
$(loadEle).Loading("close");
} }
function setValue(deviceNumber, deviceName, deviceItem, elem) { function setValue(deviceNumber, deviceName, deviceItem, elem) {
hisFirst = false;
btnSelCss(elem); btnSelCss(elem);
if ((deviceNumber != null && deviceNumber != undefined) && (deviceName != null && deviceName != undefined)) { if ((deviceNumber != null && deviceNumber != undefined) && (deviceName != null && deviceName != undefined)) {
@ -302,7 +316,20 @@
else if (deviceItem != null && deviceItem != undefined) { else if (deviceItem != null && deviceItem != undefined) {
pageAct.devicePoiName = $(elem).text(); pageAct.devicePoiName = $(elem).text();
pageAct.deviceItem = deviceItem; 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));
} }
} }
@ -364,14 +391,16 @@
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1)); 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") if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd")
end = new Date(new Date().setDate(start.getDate() + 1)); end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") { else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val()); start = new Date($('#getmonth').val());
end = new Date(new Date().setDate(start.getDate() + 30)); end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 30));
} }
else if (pageAct.dateType != "range") else if (pageAct.dateType != "range")
return; return;
pageAct.hisStartDate = start;
pageAct.hisEndDate = end;
getData(formatDate(start, "date", true), formatDate(end, "date", true)); getData(formatDate(start, "date", true), formatDate(end, "date", true));
} }
@ -390,7 +419,6 @@
function loadTable(data) { function loadTable(data) {
if (data) { if (data) {
$.each(data, function (i, v) { $.each(data, function (i, v) {
// console.log("loadTable",pageAct.devicePoiName.split(" ")[0])
v.type = pageAct.devicePoiName.split(" ")[0]; v.type = pageAct.devicePoiName.split(" ")[0];
}); });
@ -425,31 +453,61 @@
"title": "紀錄時間", "title": "紀錄時間",
"data": "timestamp", "data": "timestamp",
"render": function (data) { "render": function (data) {
// console.log(data)
return displayDate(data, "datetime"); return displayDate(data, "datetime");
} }
} }
]; ];
historyTable = new YourTeam.JqDataTables.getTableByStatic(tag, data, columns, column_defs, null, null, null, null, "tpi"); historyTable = new YourTeam.JqDataTables.getTableByStatic(tag, data, columns, column_defs, null, null, null, null, "tpi");
$(tag).DataTable().order([3, 'desc']);
} }
} }
function exportExcel() { function exportExcel() {
$(loadEle).Loading("start"); $(loadEle).Loading("start");
let url = baseApiUrl + "/History/OpeExportExcel"; let token = cookies.get("JWT-Authorization");
objSendData.Data = $('#historyTable').dataTable().fnGetData(); let url = baseApiUrl + "/api/ExportHistory";
let v = {};
$.each(objSendData.Data, function (i, v) { v.starttime = pageAct.hisStartDate;
v.starttime = (pageAct.dateType == "month" ? new Date($('#getmonth').val()) : new Date($('#his_startdate').val())); v.endtime = pageAct.hisEndDate;
v.endtime = $('#his_enddate input').val() === "" ? null : new Date($('#his_enddate input').val());
v.dateType = pageAct.dateType; v.dateType = pageAct.dateType;
}); v.device_number = pageAct.deviceNumber;
ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) { objSendData.Data = v;
if (rel.code == "0000") {
location.href = baseApiUrl + "/api/df?path=" + rel.data.split('/')[0] + "&fileName=" + rel.data.split('/')[1] + "&token=" + cookies.get("JWT-Authorization"); $.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);
} }
}, null, "POST").send();
$(loadEle).Loading("close"); $(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> </script>

View File

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

View File

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

View File

@ -1652,3 +1652,36 @@ function btnSelCss(elem) {
$(elem).removeClass('btn-secondary'); $(elem).removeClass('btn-secondary');
$(elem).addClass('btn-info'); $(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_key subfull_name,
v2.system_priority subpriority v2.system_priority subpriority
from building_menu me 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 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' 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 ( inner join (
@ -257,7 +257,7 @@ namespace FrontendWebApi.ApiControllers
string name = sub.Select(s => s.subfull_name).FirstOrDefault(); string name = sub.Select(s => s.subfull_name).FirstOrDefault();
bool check = true; bool check = true;
if (name == "人流計數") 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) if (check)
{ {
@ -580,7 +580,7 @@ namespace FrontendWebApi.ApiControllers
{disasterjoinsql} {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 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} 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); var devicelist = await backendRepository.GetAllAsync<DeviceFloor>(sql);

View File

@ -107,7 +107,7 @@ namespace FrontendWebApi.ApiControllers
[HttpPost] [HttpPost]
[Route("api/EmergencyContact/PDF")] [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); //var grouping = JsonConvert.DeserializeObject<export>(post);
ApiResult<string> apiResult = new ApiResult<string>(); ApiResult<string> apiResult = new ApiResult<string>();
@ -182,7 +182,7 @@ namespace FrontendWebApi.ApiControllers
[HttpPost] [HttpPost]
[Route("api/EmergencyContact/Excel")] [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(); //var guid = Guid.NewGuid().ToString();
ApiResult<string> apiResult = new ApiResult<string>(); ApiResult<string> apiResult = new ApiResult<string>();

View File

@ -16,10 +16,6 @@ using System.Threading.Tasks;
using System.Xml; using System.Xml;
using NPOI.XSSF.UserModel; using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel; using NPOI.SS.UserModel;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.HPSF;
using Google.Protobuf.WellKnownTypes;
namespace FrontendWebApi.ApiControllers namespace FrontendWebApi.ApiControllers
{ {
@ -47,29 +43,91 @@ namespace FrontendWebApi.ApiControllers
/// <param name="lhe"></param> /// <param name="lhe"></param>
/// <returns></returns> /// <returns></returns>
[HttpPost] [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>(); ApiResult<string> apiResult = new ApiResult<string>();
if (lhe == null) //if (lhe == null)
{ //{
apiResult.Code = "0001"; // apiResult.Code = "0001";
apiResult.Msg = "沒有資料匯入"; // apiResult.Msg = "沒有資料匯入";
return apiResult; // 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 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"); #region obix
var fileName = "歷史資料_"+fileDateName+".xlsx"; EDFunction ed = new EDFunction();
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "excel", "history"); 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)) List<HistoryExport> he = new List<HistoryExport>();
System.IO.Directory.CreateDirectory(filePath);
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(); reqStream.Write(byteArray, 0, byteArray.Length);
}
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設定 #region excel設定
IFont font12 = workbook.CreateFont(); IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體"; font12.FontName = "新細明體";
@ -133,9 +191,7 @@ namespace FrontendWebApi.ApiControllers
cell.CellStyle = styleLine12; cell.CellStyle = styleLine12;
#endregion #endregion
if (lhe.Count > 0) foreach (var d in he)
{
foreach (var he in lhe)
{ {
RowPosition += 1; RowPosition += 1;
row = sheet.CreateRow(RowPosition); row = sheet.CreateRow(RowPosition);
@ -144,40 +200,42 @@ namespace FrontendWebApi.ApiControllers
cell = row.CreateCell(i); cell = row.CreateCell(i);
if (i == 0) if (i == 0)
{ {
cell.SetCellValue(he.type); cell.SetCellValue(d.type);
} }
if (i == 1) if (i == 1)
{ {
cell.SetCellValue(he.deviceName); cell.SetCellValue(d.deviceName);
} }
if (i == 2) if (i == 2)
{ {
cell.SetCellValue(he.value); cell.SetCellValue(d.value);
} }
if (i == 3) if (i == 3)
{ {
cell.SetCellValue(he.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");// cell.SetCellValue(d.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
} }
cell.CellStyle = style12; cell.CellStyle = style12;
} }
} }
} }
workbook.Write(fs);
}
apiResult.Code = "0000";
apiResult.Data = "history/" + fileName;
}
catch (Exception exception) catch (Exception exception)
{ {
apiResult.Code = "9999"; apiResult.Code = "9999";
apiResult.Msg = "系統內部錯誤,請聯絡管理者。 Msg: " + exception.Message; apiResult.Msg = "系統內部錯誤,請聯絡管理者。 Msg: " + exception.Message;
Logger.LogError("【" + controllerName + "/" + actionName + "】" + 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> /// <summary>
@ -1204,5 +1262,167 @@ namespace FrontendWebApi.ApiControllers
} }
return Ok(apiResult); 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 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 aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date";
var sql = $@"set @i = -1; 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 ( from (
select * select *
from ( from (
@ -161,7 +161,7 @@ namespace FrontendWebApi.ApiControllers
foreach (var l in list) foreach (var l in list)
{ {
l.rawData = new List<HydroMeterRawDataOutput>(); 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") if (tag_quantity == "5")
{ {
l.rawData.AddRange( 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", 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 }); 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 l.price = input.price.HasValue
? (Math.Round(input.price.Value, 2)).ToString() ? (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(); : 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 == "month" ? (Int32.Parse(input.startTime.Split("-")[0]) + 1) + "-01-01"
: input.tableType == "year" ? (Int32.Parse(input.endTime) + 1).ToString() + "-01-01" : input.tableType == "year" ? (Int32.Parse(input.endTime) + 1).ToString() + "-01-01"
: null; : null;
string dbDateName = startTime.Split("-")[0].ToString().PadLeft(4, '0') + startTime.Split("-")[1].ToString().PadLeft(2, '0');
string sqlWhere = ""; string sqlWhere = "";
string sqlGroup = ""; string sqlGroup = "";
string sqlAvgRawData = ""; string sqlAvgRawData = "";
string dbDateName = startTime.Split("-")[0].ToString().PadLeft(4, '0') + startTime.Split("-")[1].ToString().PadLeft(2, '0');
string buildingSql = ""; 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"); 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 else
sqlAvgRawData = " round(avg_rawdata, 2) as avg_rawdata, start_timestamp, end_timestamp "; 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 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]}'"); 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 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 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 aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date";
var sql = $@"set @i = -1; 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 ( from (
select * select *
from ( from (
@ -307,9 +307,9 @@ namespace FrontendWebApi.ApiControllers
left join ( left join (
select device_number, {sqlAvgRawData} select device_number, {sqlAvgRawData}
from {table} 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} {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"; order by fd.device_number, fd.date";
var rawData = await backendRepository.GetAllAsync<HydroMeterRawDataOutput>(sql, var rawData = await backendRepository.GetAllAsync<HydroMeterRawDataOutput>(sql,
@ -334,7 +334,7 @@ namespace FrontendWebApi.ApiControllers
foreach (var l in list) foreach (var l in list)
{ {
l.rawData = new List<HydroMeterRawDataOutput>(); 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") if (tag_quantity == "5")
{ {
l.rawData.AddRange( 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", 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 }); 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 l.price = input.price.HasValue
? (Math.Round(input.price.Value, 2)).ToString() ? (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(); : 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"); Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
return File(ms, "application/vnd.ms-excel", "電表報表.xlsx"); 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) public static int GetDayInMonth(string yearMonth)
{ {
List<string> datesList = new List<string>(); List<string> datesList = new List<string>();

View File

@ -289,13 +289,41 @@ namespace FrontendWebApi.Models
public class HistoryExport public class HistoryExport
{ {
public string deviceName { get; set; } public string deviceName { get; set; }
public double value { get; set; } public string value { get; set; }
public DateTime timestamp { get; set; } public DateTime timestamp { get; set; }
public DateTime starttime { get; set; } public DateTime starttime { get; set; }
public DateTime? endtime { get; set; } public DateTime? endtime { get; set; }
public string dateType { get; set; } public string dateType { get; set; }
public string type { 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 timeStamp { get; set; }
public string device_number { get; set; } public string device_number { get; set; }
public decimal avg_rawdata { get; set; } public string avg_rawdata { get; set; }
} }
public class HydroMeterPriceInput public class HydroMeterPriceInput

View File

@ -32,8 +32,6 @@
</div> </div>
<div class="pr-3 row col"> <div class="pr-3 row col">
<div class="frame-wrap" id="groupinglist"> <div class="frame-wrap" id="groupinglist">
</div> </div>
</div> </div>
<div class="card border mb-g w-100 mb-5" id="emergency_setting_card"> <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")) { if ($(e).hasClass("btn-outline-success")) {
$(e).removeClass("btn-outline-success").addClass("btn-success"); $(e).removeClass("btn-outline-success").addClass("btn-success");
selectgroupidlist.push(grouping); selectgroupidlist.push(grouping);
@ -218,8 +215,7 @@
} }
//全選所有組別 //全選所有組別
function Allgroupingselect() function Allgroupingselect() {
{
if (Allgroupingbool) { if (Allgroupingbool) {
$('#groupinglist').find(".btn-success").removeClass("btn-success").addClass("btn-outline-success"); $('#groupinglist').find(".btn-success").removeClass("btn-success").addClass("btn-outline-success");
selectgroupidlist = []; selectgroupidlist = [];
@ -249,7 +245,27 @@
disaster: $('#Disasterlist').find('.btn-success').html(), disaster: $('#Disasterlist').find('.btn-success').html(),
groupidlist: selectgroupidlist 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(), disaster: $('#Disasterlist').find('.btn-success').html(),
groupidlist: selectgroupidlist 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==", "Port": "js2LutKe+rdjzdxMPQUrvQ==",
//"Database": "VJB2XC+lAtzuHObDGMVOAA==", //30 //"Database": "VJB2XC+lAtzuHObDGMVOAA==", //30
//"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp //"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp
//"Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome "Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome
//"Database": "siTUcDaC/g2yGTMFWD72Kg==", //tpe_dome_hotel //"Database": "siTUcDaC/g2yGTMFWD72Kg==", //tpe_dome_hotel
//"Database": "iuaY0h0+TWkir44/eZLDqw==", //tpe_dome_office //"Database": "iuaY0h0+TWkir44/eZLDqw==", //tpe_dome_office
"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //MCUT //"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //MCUT
"Root": "SzdxEgaJJ7tcTCrUl2zKsA==", "Root": "SzdxEgaJJ7tcTCrUl2zKsA==",
"Password": "FVAPxztxpY4gJJKQ/se4bQ==" "Password": "FVAPxztxpY4gJJKQ/se4bQ=="
} }

View File

@ -13,6 +13,7 @@ using System.Data.SqlTypes;
using Microsoft.Extensions.Primitives; using Microsoft.Extensions.Primitives;
using System.Web; using System.Web;
using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Collections;
using System.Reflection;
namespace Repository.BackendRepository.Implement namespace Repository.BackendRepository.Implement
{ {
@ -56,7 +57,7 @@ namespace Repository.BackendRepository.Implement
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
await conn.ExecuteAsync(sql); 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); await conn.ExecuteAsync(sql);
} }
@ -199,7 +200,7 @@ namespace Repository.BackendRepository.Implement
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"; ) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
await conn.ExecuteAsync(sql); 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); await conn.ExecuteAsync(sql);
} }
#endregion #endregion
@ -279,18 +280,20 @@ namespace Repository.BackendRepository.Implement
using (IDbConnection conn = GetDbConnection()) using (IDbConnection conn = GetDbConnection())
{ {
conn.Open(); conn.Open();
using (TransactionScope scope = new TransactionScope((TransactionScopeOption)TransactionScopeAsyncFlowOption.Enabled, new TimeSpan(0, 0, 200))) using (TransactionScope scope = new TransactionScope((TransactionScopeOption)TransactionScopeAsyncFlowOption.Enabled))
{ {
try try
{ {
List<NiagaraTags> result; List<NiagaraTags> result;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder(); StringBuilder sb2 = new StringBuilder();
sb.Append($@" SELECT m.* sb.Append($@"SELECT m.*
FROM import_niagara_tag m FROM import_niagara_tag m
LEFT JOIN device d WHERE NOT EXISTS (
ON m.niagara_tags = d.device_number SELECT 1
WHERE d.device_number IS NULL"); FROM device d
WHERE m.niagara_tags = d.device_number
);");
result = (await conn.QueryAsync<NiagaraTags>(sb.ToString())).ToList<NiagaraTags>(); result = (await conn.QueryAsync<NiagaraTags>(sb.ToString())).ToList<NiagaraTags>();
sb.Clear(); sb.Clear();
@ -365,9 +368,13 @@ namespace Repository.BackendRepository.Implement
#endregion #endregion
#region device_node #region device_node
sb.Append($@" SELECT m.* FROM import_niagara_tag m sb.Append($@" SELECT m.*
LEFT JOIN device_node d ON m.niagara_tags = d.device_number FROM import_niagara_tag m
WHERE d.device_number IS NULL"); 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>(); result = (await conn.QueryAsync<NiagaraTags>(sb.ToString())).ToList<NiagaraTags>();
sb.Clear(); sb.Clear();
@ -409,19 +416,19 @@ namespace Repository.BackendRepository.Implement
//device有niagara沒有is_link 更新成 0 //device有niagara沒有is_link 更新成 0
sb.Append($@" SET SQL_SAFE_UPDATES = 0; sb.Append($@" SET SQL_SAFE_UPDATES = 0;
UPDATE device d UPDATE device
SET d.is_link = 0 SET is_link = 0
WHERE d.is_link = 1 and not exists (select niagara_tags from import_niagara_tag where niagara_tags = d.device_number);"); WHERE is_link = 1 AND device_number NOT IN (SELECT niagara_tags FROM import_niagara_tag);");
await conn.ExecuteAsync(sb.ToString(), commandTimeout: 100); await conn.ExecuteAsync(sb.ToString());
sb.Clear(); sb.Clear();
// device_node 有, niagara沒有, is_link 更新成 0 // device_node 有, niagara沒有, is_link 更新成 0
sb.Append($@" SET SQL_SAFE_UPDATES = 0; sb.Append($@" SET SQL_SAFE_UPDATES = 0;
UPDATE device_node d UPDATE device_node
SET d.is_link = 0 SET is_link = 0
WHERE d.is_link = 1 and not exists (select niagara_tags from import_niagara_tag where niagara_tags = d.device_number);"); WHERE is_link = 1 AND device_number NOT IN (SELECT niagara_tags FROM import_niagara_tag);");
await conn.ExecuteAsync(sb.ToString(), commandTimeout: 100); await conn.ExecuteAsync(sb.ToString());
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -453,8 +460,8 @@ namespace Repository.BackendRepository.Implement
sb.Append($@" SELECT m.* sb.Append($@" SELECT m.*
FROM import_niagara_item m FROM import_niagara_item m
LEFT JOIN device_item d 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 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"); WHERE d.points IS NULL;");
result = (await conn.QueryAsync<NiagaraTagsForItem>(sb.ToString())).ToList<NiagaraTagsForItem>(); result = (await conn.QueryAsync<NiagaraTagsForItem>(sb.ToString())).ToList<NiagaraTagsForItem>();
sb.Clear(); sb.Clear();
@ -581,14 +588,12 @@ namespace Repository.BackendRepository.Implement
#region insert building_menu #region insert building_menu
if (bm.Count == 0) 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) is_link, created_by, created_at, updated_by, updated_at)
VALUES ('" + data.device_building_tag + "', '" + values('{data.device_building_tag}', '{data.device_system_tag}', '{data.device_name_tag}', '{data.device_building_tag}', '{data.device_system_tag}',
data.device_system_tag + "', '" + 4, 1, 0, 0, 1,
data.device_name_tag + "', '" + 1, 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now(), 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now());");
data.device_building_tag + "', '" +
data.device_system_tag + "', " +
"1, 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now(), 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now() );");
} }
#endregion #endregion
} }
@ -769,10 +774,16 @@ namespace Repository.BackendRepository.Implement
try try
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.Append("update device d inner JOIN import_niagara_tag m ON m.niagara_tags = d.device_number " + sb.Append(@"UPDATE device d
"set d.full_name=m.device_full_name " + INNER JOIN import_niagara_tag m ON m.niagara_tags = d.device_number
"where m.device_full_name<>d.full_name;"); SET d.full_name = m.device_full_name
await conn.ExecuteAsync(sb.ToString(), commandTimeout: 200); 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) catch (Exception exception)
{ {
@ -865,27 +876,39 @@ namespace Repository.BackendRepository.Implement
using (IDbConnection conn = GetDbConnection()) using (IDbConnection conn = GetDbConnection())
{ {
conn.Open(); 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 try
{ {
StringBuilder sb = new StringBuilder();
sb.Append("select * from device_disaster;"); 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.Clear();
sb.Append("select * from device where deleted = 0;"); sb.Append("select * from device where deleted = 0;");
var device = (await conn.QueryAsync<DeviceDisasterOutput>(sb.ToString())).ToList(); device = (await conn.QueryAsync<DeviceDisasterOutput>(sb.ToString())).ToList();
dv = dv.Where(x => device.Any(d => d.device_number == x.value.Split('/')[6])).ToList(); }
catch (Exception exception)
{
throw exception;
}
finally
{
conn.Close();
}
}
dv = dv.Where(x => device.Any(d => d.device_number == x.value.Split('/')[6])).ToList();
sb.Clear(); sb.Clear();
var updateList = dv.Where(x => deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6] && dd.device_system_value != x.disasterValue)); 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) foreach (var d in updateList)
{ {
string device_number = d.value.Split('/')[6]; string device_number = d.value.Split('/')[6];
sb.Append($"update device_disaster set device_system_value = '{d.disasterValue}' where device_number = '{device_number}'; "); 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])); var insertList = dv.Where(x => !deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6])).ToList();
foreach (var d in insertList) foreach (var d in insertList)
{ {
string device_number = d.value.Split('/')[6]; string device_number = d.value.Split('/')[6];
@ -899,9 +922,109 @@ namespace Repository.BackendRepository.Implement
'{device_number.Split('_')[4]}', '{device_number}'); "); '{device_number.Split('_')[4]}', '{device_number}'); ");
} }
using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
try
{
if (!string.IsNullOrEmpty(sb.ToString())) if (!string.IsNullOrEmpty(sb.ToString()))
await conn.ExecuteAsync(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) catch (Exception exception)
{ {
throw exception; throw exception;

View File

@ -71,5 +71,10 @@ namespace Repository.BackendRepository.Interface
/// <returns></returns> /// <returns></returns>
Task InsertSubSystemFloor(); Task InsertSubSystemFloor();
Task DeviceDisasterAysnc(List<Device_value_disaster> dv); 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 string Floor_guid { get; set; } //樓層GUID
public int Priority { get; set; } public int Priority { get; set; }
public string building_tag { get; set; }
} }
} }