Merge branch 'master' into Willy

This commit is contained in:
b110212000 2021-10-25 16:12:47 +08:00
commit 02c60eaf7d
47 changed files with 1908 additions and 745 deletions

View File

@ -914,7 +914,14 @@ namespace SolarPower.Controllers
}
catch (Exception exception)
{
apiResult.Code = "9999";
if(exception.Message == "Fatal error encountered during command execution.")
{
apiResult.Code = "9984";
}
else
{
apiResult.Code = "9999";
}
Logger.LogError("【" + controllerName + "/" + actionName + "】");
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
}

View File

@ -46,7 +46,7 @@ namespace SolarPower.Controllers
where_entities.Add("Filter", filter);
}
//抓出 除了自建自用
var temp_solarType_where = $@" ps.SolarType != 2";
where.Add(temp_solarType_where);

View File

@ -177,7 +177,7 @@ namespace SolarPower.Controllers
myUser.myPowerStationGroupByCities = myPowerStations;
ViewBag.myPowerStationGroupByCities = myPowerStations;
if (controllerName == "PowerStation" && actionName == "Edit")
if (controllerName == "StationOverview" && actionName == "Info")
{
//電站資訊的各電站
string stationId_param = filterContext.HttpContext.Request.Query["stationId"];

View File

@ -643,7 +643,7 @@ namespace SolarPower.Controllers
OperationRecordPersonnel operationRecordPersonnel = new OperationRecordPersonnel();
operationRecordPersonnel.OperationRecordId = id;
operationRecordPersonnel.UserId = op;
operationRecordPersonnel.CreatedBy = myUser.Id;
insertOperationRecordPersonnels.Add(operationRecordPersonnel);
}
@ -651,6 +651,7 @@ namespace SolarPower.Controllers
{
"OperationRecordId",
"UserId",
"CreatedBy"
};
await operationRepository.AddOperationRecordPersonnelAsync(insertOperationRecordPersonnels, operationRecordPersonnelProperties);
@ -658,82 +659,83 @@ namespace SolarPower.Controllers
}
if (post.WorkPersonIds != null)
if(post.Emailcheck == 1)
{
var powerstations = await powerStationRepository.GetOneAsync(post.PowerStationId);
List<NoticeSchedule> noticeSchedules = new List<NoticeSchedule>();
foreach (var person in post.WorkPersonIds)
if (post.WorkPersonIds != null)
{
var fixtype = post.WorkType switch
var powerstations = await powerStationRepository.GetOneAsync(post.PowerStationId);
List<NoticeSchedule> noticeSchedules = new List<NoticeSchedule>();
foreach (var person in post.WorkPersonIds)
{
var fixtype = post.WorkType switch
{
0 => "清洗",
1 => "巡檢",
2 => "維修",
_ => ""
};
var user = await userRepository.GetOneAsync(person);
NoticeSchedule schedule = new NoticeSchedule()
{
EmailType = 3,
Type = 1,
UserId = person,
RecipientName = user.Name,
RecipientEmail = user.Email,
Subject = powerstations.Name + "-" + fixtype + "-" + post.WorkTime,
Content = "維修項目" + post.FixDo + "</br>注意事項 :" + post.Notice,
};
noticeSchedules.Add(schedule);
}
properties = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Content",
"RecipientName",
"Type",
"ExceptionId"
};
await noticeScheduleRepository.AddAnyThing<List<NoticeSchedule>>(noticeSchedules, properties, "notice_schedule");
}
if (post.FixFirm != 0)
{
var powerstations = await powerStationRepository.GetOneAsync(post.PowerStationId);
var fixtype = operationRecord.WorkType switch
{
0 => "清洗",
1 => "巡檢",
2 => "維修",
_ => ""
};
var user = await userRepository.GetOneAsync(person);
var powerstation = await powerStationRepository.GetOneAsync(post.PowerStationId);
var firm = await operationRepository.GetOneWithCustomDBNameAndTableAsync<OperationInfo>(post.FixFirm, powerstations.SiteDB, "operation_firm");
NoticeSchedule schedule = new NoticeSchedule()
{
EmailType = 3,
Type = 1,
UserId = person,
RecipientName = user.Name,
RecipientEmail = user.Email,
RecipientName = firm.Name,
RecipientEmail = firm.Email,
Subject = powerstations.Name + "-" + fixtype + "-" + post.WorkTime,
Content = "維修項目" + post.FixDo + "</br>注意事項 :" + post.Notice,
};
noticeSchedules.Add(schedule);
properties = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Content",
"RecipientName",
"Type",
"ExceptionId"
};
await noticeScheduleRepository.AddAnyThing<NoticeSchedule>(schedule, properties, "notice_schedule");
}
properties = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Content",
"RecipientName",
"Type",
"ExceptionId"
};
await noticeScheduleRepository.AddAnyThing<List<NoticeSchedule>>(noticeSchedules, properties, "notice_schedule");
}
if (post.FixFirm != 0)
{
var powerstations = await powerStationRepository.GetOneAsync(post.PowerStationId);
var fixtype = operationRecord.WorkType switch
{
0 => "清洗",
1 => "巡檢",
2 => "維修",
_ => ""
};
var powerstation = await powerStationRepository.GetOneAsync(post.PowerStationId);
var firm = await operationRepository.GetOneWithCustomDBNameAndTableAsync<OperationInfo>(post.FixFirm, powerstations.SiteDB, "operation_firm");
NoticeSchedule schedule = new NoticeSchedule()
{
EmailType = 3,
Type = 1,
RecipientName = firm.Name,
RecipientEmail = firm.Email,
Subject = powerstations.Name + "-" + fixtype + "-" + post.WorkTime,
Content = "維修項目" + post.FixDo + "</br>注意事項 :" + post.Notice,
};
properties = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Content",
"RecipientName",
"Type",
"ExceptionId"
};
await noticeScheduleRepository.AddAnyThing<NoticeSchedule>(schedule, properties, "notice_schedule");
}
//using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Suppress))
//{
@ -879,83 +881,89 @@ namespace SolarPower.Controllers
}
#endregion
if (post.WorkPersonIds != null)
if (post.Emailcheck == 1)
{
var powerstations = await powerStationRepository.GetOneAsync(post.PowerStationId);
List<NoticeSchedule> noticeSchedules = new List<NoticeSchedule>();
foreach (var person in post.WorkPersonIds)
if (post.WorkPersonIds != null)
{
var fixtype = operationRecord.WorkType switch
var powerstations = await powerStationRepository.GetOneAsync(post.PowerStationId);
List<NoticeSchedule> noticeSchedules = new List<NoticeSchedule>();
foreach (var person in post.WorkPersonIds)
{
var fixtype = operationRecord.WorkType switch
{
0 => "清洗",
1 => "巡檢",
2 => "維修",
_ => ""
};
var user = await userRepository.GetOneAsync(person);
NoticeSchedule schedule = new NoticeSchedule()
{
EmailType = 3,
Type = 1,
UserId = person,
RecipientName = user.Name,
RecipientEmail = user.Email,
Subject = powerstations.Name + "-" + fixtype + "-" + post.WorkTime,
Content = "維修項目:" + post.FixDo + "</br>注意事項 :" + post.Notice,
};
noticeSchedules.Add(schedule);
}
properties = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Content",
"RecipientName",
"Type",
"ExceptionId"
};
await noticeScheduleRepository.AddAnyThing<List<NoticeSchedule>>(noticeSchedules, properties, "notice_schedule");
}
if (post.FixFirm != 0)
{
var powerstations = await powerStationRepository.GetOneAsync(post.PowerStationId);
var fixtype = post.WorkType switch
{
0 => "清洗",
1 => "巡檢",
2 => "維修",
_ => ""
};
var user = await userRepository.GetOneAsync(person);
var powerstation = await powerStationRepository.GetOneAsync(post.PowerStationId);
var firm = await operationRepository.GetOneWithCustomDBNameAndTableAsync<OperationInfo>(post.FixFirm, powerstations.SiteDB, "operation_firm");
NoticeSchedule schedule = new NoticeSchedule()
{
EmailType = 3,
Type = 1,
UserId = person,
RecipientName = user.Name,
RecipientEmail = user.Email,
RecipientName = firm.Name,
RecipientEmail = firm.Email,
Subject = powerstations.Name + "-" + fixtype + "-" + post.WorkTime,
Content = "維修項目:" + post.FixDo + "</br>注意事項 :" + post.Notice,
};
noticeSchedules.Add(schedule);
properties = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Content",
"RecipientName",
"Type",
"ExceptionId"
};
await noticeScheduleRepository.AddAnyThing<NoticeSchedule>(schedule, properties, "notice_schedule");
}
properties = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Content",
"RecipientName",
"Type",
"ExceptionId"
};
await noticeScheduleRepository.AddAnyThing<List<NoticeSchedule>>(noticeSchedules, properties, "notice_schedule");
}
if (post.FixFirm != 0)
{
var powerstations = await powerStationRepository.GetOneAsync(post.PowerStationId);
var fixtype = post.WorkType switch
{
0 => "清洗",
1 => "巡檢",
2 => "維修",
_ => ""
};
var powerstation = await powerStationRepository.GetOneAsync(post.PowerStationId);
var firm = await operationRepository.GetOneWithCustomDBNameAndTableAsync<OperationInfo>(post.FixFirm, powerstations.SiteDB, "operation_firm");
NoticeSchedule schedule = new NoticeSchedule()
{
EmailType = 3,
Type = 1,
RecipientName = firm.Name,
RecipientEmail = firm.Email,
Subject = powerstations.Name + "-" + fixtype + "-" + post.WorkTime,
Content = "維修項目:" + post.FixDo + "</br>注意事項 :" + post.Notice,
};
properties = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Content",
"RecipientName",
"Type",
"ExceptionId"
};
await noticeScheduleRepository.AddAnyThing<NoticeSchedule>(schedule, properties, "notice_schedule");
}
#endregion

View File

@ -47,7 +47,7 @@ namespace SolarPower.Controllers
where_entities.Add("Filter", filter);
}
var temp_solartype_where = @" ps.SolarType = 0";
var temp_solartype_where = @" ps.SolarType != 2";
where.Add(temp_solartype_where);
var powerStations = myPowerStationService.GetMyPowerStations(myUser, 1, null, where, where_entities);

View File

@ -420,7 +420,7 @@ namespace SolarPower.Controllers
"日發電量(kWh)",
"日發電量百分比(%)",
"日照小時(hr)",
"kWH/kWP",
"有效發電小時",
"PR%",
"日平均日照度(W/㎡)",
"日平均模組溫度(°C)"
@ -518,7 +518,7 @@ namespace SolarPower.Controllers
cell.CellStyle = styleLine12;
index++;
cell = row.CreateCell(index);
cell.SetCellValue("kWH/kWP平均(日)");
cell.SetCellValue("平均有效發電小時(日)");
cell.CellStyle = styleLine12;
index++;
cell = row.CreateCell(index);
@ -666,7 +666,7 @@ namespace SolarPower.Controllers
"月發電量(kWh)",
"月發電量百分比(%)",
"日照小時(hr)",
"kWH/kWP",
"有效發電小時",
"PR%",
"月平均日照度(W/㎡)",
"月平均模組溫度(°C)"
@ -764,7 +764,7 @@ namespace SolarPower.Controllers
cell.CellStyle = styleLine12;
index++;
cell = row.CreateCell(index);
cell.SetCellValue("kWH/kWP平均(月)");
cell.SetCellValue("平均有效發電小時(月)");
cell.CellStyle = styleLine12;
index++;
cell = row.CreateCell(index);
@ -1141,7 +1141,7 @@ namespace SolarPower.Controllers
index = 0;
row = sheet.CreateRow(RowPosition);
cell = row.CreateCell(index);
cell.SetCellValue("kWH/kWP:");
cell.SetCellValue("有效發電小時:");
cell.CellStyle = styleLine12;
cell = row.CreateCell(1);
cell.SetCellValue(!string.IsNullOrEmpty(kWhkwp) ? Convert.ToDouble(kWhkwp) : 0);
@ -1220,7 +1220,7 @@ namespace SolarPower.Controllers
"日發電量(kWh)",
"日發電量百分比(%)",
"日照小時(hr)",
"kWH/kWP",
"有效發電小時",
"PR%",
"日平均日照度(W/㎡)",
"日平均模組溫度(°C)"
@ -1574,7 +1574,7 @@ namespace SolarPower.Controllers
index++;
cell = row.CreateCell(index);
cell.SetCellValue(Math.Round(form.SolarHour,2));
cell.SetCellValue(Math.Round(form.AvgKWHKWP,2));
cell.CellStyle = styleLine12;
index++;
@ -1634,7 +1634,8 @@ namespace SolarPower.Controllers
City = form.CityName,
Count = 1,
Kwh = form.Kwh,
SolarHour = form.SolarHour
SolarHour = form.SolarHour,
Kwhkwp = form.AvgKWHKWP
};
if( cityArrays.Where(a=>a.City == form.CityName).Count() > 0)
{
@ -1642,6 +1643,7 @@ namespace SolarPower.Controllers
city.Count += cityinfo.Count;
city.Kwh += cityinfo.Kwh;
city.SolarHour += cityinfo.SolarHour;
city.Kwhkwp += cityinfo.Kwhkwp;
}
else
{
@ -1659,7 +1661,7 @@ namespace SolarPower.Controllers
"區域",
"電站名稱",
"發電量",
"發電小時",
"有效發電小時",
"平均日照",
"PR"
};
@ -1708,7 +1710,7 @@ namespace SolarPower.Controllers
index++;
cell = row.CreateCell(index);
cell.SetCellValue(Math.Round((cityArray.SolarHour / cityArray.Count), 2));
cell.SetCellValue(Math.Round((cityArray.Kwhkwp / cityArray.Count), 2));
cell.CellStyle = styleLine12;
region = new CellRangeAddress(cityRowPosition, cityRowPosition, index, index + 1);
sheet.AddMergedRegion(region);
@ -1742,7 +1744,7 @@ namespace SolarPower.Controllers
index++;
cell = row.CreateCell(index);
cell.SetCellValue("發電時間(小時)");
cell.SetCellValue("有效發電小時");
cell.CellStyle = styleLine12;
region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
sheet.AddMergedRegion(region);
@ -1919,7 +1921,7 @@ namespace SolarPower.Controllers
index++;
cell = row.CreateCell(index);
cell.SetCellValue(Math.Round(form.SolarHour, 2));
cell.SetCellValue(Math.Round(form.AvgKWHKWP, 2));
cell.CellStyle = styleLine12;
index++;
@ -1979,7 +1981,8 @@ namespace SolarPower.Controllers
City = form.CityName,
Count = 1,
Kwh = form.Kwh,
SolarHour = form.SolarHour
SolarHour = form.SolarHour,
Kwhkwp = form.AvgKWHKWP
};
if (cityArrays.Where(a => a.City == form.CityName).Count() > 0)
{
@ -1987,6 +1990,7 @@ namespace SolarPower.Controllers
city.Count += cityinfo.Count;
city.Kwh += cityinfo.Kwh;
city.SolarHour += cityinfo.SolarHour;
city.Kwhkwp += cityinfo.Kwhkwp;
}
else
{
@ -2004,7 +2008,7 @@ namespace SolarPower.Controllers
"區域",
"電站名稱",
"發電量",
"發電小時",
"有效發電小時",
"平均日照",
"PR"
};
@ -2053,7 +2057,7 @@ namespace SolarPower.Controllers
index++;
cell = row.CreateCell(index);
cell.SetCellValue(Math.Round((cityArray.SolarHour / cityArray.Count), 2));
cell.SetCellValue(Math.Round((cityArray.Kwhkwp / cityArray.Count), 2));
cell.CellStyle = styleLine12;
region = new CellRangeAddress(cityRowPosition, cityRowPosition, index, index + 1);
sheet.AddMergedRegion(region);
@ -2087,7 +2091,7 @@ namespace SolarPower.Controllers
index++;
cell = row.CreateCell(index);
cell.SetCellValue("發電時間(小時)");
cell.SetCellValue("有效發電小時");
cell.CellStyle = styleLine12;
region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
sheet.AddMergedRegion(region);
@ -2182,6 +2186,46 @@ namespace SolarPower.Controllers
return Path.Combine("\\" + "upload", "report", Datename, "FIC太陽能監控平台" + "_" + "綜合報表" + "_" + postObject.Userid + Datename + ".xlsx");
}
public async Task<ApiResult<List<string>>> CheckExcel(Select_table2 post)
{
var ApiResult = new ApiResult<List<string>>();
var ErrorMessage = new List<string>();
foreach (var station in post.PowerStation)
{
var Id = Convert.ToInt32(station.Value);
var table = new Select_table()
{
FormType = post.FormType,
SearchType = post.SearchType,
PowerStation = Id,
Time = post.Time,
Userid = post.Userid
};
var checkinv = await stationReportRepository.Findhaveinv(table);
var getinvsql = checkinv[0] as IDictionary<string, object>;
if (getinvsql["mySelect"] == null)
{
ErrorMessage.Add(station.Name + "此時段無逆變器資料");
}
else
{
var cid = await stationReportRepository.CheckExcelAsync(table);
if (cid == 0)
{
ErrorMessage.Add(station.Name + "此時段資料未建立");
}
}
}
if(ErrorMessage.Count > 0)
{
ApiResult.Code = "9999";
ApiResult.Data = ErrorMessage;
}
else
{
ApiResult.Code = "0000";
}
return ApiResult;
}
}
}

View File

@ -17,6 +17,8 @@ namespace SolarPower.Models
public double All_PR { get; set; }//總平均PR
public double Now_Carbon { get; set; }//現減炭
public double All_Carbon { get; set; }//總減炭
public double All_irradiance { get; set; }
public double Now_irradiance { get; set; }
}
public class ChartInput
{

View File

@ -17,10 +17,11 @@ namespace SolarPower.Models
{
{ "0000", "OK" },
{ "0001", "傳入參數錯誤。" },
{ "0002","請先刪除相關逆變器"},
{ "0003","請先刪除相關設備"},
{ "0004","請先移除相關逆變器綁定"},
{ "9985","該電站尚無逆變器資料"},
{ "0002", "請先刪除相關逆變器"},
{ "0003", "請先刪除相關設備"},
{ "0004", "請先移除相關逆變器綁定"},
{ "9984", "連線逾時"},
{ "9985", "該電站尚無逆變器資料"},
{ "9986", "該帳號已被註冊,請重新輸入"},
{ "9987", "查無該運維作業記錄檔案"},
{ "9988", "查無該資料紀錄"},

View File

@ -293,6 +293,7 @@ namespace SolarPower.Models
public string Notice { get; set; }
public string Description { get; set; }
public IFormFile[] RecordFiles { get; set; }
public byte Emailcheck { get; set; }
}
public class UpdateOperationRecord : Updated

View File

@ -199,7 +199,8 @@ namespace SolarPower.Models
public string errMsg { get; set; }//錯誤原因
public string PowerStationName { get; set; }//電站名稱
public int PowerStationId { get; set; }//電站流水號
public string normalTime { get; set; }
public string normalTime { get; set; }//賦歸時間
public string errMsgT { get; set; } //errMsgType
}
public class UserPowerStationTo

View File

@ -106,6 +106,7 @@ namespace SolarPower.Models
public double Kwh { get; set; }
public double SolarHour { get; set; }
public int Count { get; set; }
public double Kwhkwp { get; set; }
}

View File

@ -8,6 +8,7 @@ using SolarPower.Models.PowerStation;
using SolarPower.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
@ -870,40 +871,83 @@ namespace SolarPower.Quartz.Jobs
#region
var users = userRepository.GetAllAsync();
var ttt = new List<string>() {
"s506488@gmail.com",
"cesarliuc@gmail.com"
};
foreach (var user in users.Result)
{
List<OperationPersonnel> powerstations = new List<OperationPersonnel>();
powerstations = await noticeScheduleRepository.GetPowerStationOperationPersonnel(user.Id);
if (powerstations.Count == 0)
try
{
continue;
}
List<Excelpowerstation> sentdaypowerstations = powerstations.Where(x => x.EmailDayReport == 1).Select(a => new Excelpowerstation { Name = a.Name, Value = a.PowerStationId.ToString() }).ToList();
List<Excelpowerstation> sentMaxpowerstations = powerstations.Where(x => x.EmailComplexReport == 1).Select(a => new Excelpowerstation { Name = a.Name, Value = a.PowerStationId.ToString() }).ToList();
logger.LogInformation("【CalcAvgPowerStationJob】【開始產生使用者[{0}({1})]的日月報】", user.Account, user.Name);
Controllers.StationReportController stationReportController = new Controllers.StationReportController(powerStationRepository, stationReportRepository);
//日報表
if (sentdaypowerstations.Count != 0)
{
Excel dayexcel = new Excel()
List<OperationPersonnel> powerstations = new List<OperationPersonnel>();
powerstations = await noticeScheduleRepository.GetPowerStationOperationPersonnel(user.Id);
if (powerstations.Count == 0)
{
FormType = 0,
PowerStation = sentdaypowerstations,
SearchType = 0,
Time = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"),
Userid = user.Id
};
var stationReportName = stationReportController.ExportExcelBackDownload(JsonConvert.SerializeObject(dayexcel, Formatting.Indented));
if (stationReportName != "")
continue;
}
List<Excelpowerstation> sentdaypowerstations = powerstations.Where(x => x.EmailDayReport == 1).Select(a => new Excelpowerstation { Name = a.Name, Value = a.PowerStationId.ToString() }).ToList();
List<Excelpowerstation> sentMaxpowerstations = powerstations.Where(x => x.EmailComplexReport == 1).Select(a => new Excelpowerstation { Name = a.Name, Value = a.PowerStationId.ToString() }).ToList();
Controllers.StationReportController stationReportController = new Controllers.StationReportController(powerStationRepository, stationReportRepository);
//日報表
if (sentdaypowerstations.Count != 0)
{
NoticeSchedule DaySchedule = new NoticeSchedule()
Excel dayexcel = new Excel()
{
FormType = 0,
PowerStation = sentdaypowerstations,
SearchType = 0,
Time = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"),
Userid = user.Id
};
var stationReportName = stationReportController.ExportExcelBackDownload(JsonConvert.SerializeObject(dayexcel, Formatting.Indented));
if (stationReportName != "")
{
NoticeSchedule DaySchedule = new NoticeSchedule()
{
UserId = user.Id,
EmailType = 0,
RecipientEmail = user.Email,
Subject = "日報表",
Attachment = stationReportName,
RecipientName = user.Name,
Type = 1
};
List<string> properties = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Attachment",
"RecipientName",
"Type"
};
await noticeScheduleRepository.AddOneAsync(DaySchedule, properties);
}
}
//綜合報表 每日
if (sentMaxpowerstations.Count != 0)
{
Select_table2 maxdayexcel = new Select_table2()
{
FormType = 0,
PowerStation = sentMaxpowerstations,
SearchType = 0,
Time = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"),
Userid = user.Id
};
var stationMaxReportName = stationReportController.ExportExcelmaxtableBackDownload(JsonConvert.SerializeObject(maxdayexcel, Formatting.Indented));
NoticeSchedule MaxSchedule = new NoticeSchedule()
{
UserId = user.Id,
EmailType = 0,
EmailType = 2,
RecipientEmail = user.Email,
Subject = "日報表",
Attachment = stationReportName,
Subject = "綜合報表",
Attachment = stationMaxReportName,
RecipientName = user.Name,
Type = 1
};
@ -917,120 +961,100 @@ namespace SolarPower.Quartz.Jobs
"RecipientName",
"Type"
};
await noticeScheduleRepository.AddOneAsync(DaySchedule, properties);
await noticeScheduleRepository.AddOneAsync(MaxSchedule, properties);
if (DateTime.Now.ToString("dd") == "01")
{
Select_table2 maxmonthexcel = new Select_table2()
{
FormType = 0,
PowerStation = sentMaxpowerstations,
SearchType = 0,
Time = DateTime.Now.AddDays(-1).ToString("yyyy-MM"),
Userid = user.Id
};
var stationReportmaxmonthName = stationReportController.ExportExcelBackDownload(JsonConvert.SerializeObject(maxmonthexcel, Formatting.Indented));
NoticeSchedule MaxmonthSchedule = new NoticeSchedule()
{
RecipientEmail = user.Email,
Subject = "綜合報表",
Attachment = stationReportmaxmonthName,
RecipientName = user.Name,
Type = 1,
UserId = user.Id,
EmailType = 2
};
List<string> properties2 = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Attachment",
"RecipientName",
"Type"
};
await noticeScheduleRepository.AddOneAsync(MaxmonthSchedule, properties2);
}
}
}
//綜合報表 每日
if (sentMaxpowerstations.Count != 0)
{
Select_table2 maxdayexcel = new Select_table2()
{
FormType = 0,
PowerStation = sentMaxpowerstations,
SearchType = 0,
Time = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"),
Userid = user.Id
};
var stationMaxReportName = stationReportController.ExportExcelmaxtableBackDownload(JsonConvert.SerializeObject(maxdayexcel, Formatting.Indented));
NoticeSchedule MaxSchedule = new NoticeSchedule()
{
UserId = user.Id,
EmailType = 2,
RecipientEmail = user.Email,
Subject = "綜合報表",
Attachment = stationMaxReportName,
RecipientName = user.Name,
Type = 1
};
List<string> properties = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Attachment",
"RecipientName",
"Type"
};
await noticeScheduleRepository.AddOneAsync(MaxSchedule, properties);
if (DateTime.Now.ToString("dd") == "01")
{
Select_table2 maxmonthexcel = new Select_table2()
List<Excelpowerstation> sentmonthpowerstations = powerstations.Where(x => x.EmailMonthReport == 1).Select(a => new Excelpowerstation { Name = a.Name, Value = a.PowerStationId.ToString() }).ToList();
if (sentmonthpowerstations.Count == 0)
{
FormType = 0,
PowerStation = sentMaxpowerstations,
SearchType = 0,
break;
}
Excel monthexcel = new Excel()
{
FormType = 1,
PowerStation = sentmonthpowerstations,
SearchType = 2,
Time = DateTime.Now.AddDays(-1).ToString("yyyy-MM"),
Userid = user.Id
};
var stationReportmaxmonthName = stationReportController.ExportExcelBackDownload(JsonConvert.SerializeObject(maxmonthexcel, Formatting.Indented));
NoticeSchedule MaxmonthSchedule = new NoticeSchedule()
var stationReportmonthName = stationReportController.ExportExcelBackDownload(JsonConvert.SerializeObject(monthexcel, Formatting.Indented));
if (stationReportmonthName != "")
{
RecipientEmail = user.Email,
Subject = "綜合報表",
Attachment = stationReportmaxmonthName,
RecipientName = user.Name,
Type = 1,
UserId = user.Id,
EmailType = 2
};
List<string> properties2 = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Attachment",
"RecipientName",
"Type"
};
await noticeScheduleRepository.AddOneAsync(MaxmonthSchedule, properties2);
NoticeSchedule MonthSchedule = new NoticeSchedule()
{
RecipientEmail = user.Email,
Subject = "月報表",
Attachment = stationReportmonthName,
RecipientName = user.Name,
Type = 1,
UserId = user.Id,
EmailType = 1
};
List<string> properties2 = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Attachment",
"RecipientName",
"Type"
};
await noticeScheduleRepository.AddOneAsync(MonthSchedule, properties2);
}
}
logger.LogInformation("【CalcAvgPowerStationJob】【產生完成使用者[{0}({1})]的日月報】", user.Account, user.Name);
}
if (DateTime.Now.ToString("dd") == "01")
catch (Exception exception)
{
List<Excelpowerstation> sentmonthpowerstations = powerstations.Where(x => x.EmailMonthReport == 1).Select(a => new Excelpowerstation { Name = a.Name, Value = a.PowerStationId.ToString() }).ToList();
if (sentmonthpowerstations.Count == 0)
logger.LogError("【CalcAvgPowerStationJob】【產生失敗使用者[{0}({1})]的日月報】", user.Account, user.Name);
logger.LogError("【CalcAvgPowerStationJob】[Exception] - {0}", exception.Message);
if (exception.InnerException != null)
{
break;
}
Excel monthexcel = new Excel()
{
FormType = 1,
PowerStation = sentmonthpowerstations,
SearchType = 2,
Time = DateTime.Now.AddDays(-1).ToString("yyyy-MM"),
Userid = user.Id
};
var stationReportmonthName = stationReportController.ExportExcelBackDownload(JsonConvert.SerializeObject(monthexcel, Formatting.Indented));
if (stationReportmonthName != "")
{
NoticeSchedule MonthSchedule = new NoticeSchedule()
{
RecipientEmail = user.Email,
Subject = "月報表",
Attachment = stationReportmonthName,
RecipientName = user.Name,
Type = 1,
UserId = user.Id,
EmailType = 1
};
List<string> properties2 = new List<string>()
{
"UserId",
"EmailType",
"RecipientEmail",
"Subject",
"Attachment",
"RecipientName",
"Type"
};
await noticeScheduleRepository.AddOneAsync(MonthSchedule, properties2);
logger.LogError("【CalcAvgPowerStationJob】[InnerException] - {0}", exception.InnerException.Message);
}
var line = new StackTrace(exception, true).GetFrame(0).GetFileLineNumber();
logger.LogError("【CalcAvgPowerStationJob】[錯誤行數] - {0}", line);
}
}

View File

@ -162,7 +162,7 @@ namespace SolarPower.Quartz.Jobs
await powerStationRepository.UpdateInvStatus(update_invStatusErr.Key, null, update_invStatusErr.Select(x => x.InverterId).ToList(), 2);
}
logger.LogError("【CalcInverter15minJob】檢測完成逆變器狀態");
logger.LogInformation("【CalcInverter15minJob】檢測完成逆變器狀態");
}
catch(Exception exception)
{

View File

@ -84,8 +84,6 @@ namespace SolarPower.Quartz.Jobs
logger.LogError("【{0}】{1}", "CalcPowerStationJob", ex.Message);
observation = null;
}
#endregion
#region step2. DB及電站編號找出該電站的控制器
@ -103,7 +101,7 @@ namespace SolarPower.Quartz.Jobs
if (string.IsNullOrEmpty(exist))
{
logger.LogError("【CalcPowerStationJob】【查無電站[{0}]的s{0}01_station資料表】", powerStation.Code);
logger.LogError($"【CalcPowerStationJob】【查無電站[{powerStation.Code}]的s{powerStation.Code}01_station資料表】");
}
else
{
@ -133,30 +131,32 @@ namespace SolarPower.Quartz.Jobs
#region
history.MONEY = history.KWH * powerStation.PowerRate;
history.TODAYMONEY = history.TodayKWh * powerStation.PowerRate;
history.TOTALMONEY = history.TotalKWH * powerStation.PowerRate;
//即時發電金額
switch (powerStation.SolarType)
{
case (int)SolarTypeEnum.SelfSold: //自建躉售
if (lastmoneyhistorybyhour != null)
{
history.TODAYMONEY = lastmoneyhistorybyhour.TODAYMONEY + history.KWH * powerStation.PowerRate;
history.TOTALMONEY = lastmoneyhistorybyhour.TOTALMONEY + history.KWH * powerStation.PowerRate;
}
else
{
history.TODAYMONEY = history.KWH * powerStation.PowerRate;
history.TOTALMONEY = history.KWH * powerStation.PowerRate;
}
//if (lastmoneyhistorybyhour != null)
//{
// history.TODAYMONEY = lastmoneyhistorybyhour.TODAYMONEY + history.KWH * powerStation.PowerRate;
// history.TOTALMONEY = lastmoneyhistorybyhour.TOTALMONEY + history.KWH * powerStation.PowerRate;
//}
//else
//{
// history.TODAYMONEY = history.KWH * powerStation.PowerRate;
// history.TOTALMONEY = history.KWH * powerStation.PowerRate;
//}
//今日發電金額 計算方式todaykWh * 授電費率,如有上筆資料,需累加 上一筆金額
//calcPowerStation.Today_Money = history.TodayKWh * powerStation.PowerRate;
calcPowerStation.Today_Money = history.TODAYMONEY;
//今日發電金額 計算方式todaykWh * 授電費率
calcPowerStation.Today_Money = history.TodayKWh * powerStation.PowerRate;
//calcPowerStation.Today_Money = history.TODAYMONEY;
////總發電金額 計算方式totalkWh * 授電費率,如有上筆資料,需累加 上一筆金額
//calcPowerStation.Total_Money = history.TotalKWH * powerStation.PowerRate;
calcPowerStation.Total_Money = history.TOTALMONEY;
////總發電金額 計算方式totalkWh * 授電費率
calcPowerStation.Total_Money = history.TotalKWH * powerStation.PowerRate;
//calcPowerStation.Total_Money = history.TOTALMONEY;
break;
case (int)SolarTypeEnum.HireSold: //租建躉售
//找出該電站的所有土地房屋資訊
@ -170,43 +170,49 @@ namespace SolarPower.Quartz.Jobs
}
//avgLeaseRate = sumLeaseRate / landBuildings.Count();
if (lastmoneyhistorybyhour != null)
{
history.TODAYMONEY = lastmoneyhistorybyhour.TODAYMONEY + history.KWH * powerStation.PowerRate;
history.TOTALMONEY = lastmoneyhistorybyhour.TOTALMONEY + history.KWH * powerStation.PowerRate;
//if (lastmoneyhistorybyhour != null)
//{
// history.TODAYMONEY = lastmoneyhistorybyhour.TODAYMONEY + history.KWH * powerStation.PowerRate;
// history.TOTALMONEY = lastmoneyhistorybyhour.TOTALMONEY + history.KWH * powerStation.PowerRate;
//今日發電金額計算方式todaykWh * 出借費率(各個土地房屋租借比率平均)
calcPowerStation.Today_Money = lastmoneyhistorybyhour.TODAYMONEY + (history.KWH * powerStation.PowerRate * sumLeaseRate);
//總發電金額 計算方式totalkWh * 授電費率
calcPowerStation.Total_Money = lastmoneyhistorybyhour.TOTALMONEY + (history.KWH * powerStation.PowerRate * sumLeaseRate);
}
else
{
history.TODAYMONEY = history.KWH * powerStation.PowerRate;
history.TOTALMONEY = history.KWH * powerStation.PowerRate;
// //今日發電金額計算方式todaykWh * 出借費率(各個土地房屋租借比率平均)
// calcPowerStation.Today_Money = lastmoneyhistorybyhour.TODAYMONEY + (history.KWH * powerStation.PowerRate * sumLeaseRate);
// //總發電金額 計算方式totalkWh * 授電費率
// calcPowerStation.Total_Money = lastmoneyhistorybyhour.TOTALMONEY + (history.KWH * powerStation.PowerRate * sumLeaseRate);
//}
//else
//{
// history.TODAYMONEY = history.KWH * powerStation.PowerRate;
// history.TOTALMONEY = history.KWH * powerStation.PowerRate;
// calcPowerStation.Today_Money = history.KWH * powerStation.PowerRate * sumLeaseRate;
// calcPowerStation.Total_Money = history.KWH * powerStation.PowerRate * sumLeaseRate;
//}
calcPowerStation.Today_Money = history.TodayKWh * powerStation.PowerRate * sumLeaseRate / 100;
calcPowerStation.Total_Money = history.TotalKWH * powerStation.PowerRate * sumLeaseRate / 100;
calcPowerStation.Today_Money = history.KWH * powerStation.PowerRate * sumLeaseRate;
calcPowerStation.Total_Money = history.KWH * powerStation.PowerRate * sumLeaseRate;
}
break;
case (int)SolarTypeEnum.SelfUse: //自建自用
if (lastmoneyhistorybyhour != null)
{
history.TODAYMONEY = lastmoneyhistorybyhour.TODAYMONEY + history.KWH * powerStation.PowerRate;
history.TOTALMONEY = lastmoneyhistorybyhour.TOTALMONEY + history.KWH * powerStation.PowerRate;
}
else
{
history.TODAYMONEY = history.KWH * powerStation.PowerRate;
history.TOTALMONEY = history.KWH * powerStation.PowerRate;
}
//if (lastmoneyhistorybyhour != null)
//{
// history.TODAYMONEY = lastmoneyhistorybyhour.TODAYMONEY + history.KWH * powerStation.PowerRate;
// history.TOTALMONEY = lastmoneyhistorybyhour.TOTALMONEY + history.KWH * powerStation.PowerRate;
//}
//else
//{
// history.TODAYMONEY = history.KWH * powerStation.PowerRate;
// history.TOTALMONEY = history.KWH * powerStation.PowerRate;
//}
//今日發電金額 計算方式todaykWh * 授電費率
calcPowerStation.Today_Money = history.TODAYMONEY;
//calcPowerStation.Today_Money = history.TODAYMONEY;
calcPowerStation.Today_Money = history.TodayKWh * powerStation.PowerRate;
//總發電金額 計算方式totalkWh * 授電費率
calcPowerStation.Total_Money = history.TOTALMONEY;
//calcPowerStation.Total_Money = history.TOTALMONEY;
calcPowerStation.Total_Money = history.TotalKWH * powerStation.PowerRate;
break;
}
#endregion
@ -225,29 +231,26 @@ namespace SolarPower.Quartz.Jobs
carbonRate = Convert.ToDouble(await powerStationRepository.GetOneVariableByName("CarbonRate"));
history.CARBON = history.KWH * carbonRate;
if (lastmoneyhistorybyhour != null)
{
history.TODAYCARBON = lastmoneyhistorybyhour.TODAYCARBON + history.KWH * carbonRate;
history.TOTALCARBON = lastmoneyhistorybyhour.TOTALCARBON + history.KWH * carbonRate;
history.TODAYCARBON = history.TodayKWh * carbonRate;
history.TOTALCARBON = history.TotalKWH * carbonRate;
//if (lastmoneyhistorybyhour != null)
//{
// history.TODAYCARBON = lastmoneyhistorybyhour.TODAYCARBON + history.KWH * carbonRate;
// history.TOTALCARBON = lastmoneyhistorybyhour.TOTALCARBON + history.KWH * carbonRate;
//}
//else
//{
// history.TODAYCARBON = history.KWH * carbonRate;
// history.TOTALCARBON = history.KWH * carbonRate;
//}
//今日減碳量( 今日發電量 * (0.554/1000)[抓資料庫值]
calcPowerStation.Today_Carbon = history.TODAYCARBON;
//今日減碳量( 今日發電量 * (0.554/1000)[抓資料庫值]
//calcPowerStation.Today_Carbon = history.TODAYCARBON;
calcPowerStation.Today_Carbon = history.TodayKWh * carbonRate;
//總減碳量(總發電量 * (0.554/1000)[抓資料庫值]
calcPowerStation.Total_Carbon = history.TOTALCARBON;
}
else
{
history.TODAYCARBON = history.KWH * carbonRate;
history.TOTALCARBON = history.KWH * carbonRate;
//今日減碳量( 今日發電量 * (0.554/1000)[抓資料庫值]
calcPowerStation.Today_Carbon = history.TODAYCARBON;
history.CARBON = history.KWH * carbonRate;
//總減碳量(總發電量 * (0.554/1000)[抓資料庫值]
calcPowerStation.Total_Carbon = history.TotalKWH * carbonRate;
}
//總減碳量(總發電量 * (0.554/1000)[抓資料庫值]
//calcPowerStation.Total_Carbon = history.TotalKWH * carbonRate;
calcPowerStation.Total_Carbon = history.TotalKWH * carbonRate;
#endregion
@ -269,7 +272,7 @@ namespace SolarPower.Quartz.Jobs
var sensoravg_table_exist = await powerStationRepository.ExistTable(powerStation.SiteDB, sensoravg_table_name);
if (string.IsNullOrEmpty(sensoravg_table_exist))
{
logger.LogError("【CalcPowerStationJob】【查無電站[0]的s{0}01_sensoravg資料表】", powerStation.Code);
logger.LogError($"【CalcPowerStationJob】【查無電站[{powerStation.Code}]的s{powerStation.Code}01_sensoravg資料表】");
}
else
{
@ -534,7 +537,7 @@ namespace SolarPower.Quartz.Jobs
var exist_meter_table = await powerStationRepository.ExistTable(powerStation.SiteDB, meter_table_name);
if (string.IsNullOrEmpty(exist_meter_table))
{
logger.LogError("【CalcPowerStationJob】【查無電站[{0}]的s{0}01_meter資料表】", powerStation.Code);
logger.LogError($"【CalcPowerStationJob】【查無電站[{powerStation.Code}]的s{powerStation.Code}01_meter資料表】");
}
else
{

View File

@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Quartz;
using SolarPower.Models;
@ -21,38 +22,45 @@ namespace SolarPower.Quartz.Jobs
private readonly INoticeScheduleRepository noticeScheduleRepository;
private readonly IUserRepository userRepository;
private readonly IPowerStationRepository powerStationRepository;
private readonly IConfiguration Configuration;
public ExceptionSchedule(ILogger<ExceptionSchedule> logger, IOverviewRepository overviewRepository,INoticeScheduleRepository noticeScheduleRepository,IUserRepository userRepository,IPowerStationRepository powerStationRepository)
public ExceptionSchedule(ILogger<ExceptionSchedule> logger, IOverviewRepository overviewRepository,INoticeScheduleRepository noticeScheduleRepository,IUserRepository userRepository,IPowerStationRepository powerStationRepository, IConfiguration Configuration)
{
this.logger = logger;
this.overviewRepository = overviewRepository;
this.noticeScheduleRepository = noticeScheduleRepository;
this.userRepository = userRepository;
this.powerStationRepository = powerStationRepository;
this.Configuration = Configuration;
}
public async Task Execute(IJobExecutionContext context)
{
try
{
var ExceptionTimes = this.Configuration.GetValue<int>("ExceptionTimes");
var ExceptionList = await overviewRepository.GetEmailExceptionList();
if(ExceptionList.Count > 0 )
{
var ExceptionListex = ExceptionList.Where(x => x.normalTime == "1970-01-01 08:00:00" && DateTime.Now.Subtract(DateTime.Parse(x.dev_time)).Hours >= 4).ToList();
var ExceptionListex = ExceptionList.Where(x => x.normalTime == "1970-01-01 08:00:00" && DateTime.Now.Subtract(DateTime.Parse(x.dev_time)).Minutes >= ExceptionTimes).ToList();
foreach (var Exception in ExceptionListex)
{
var UserListWithPowerstation = await overviewRepository.GetUserListWithPowerstation(Exception.PowerStationId);
foreach (var user in UserListWithPowerstation)
{
var Content = $"電站名稱:{Exception.PowerStationName}" + "<br>" +
var Content = $"電站名稱:{Exception.PowerStationName}" + "<br>" +
$"設備編號:{Exception.errDevice}" + "<br>" +
$"異常ID編號:{Exception.id}" + "<br>" +
$"異常類別:{Exception.alarmClassName}" + "<br>" +
$"設備訊息:{Exception.errMsg}" + "<br>" +
$"發生時間:{Exception.dev_time}" ;
$"設備訊息:{Exception.errMsg}" + "<br>";
if(Exception.errMsgT == "d")
{
Content += $"當前數值:{Exception.errValue}" + "<br>";
}
Content += $"發生時間:{Exception.dev_time}";
foreach (var user in UserListWithPowerstation)
{
NoticeSchedule DaySchedule = new NoticeSchedule()
{
UserId = user.Id,
@ -77,11 +85,14 @@ namespace SolarPower.Quartz.Jobs
};
await noticeScheduleRepository.AddOneAsync(DaySchedule, properties);
var powerstation = await powerStationRepository.GetOneAsync(Exception.PowerStationId);
if(powerstation.line_token != null)
{
CallLineToken(Content, powerstation.line_token);
}
}
var powerstation = await powerStationRepository.GetOneAsync(Exception.PowerStationId);
if (powerstation.line_token != null)
{
Content = " %0D%0A " + Content.Replace("<br>", " %0D%0A ");
CallLineToken(Content, powerstation.line_token);
}
}
}

View File

@ -17,6 +17,8 @@ namespace SolarPower.Repository.Implement
tableName = "power_station";
}
public async Task<AnalysisStationCombine> GetPowerStationInfoList(ChartInput post)
{
var a = new AnalysisStationCombine();
@ -32,14 +34,33 @@ namespace SolarPower.Repository.Implement
{
case 0:
string timerange = Convert.ToDateTime(post.Timerange).ToString("yyyy-MM-dd");
sql = $@"SELECT m.*,n.*,o.* FROM
var today = "";
if(timerange == DateTime.Now.ToString("yyyy-MM-dd"))
{
today = @$" SELECT
AVG(a.today_irradiance) AS Now_irradiance
FROM
power_station a
WHERE a.Id IN @ids ";
}
else
{
today = $@" SELECT
AVG(a.Irradiance) AS Now_irradiance
FROM
sensor_history_day a
WHERE a.PowerStationId IN @ids AND DATE_FORMAT(a.TIMESTAMP,'%Y-%m-%d') = '{timerange}'";
}
sql = $@"SELECT m.*,n.*,o.*,p.* FROM
(
SELECT
SUM(TOTALMONEY) AS All_money,
SUM(TOTALKWH) AS All_kwh,
SUM(TOTALCARBON) AS All_Carbon
from power_station_history_month
WHERE PowerStationId IN @ids
from (SELECT psm.PowerStationId, max(psm.TIMESTAMP) AS TIMESTAMP FROM power_station_history_month psm WHERE PowerStationId IN @ids GROUP BY PowerStationId) a
LEFT JOIN power_station_history_month psm ON a.PowerStationId = psm.PowerStationId AND a.TIMESTAMP = psm.TIMESTAMP
)
AS m,
(
@ -60,22 +81,47 @@ namespace SolarPower.Repository.Implement
(
SELECT
AVG(avg_kwhkwp) AS All_KWH_KWP,
AVG(avg_PR) AS All_PR
AVG(avg_PR) AS All_PR,
AVG(avg_irradiance) as All_irradiance
from power_station
WHERE Id IN @ids
)
AS o";
AS o,
(
{today}
) AS p";
break;
case 1:
var time = post.Timerange.Split('-');
sql = $@"SELECT m.*,n.*,o.* FROM
var ttot = "";
if(time[1].Replace(" ","") == DateTime.Now.ToString("yyyy/MM/dd"))
{
ttot = @$"SELECT
AVG(c.Now_irradiance) AS Now_irradiance
FROM
(SELECT AVG(a.today_irradiance) AS Now_irradiance FROM power_station a WHERE a.Id IN (1)
UNION
SELECT AVG(b.Irradiance) AS Now_irradiance FROM sensor_history_day b
WHERE b.PowerStationId IN (1) AND DATE_FORMAT(b.TIMESTAMP, '%Y/%m/%d') BETWEEN '{time[0].Replace(" ", "")}' AND '{Convert.ToDateTime(time[1].Replace(" ", "")).AddDays(-1).ToString("yyyy/MM/dd")}') c";
}
else
{
ttot = @$" SELECT
AVG(a.Irradiance) AS Now_irradiance
FROM
sensor_history_day a
WHERE a.PowerStationId IN @ids AND DATE_FORMAT(a.TIMESTAMP, '%Y/%m/%d') BETWEEN '{time[0].Replace(" ", "")}' AND '{time[1].Replace(" ", "")}'";
}
sql = $@"SELECT m.*,n.*,o.*,p.* FROM
(
SELECT
SUM(TOTALMONEY) AS All_money,
SUM(TOTALKWH) AS All_kwh,
SUM(TOTALCARBON) AS All_Carbon
from power_station_history_month
WHERE PowerStationId IN @ids
from (SELECT psm.PowerStationId, max(psm.TIMESTAMP) AS TIMESTAMP FROM power_station_history_month psm WHERE PowerStationId IN @ids GROUP BY PowerStationId) a
LEFT JOIN power_station_history_month psm ON a.PowerStationId = psm.PowerStationId AND a.TIMESTAMP = psm.TIMESTAMP
)
AS m,
(
@ -92,21 +138,25 @@ namespace SolarPower.Repository.Implement
(
SELECT
AVG(avg_kwhkwp) AS All_KWH_KWP,
AVG(avg_PR) AS All_PR
AVG(avg_PR) AS All_PR,
AVG(avg_irradiance) as All_irradiance
from power_station
WHERE Id IN @ids
)
AS o";
AS o,
(
{ttot}
) AS p";
break;
case 2:
sql = $@"SELECT m.*,n.*,o.* FROM
sql = $@"SELECT m.*,n.*,o.*,p.* FROM
(
SELECT
SUM(TOTALMONEY) AS All_money,
SUM(TOTALKWH) AS All_kwh,
SUM(TOTALCARBON) AS All_Carbon
from power_station_history_month
WHERE PowerStationId IN @ids
from (SELECT psm.PowerStationId, max(psm.TIMESTAMP) AS TIMESTAMP FROM power_station_history_month psm WHERE PowerStationId IN @ids GROUP BY PowerStationId) a
LEFT JOIN power_station_history_month psm ON a.PowerStationId = psm.PowerStationId AND a.TIMESTAMP = psm.TIMESTAMP
)
AS m,
(
@ -123,21 +173,28 @@ namespace SolarPower.Repository.Implement
(
SELECT
AVG(avg_kwhkwp) AS All_KWH_KWP,
AVG(avg_PR) AS All_PR
AVG(avg_PR) AS All_PR,
AVG(avg_irradiance) as All_irradiance
from power_station
WHERE Id IN @ids
)
AS o";
AS o,
(
SELECT
AVG(a.Irradiance) AS Now_irradiance
from sensor_history_month a
WHERE PowerStationId IN @ids AND DATE_FORMAT(TIMESTAMP, '%Y-%m') = '{post.Timerange}'
) AS p";
break;
case 3:
sql = $@"SELECT m.*,n.*,o.* FROM
sql = $@"SELECT m.*,n.*,o.*,p.* FROM
(
SELECT
SUM(TOTALMONEY) AS All_money,
SUM(TOTALKWH) AS All_kwh,
SUM(TOTALCARBON) AS All_Carbon
from power_station_history_month
WHERE PowerStationId IN @ids
from (SELECT psm.PowerStationId, max(psm.TIMESTAMP) AS TIMESTAMP FROM power_station_history_month psm WHERE PowerStationId IN @ids GROUP BY PowerStationId) a
LEFT JOIN power_station_history_month psm ON a.PowerStationId = psm.PowerStationId AND a.TIMESTAMP = psm.TIMESTAMP
)
AS m,
(
@ -155,11 +212,18 @@ namespace SolarPower.Repository.Implement
(
SELECT
AVG(avg_kwhkwp) AS All_KWH_KWP,
AVG(avg_PR) AS All_PR
AVG(avg_PR) AS All_PR,
AVG(avg_irradiance) as All_irradiance
from power_station
WHERE Id IN @ids
)
AS o";
AS o,
(
SELECT
AVG(a.Irradiance) AS Now_irradiance
from sensor_history_month a
WHERE PowerStationId IN @ids AND DATE_FORMAT(TIMESTAMP, '%Y') = '{post.Timerange}'
) AS p";
break;
}
@ -192,57 +256,51 @@ namespace SolarPower.Repository.Implement
switch (post.SeacrhType)
{
case 0:
sql = $@"SELECT DATE_FORMAT(ps.TIMESTAMP,'%h %p') AS `Time`,
SUM(ps.KWH) AS KWH,
SUM(sh.Irradiance) AS Irradiance,
AVG(sh.Temperature) AS Temperature
FROM power_station_history_hour ps
LEFT JOIN sensor_history_hour sh
ON sh.TIMESTAMP = ps.TIMESTAMP AND sh.PowerStationId = ps.PowerStationId
WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m-%d') = '{post.Timerange}'
GROUP BY ps.TIMESTAMP";
sql = $@"SELECT DATE_FORMAT(p.TIMESTAMP,'%h %p') AS `Time`,
SUM(p.KWH) AS KWH,
SUM(s.Irradiance) AS Irradiance,
AVG(s.Temperature) AS Temperature
FROM (SELECT * FROM power_station_history_hour ps WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') = '{post.Timerange}') p
LEFT JOIN (SELECT * FROM sensor_history_hour sh WHERE sh.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m-%d') = '{post.Timerange}') s
ON p.TIMESTAMP = s.TIMESTAMP AND p.PowerStationId = s.PowerStationId
GROUP BY p.TIMESTAMP";
break;
case 1:
var time = post.Timerange.Replace(" ","").Split('-');
sql = $@"SELECT
DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') AS `Time`,
SUM(ps.TODAYKWH) AS KWH,
SUM(sh.Irradiance) AS Irradiance,
AVG(sh.Temperature) AS Temperature
FROM power_station_history_day ps
LEFT JOIN sensor_history_day sh
ON sh.TIMESTAMP = ps.TIMESTAMP
WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m-%d') BETWEEN '{time[0].Replace('/', '-')}' AND '{time[1].Replace('/', '-')}'
GROUP BY ps.TIMESTAMP";
DATE_FORMAT(p.TIMESTAMP,'%Y-%m-%d') AS `Time`,
SUM(p.TODAYKWH) AS KWH,
SUM(s.Irradiance) AS Irradiance,
AVG(s.Temperature) AS Temperature
FROM (SELECT * FROM power_station_history_day ps WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') BETWEEN '{time[0].Replace('/', '-')}' AND '{time[1].Replace('/', '-')}') p
LEFT JOIN (SELECT * FROM sensor_history_day sh WHERE sh.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m-%d') BETWEEN '{time[0].Replace('/', '-')}' AND '{time[1].Replace('/', '-')}') s
ON s.TIMESTAMP = p.TIMESTAMP AND p.PowerStationId = s.PowerStationId
GROUP BY p.TIMESTAMP";
break;
case 2:
sql = $@"SELECT
DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') AS `Time`,
SUM(ps.TODAYKWH) AS KWH,
SUM(sh.Irradiance) AS Irradiance,
AVG(sh.Temperature) AS Temperature
FROM power_station_history_day ps
LEFT JOIN sensor_history_day sh
ON sh.TIMESTAMP = ps.TIMESTAMP
WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m') = '{post.Timerange}'
GROUP BY ps.TIMESTAMP";
DATE_FORMAT(p.TIMESTAMP,'%Y-%m-%d') AS `Time`,
SUM(p.TODAYKWH) AS KWH,
SUM(s.Irradiance) AS Irradiance,
AVG(s.Temperature) AS Temperature
FROM (SELECT * FROM power_station_history_day ps WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m') = '{post.Timerange}') p
LEFT JOIN (SELECT * FROM sensor_history_day sh WHERE sh.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m') = '{post.Timerange}') s
ON s.TIMESTAMP = p.TIMESTAMP AND p.PowerStationId = s.PowerStationId
GROUP BY p.TIMESTAMP";
break;
case 3:
sql = $@"SELECT
DATE_FORMAT(ps.TIMESTAMP,'%Y-%m') AS `Time`,
SUM(ps.MONTHKWH) AS KWH,
SUM(sh.Irradiance) AS Irradiance,
AVG(sh.Temperature) AS Temperature
FROM power_station_history_month ps
LEFT JOIN sensor_history_month sh
ON sh.TIMESTAMP = ps.TIMESTAMP
WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y') = '{post.Timerange}'
GROUP BY ps.TIMESTAMP";
DATE_FORMAT(p.TIMESTAMP,'%Y-%m') AS `Time`,
SUM(p.MONTHKWH) AS KWH,
SUM(s.Irradiance) AS Irradiance,
AVG(s.Temperature) AS Temperature
FROM (SELECT * FROM power_station_history_month ps WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(ps.TIMESTAMP,'%Y') = '{post.Timerange}') p
LEFT JOIN (SELECT * FROM sensor_history_month sh WHERE sh.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y') = '{post.Timerange}') s
ON s.TIMESTAMP = p.TIMESTAMP AND p.PowerStationId = s.PowerStationId
GROUP BY p.TIMESTAMP";
break;
}
a = (await conn.QueryAsync<Chartoutput>(sql,new { ids = post.StationIds})).ToList();
}
catch (Exception exception)
{

View File

@ -122,7 +122,7 @@ namespace SolarPower.Repository.Implement
var sql = @$"SELECT aa.StartAt,aa.EndAt,aa.Kwh actualkwh,aa.Money actualMoney,SUM(pd.TODAYKWH) realKWH,SUM(pd.MONEY) realMoney,ps.Estimate_kwh CBAkwh,ps.EstimateEfficacy CBAeff ,ps.GeneratingCapacity capacity ,ps.PowerRate rate
FROM power_station_history_day pd
LEFT JOIN ( SELECT er.* FROM electricity_sold_record er WHERE {sqlwhere} AND er.Deleted = 0 ) aa
LEFT JOIN ( SELECT er.* FROM electricity_sold_record er WHERE {sqlwhere} AND er.Deleted = 0 AND er.PowerstationId = {info.PowerstationId}) aa
ON aa.PowerstationId = pd.PowerStationId
LEFT JOIN power_station ps ON ps.Id = pd.PowerStationId
WHERE pd.TIMESTAMP BETWEEN aa.StartAt AND aa.EndAt AND ps.Id = {info.PowerstationId} GROUP BY aa.Id";

View File

@ -625,7 +625,7 @@ namespace SolarPower.Repository.Implement
{
try
{
var sql = @$"SELECT us.* FROM power_station_operation_personnel ps LEFT JOIN user us ON ps.UserId = us.Id WHERE PowerStationId = {PowerStationId}";
var sql = @$"SELECT us.* FROM power_station_operation_personnel ps LEFT JOIN user us ON ps.UserId = us.Id WHERE ps.PowerStationId = {PowerStationId} and ps.Deleted = 0 AND us.Deleted = 0";
result = (await conn.QueryAsync<MyUser>(sql)).ToList();
}
catch (Exception exception)

View File

@ -663,7 +663,7 @@ namespace SolarPower.Repository.Implement
select a.id, site_id, `timestamp`, FROM_UNIXTIME((`timestamp` / 1000), '%Y-%m-%d %H:%i:%s') dev_time , a.sourceState err_status, FROM_UNIXTIME( (a.normalTime / 1000), '%Y-%m-%d %H:%i:%s') normalTime,
a.alarmClass, b.alarmClass as alarmClassName,ps.Name as PowerStationName,ps.Id as PowerStationId,
errDevice, err_valueKind, errValue, FROM_UNIXTIME( (a.lastUpdate / 1000), '%Y-%m-%d %H:%i:%s') lastUpdate,
case when c.errMsg_tw is null then d.errMsg_tw else c.errMsg_tw end errMsg
case when c.errMsg_tw is null then d.errMsg_tw else c.errMsg_tw end errMsg ,case when c.errMsg is null then d.errMsg else c.errMsg end errMsgT
from err_main a
join alarmorion_orionalarmclass b on a.alarmclass = b.id
left join ref_err_device c on trim(b.alarmClass) = c.deviceType

View File

@ -4473,9 +4473,9 @@ namespace SolarPower.Repository.Implement
sql_perSiteDB.Add(temp_sql);
}
sql = string.Join(" UNION ", sql_perSiteDB);
sql = "SELECT * FROM (" + string.Join(" UNION ", sql_perSiteDB) + ") a ORDER BY a.TIMESTAMP ASC";
result = (await conn.QueryAsync<InverterHistory>(sql, new { NowDay = nowDay })).ToList();
result = (await conn.QueryAsync<InverterHistory>(sql, new { NowDay = nowDay }, commandTimeout: 300)).ToList();
}
catch (Exception exception)
{
@ -4504,7 +4504,7 @@ namespace SolarPower.Repository.Implement
var temp_sql = $@"SELECT
DATE_FORMAT(inv.TIMESTAMP, '%Y-%m-%d') AS TIMESTAMP,
INVERTERID,
inv.INVERTERID,
i.InverterName AS INVERTERName,
inv.Irradiance,
inv.KWH,
@ -4523,7 +4523,7 @@ namespace SolarPower.Repository.Implement
sql_perSiteDB.Add(temp_sql);
}
sql = string.Join(" UNION ", sql_perSiteDB);
sql = "SELECT * FROM (" + string.Join(" UNION ", sql_perSiteDB) + ") a ORDER BY a.TIMESTAMP ASC";
result = (await conn.QueryAsync<InverterHistory>(sql, new { StartDay = startDay, EndDay = endDay })).ToList();
}
@ -4554,7 +4554,7 @@ namespace SolarPower.Repository.Implement
var temp_sql = $@"SELECT
DATE_FORMAT(inv.TIMESTAMP, '%Y-%m-%d') AS TIMESTAMP,
INVERTERID,
inv.INVERTERID,
i.InverterName AS INVERTERName,
inv.KWH,
inv.TODAYKWH,
@ -5338,7 +5338,7 @@ namespace SolarPower.Repository.Implement
SELECT api.Item, api.ItemName
FROM apicall api
LEFT join
(SELECT * FROM {dbname}.power_station_exception ex WHERE ex.Deleted = 0) a
(SELECT * FROM {dbname}.power_station_exception ex WHERE ex.Deleted = 0 AND ex.PowerStationId = {powerStationId}) a
ON a.`Type` = api.Item
WHERE api.PowerStationId = {powerStationId}
AND ISNULL(a.Id)

View File

@ -243,7 +243,7 @@ namespace SolarPower.Repository.Implement
break;
}
a = await conn.QueryAsync<dynamic>(sql);
a = await conn.QueryAsync<dynamic>(sql, commandTimeout: 300);
}
catch (Exception exception)
{
@ -257,6 +257,52 @@ namespace SolarPower.Repository.Implement
}
}
public async Task<int> CheckExcelAsync(Select_table post)
{
using (IDbConnection conn = _databaseHelper.GetConnection())
{
int a;
conn.Open();
try
{
string sql = "";
switch ( post.FormType )
{
case 0:
sql = @$"select Id from power_station_history_day where powerstationid = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') = '{post.Time}'";
break;
case 1:
if(post.SearchType == 2)
{
sql = @$"select Id from power_station_history_month where powerstationid = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y-%m') = '{post.Time}'";
}
else
{
var times = post.Time.Replace('-', 'a').Replace('/', '-').Replace(" ", "").Split('a');
sql = @$"select Id from power_station_history_day where powerstationid = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') BETWEEN '{times[0]}' AND '{times[1]}'";
}
break;
case 3:
sql = @$"select Id from power_station_history_month where powerstationid = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y') = '{post.Time}'";
break;
}
a = await conn.QueryFirstOrDefaultAsync<int>(sql);
}
catch (Exception exception)
{
throw exception;
}
finally
{
conn.Close();
}
return a;
}
}
public async Task<List<Landinfo>> GetHire (PsIdAndSiteDB post)
{
List<Landinfo> result = new List<Landinfo>();

View File

@ -13,5 +13,6 @@ namespace SolarPower.Repository.Interface
Task<List<Landinfo>> GetHire(PsIdAndSiteDB post);
Task<List<MaxFormbody>> GetMaxtablebody(Select_table2 post);
Task<dynamic> Findhaveinv(Select_table post);
Task<int> CheckExcelAsync(Select_table post);
}
}

View File

@ -111,6 +111,25 @@
</div>
</div>
}
else
{
<div class="card">
<div class="card-header bg-fusion-25 pr-3 d-flex align-items-center flex-wrap">
<h4 class="mb-0 font-weight-bold"><span class="fal fa-sun mr-1"></span> 日照度</h4>
<div class="ml-auto">k W/m<sup>2</sup></div>
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p id="today_irradiance_label">當日日照度</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_irradiance">0.00</span></p>
</div>
<div class="d-flex justify-content-between">
<p>平均日照度(30天)</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="total_irradiance">0.00</span></p>
</div>
</div>
</div>
}
<div class="card">
<div class="card-header bg-fusion-25 pr-3 d-flex align-items-center flex-wrap">
<h4 class="mb-0 font-weight-bold"><span class="fal fa-bolt mr-1"></span> PR值</h4>
@ -309,7 +328,7 @@
$("#today_kwhkwp_label").html(timename + "有效日照時數");
$("#today_PR_label").html(timename + "PR值");
$("#today_carbon_label").html(timename + "減碳量");
$("#today_irradiance_label").html(timename + "日照度");
if (type == 1) {
timerange = $('#DateGettext').val();
@ -411,7 +430,7 @@
$('#total_kwhkwp').html(rel.data.all_KWH_KWP.toFixed(2));
$('#total_PR').html(rel.data.all_PR.toFixed(2));
$('#total_carbon').html(rel.data.all_Carbon.toFixed(2));
$('#total_irradiance').html(rel.data.all_Carbon.toFixed(2));
$('#total_irradiance').html(rel.data.all_irradiance.toFixed(2));
$('#today_kwh').html(rel.data.now_kwh.toFixed(2));
@ -419,7 +438,7 @@
$('#today_kwhkwp').html(rel.data.now_KWH_KWP.toFixed(2));
$('#today_PR').html(rel.data.now_PR.toFixed(2));
$('#today_carbon').html(rel.data.now_Carbon.toFixed(2));
$('#today_irradiance').html(rel.data.now_Carbon.toFixed(2));
$('#today_irradiance').html(rel.data.now_irradiance.toFixed(2));
chart();
})

View File

@ -250,6 +250,9 @@
'render': function (data, type, full, meta) {
return '<img src="' + data + '?v=' + Date.now() + '" width="200px" height="40px">';
}
},{
'targets': 8,
'visible': false
}],
"language": {
"emptyTable": "查無資料",

View File

@ -20,7 +20,7 @@
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p>即時總發電量</p>
<p>今日總發電量</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_kwh">0.00</span></p>
</div>
<div class="d-flex justify-content-between">
@ -36,7 +36,7 @@
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p>即時平均日照度</p>
<p>今日日照度</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_irradiance">0.00</span></p>
</div>
<div class="d-flex justify-content-between">
@ -52,7 +52,7 @@
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p>即時平均 PR 值</p>
<p>今日 PR 值</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_PR">0.00</span></p>
</div>
<div class="d-flex justify-content-between">
@ -68,7 +68,7 @@
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p>即時平均有效日照時數</p>
<p>今日有效日照時數(kwh/kwp)</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_kwhkwp">0.00</span></p>
</div>
<div class="d-flex justify-content-between">
@ -171,7 +171,8 @@
@section Scripts{
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
@*<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>*@
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBF-NZ6zKpzthzB8cgFYVfAWPu_ZhSFR1c&callback=initMap" async></script>
<script src="https://unpkg.com/@@googlemaps/markerclustererplus/dist/index.min.js"></script>
<script>
@ -278,9 +279,9 @@
'<div id="bodyContent">' +
'<div class="row">' +
'<div class="col-12">' +
'<div>今日發電量(kW h)' + item.today_kWh + '</div>'+
'<div>今日發電量(kW h)' + item.today_kWh.toFixed(2) + '</div>'+
'<div>今日日照度(k W/m<sup>2</sup>)' + item.today_irradiance + '</div>'+
'<div>今日發電小時(hr)' + item.solarHour + '</div>' +
'<div>有效日照時數(kwh/kwp)' + item.today_kwhkwp.toFixed(2) + '</div>' +
'<div>裝置容量(kWp)' + item.generatingCapacity.toFixed(3) + '</div>' +
'<div>掛錶日期:' + item.electricityMeterAt + '</div>' +
'<div>天氣:' + item.wx + '</div>'+

View File

@ -211,8 +211,13 @@
<select class="form-control" id="fix_firm_select_modal"></select>
</div>
</div>
<div class="col-lg-6 mt-5">
<div class="custom-control custom-checkbox d-flex align-content-center">
<input type="checkbox" class="custom-control-input" id="EmailcheckBox">
<label class="custom-control-label" for="EmailcheckBox">發送Email通知</label>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-12">
<div class="form-group">
@ -707,7 +712,7 @@
$("#work_time_modal-error").hide();
$("#EmailcheckBox").prop("checked", false);
$("#record-form-modal").modal();
}
//#endregion
@ -1038,7 +1043,7 @@
$("#EmailcheckBox").prop("checked", false);
$("#record-form-modal").modal();
}, 'json');
});
@ -1057,94 +1062,87 @@
//#region 儲存表單資料
function SaveRecord() {
if ($('#work_person_select_modal').val().length > 0 && $("#work_time_modal").val() != "") {
Swal.fire(
{
title: "儲存",
text: "你確定是否儲存此筆資料?\r\n 儲存成功後將會發送Email至負責人員及廠商",
type: "warning",
icon: 'warning',
showCancelButton: true,
confirmButtonText: "是",
cancelButtonText: "否"
}).then(function (result) {
if (result.value) {
if ($("#record-form").valid()) {
var url = "/Operation/SaveOperationRecord";
if ($("#record-form").valid())
{
var url = "/Operation/SaveOperationRecord";
var formData = new FormData();
var formData = new FormData();
@*var work_person_ids = $.map($("#work_person_select_modal").val(), function (item) {
return parseInt(item);
}) *@
@*var work_person_ids = $.map($("#work_person_select_modal").val(), function (item) {
return parseInt(item);
}) *@
formData.append("Id", selected_id);
formData.append("PowerStationId", $("#power_station_select_modal").val());
formData.append("WorkType", selected_work_type);
formData.append("ErrorCode", $("#error_code_modal").val());
formData.append("FixDo", $("#fix_do_modal").val());
formData.append("FixFirm", $("#fix_firm_select_modal").val());
formData.append("Status", $("input[name=status_modal]:checked").val());
$("#work_person_select_modal").val().forEach(function (item) {
formData.append("WorkPersonIds", parseInt(item));
});
formData.append("WorkTime", $("#work_time_modal").val());
formData.append("Notice", $("#notice_textarea_modal").val());
formData.append("Description", $("#description_textarea_modal").val());
formData.append("Id", selected_id);
formData.append("PowerStationId", $("#power_station_select_modal").val());
formData.append("WorkType", selected_work_type);
formData.append("ErrorCode", $("#error_code_modal").val());
formData.append("FixDo", $("#fix_do_modal").val());
formData.append("FixFirm", $("#fix_firm_select_modal").val());
formData.append("Status", $("input[name=status_modal]:checked").val());
$("#work_person_select_modal").val().forEach(function (item) {
formData.append("WorkPersonIds", parseInt(item));
});
formData.append("WorkTime", $("#work_time_modal").val());
formData.append("Notice", $("#notice_textarea_modal").val());
formData.append("Description", $("#description_textarea_modal").val());
if (document.querySelector('[id=EmailcheckBox]:checked')) {
formData.append("Emailcheck", 1);
}
else {
formData.append("Emailcheck", 0);
}
$.ajax({
type: "POST",
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (rel) {
if (rel.code != "0000") {
toast_error(rel.msg);
return;
}
$.ajax({
type: "POST",
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (rel) {
if (rel.code != "0000") {
toast_error(rel.msg);
return;
}
var myDropzone = Dropzone.forElement("#record-file-form");
var myDropzone = Dropzone.forElement("#record-file-form");
if (myDropzone.files.length > 0) {
if (myDropzone.files.length > 0) {
selected_id = rel.data;
selected_id = rel.data;
myDropzone.processQueue();
myDropzone.processQueue();
myDropzone.on("successmultiple", function (file, rel) {
if (rel.code != "0000") {
toast_error(rel.msg);
return;
}
toast_ok(rel.msg);
$('#record-form-modal').modal('hide');
recordFileDropzone.removeAllFiles();
if (status == 2) {
operationRecordTable.column(10).visible(true);
}
else {
operationRecordTable.column(10).visible(false);
}
operationRecordTable.ajax.reload();
});
} else {
$('#record-form-modal').modal('hide');
myDropzone.removeAllFiles();
if (status == 2) {
operationRecordTable.column(10).visible(true);
}
else {
operationRecordTable.column(10).visible(false);
}
operationRecordTable.ajax.reload();
}
myDropzone.on("successmultiple", function (file, rel) {
if (rel.code != "0000") {
toast_error(rel.msg);
return;
}
toast_ok(rel.msg);
$('#record-form-modal').modal('hide');
recordFileDropzone.removeAllFiles();
if (status == 2) {
operationRecordTable.column(10).visible(true);
}
else {
operationRecordTable.column(10).visible(false);
}
operationRecordTable.ajax.reload();
});
} else {
$('#record-form-modal').modal('hide');
myDropzone.removeAllFiles();
if (status == 2) {
operationRecordTable.column(10).visible(true);
}
else {
operationRecordTable.column(10).visible(false);
}
operationRecordTable.ajax.reload();
}
}
});
}
}
else
{

View File

@ -1,5 +1,5 @@
@{
ViewData["MainNum"] = "6";
ViewData["MainNum"] = "8";
ViewData["SubNum"] = "1";
ViewData["Title"] = "電站管理";
}

View File

@ -1,5 +1,5 @@
@{
ViewData["MainNum"] = "6";
ViewData["MainNum"] = "8";
ViewData["SubNum"] = "1";
ViewData["Title"] = "電站管理";
}
@ -812,7 +812,12 @@
powerStationSingleLineCard = $("#power-station-single-line-card > .row");
powerStationSingleLineCard.empty();
rel.data.forEach(function (value, index) {
CreatePowerStationSingleLineBox(powerStationSingleLineCard, value);
var split = value.image.split(".");
if (split[split.length - 1].toLowerCase() == "pdf") {
CreatePowerStationSingleLineBoxPDF(powerStationSingleLineCard, value);
} else {
CreatePowerStationSingleLineBox(powerStationSingleLineCard, value);
}
});
@ -2870,7 +2875,7 @@
//#region 單線圖 Dropzone
var powerStationSingleLineDropzone = new Dropzone("#power-station-single-line-form", {
url: "/PowerStation/SavePowerStationSingleLine",
acceptedFiles: "image/*",
acceptedFiles: "image/*,application/pdf",
autoProcessQueue: false,
parallelUploads: 5,
maxFiles: 5,
@ -2914,7 +2919,14 @@
powerStationSingleLineCard = $("#power-station-single-line-card > .row");
powerStationSingleLineCard.empty();
rel.data.forEach(function (value, index) {
CreatePowerStationSingleLineBox(powerStationSingleLineCard, value);
var split = value.image.split(".");
if (split[split.length - 1].toLowerCase() == "pdf") {
CreatePowerStationSingleLineBoxPDF(powerStationSingleLineCard, value);
} else {
CreatePowerStationSingleLineBox(powerStationSingleLineCard, value);
}
});
});
@ -2937,6 +2949,24 @@
}
//#endregion
//#region 創建單線圖PDFbox
function CreatePowerStationSingleLineBoxPDF(dom, value) {
var str = '<div class="col-xl" style="max-width: 20%;">' +
'<div class="card border m-auto m-lg-0" style="padding: 9.5px;">' +
'<a href="' + value.image + '" download>' +
'<img src="/img/pdf.png" class="card-img-top " alt="...">' +
'</a>'+
'<a href="javascript:void(0);" class="btn btn-danger btn-lg btn-icon rounded-circle waves-effect waves-themed position-absolute pos-top pos-right del-power-station-single-line-btn" data-id="' + value.id + '">' +
'<i class="fal fa-times"></i>' +
'</a>' +
'</div>' +
'</div>';
dom.append(str);
}
//#endregion
//#region 刪除單線圖
$('#power-station-single-line-card').on("click", "a.del-power-station-single-line-btn", function () {

View File

@ -151,7 +151,7 @@
<div class="col-xl-3 row justify-content-center align-items-center">
<label class="col-xl-4 form-label" id="coordinate_label" for="coordinate">Line Token</label>
<div class="col-xl-8">
<label id="line_token_text" class="color-info-600"></label>
<label id="line_token_text" class="color-info-600" style="word-break: break-all"></label>
<input type="text" id="line_token" name="line_token" class="form-control">
</div>
</div>

View File

@ -41,7 +41,7 @@
<div class="card-title font-weight-bold">單線圖</div>
<div class="text-right">
<a href="javascript:;" class="btn btn-sm btn-success ml-auto waves-effect waves-themed" id="upload-station-single-line">
<span class="fal fa-plus mr-1"></span> 上傳圖片
<span class="fal fa-plus mr-1"></span> 上傳檔案
</a>
</div>
</div>

View File

@ -154,12 +154,12 @@
-->
<ul id="js-nav-menu" class="nav-menu">
<!--<li class="active">
<a href="blank.html" title="Blank Project" data-filter-tags="blank page">
<i class="fal fa-globe"></i>
<span class="nav-link-text" data-i18n="nav.blankpage">Blank Project</span>
</a>
</li>
<li class="nav-title">Navigation Title</li>-->
<a href="blank.html" title="Blank Project" data-filter-tags="blank page">
<i class="fal fa-globe"></i>
<span class="nav-link-text" data-i18n="nav.blankpage">Blank Project</span>
</a>
</li>
<li class="nav-title">Navigation Title</li>-->
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("MapOverview") || ViewBag.auths.Contains("StationOverview"))
{
<li class="@(ViewData["MainNum"] == "1" ? "active open" : "")">
@ -176,14 +176,14 @@
</a>
</li>
}
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin
|| ViewBag.auths.Contains("StationOverview_UpToDate")
|| ViewBag.auths.Contains("StationOverview_Info")
|| ViewBag.auths.Contains("StationOverview_InverterInfo")
|| ViewBag.auths.Contains("StationOverview_Inverter")
|| ViewBag.auths.Contains("StationOverview_History")
|| ViewBag.auths.Contains("StationOverview_Exception")
|| ViewBag.auths.Contains("StationOverview_OperationRecord"))
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin
|| ViewBag.auths.Contains("StationOverview_UpToDate")
|| ViewBag.auths.Contains("StationOverview_Info")
|| ViewBag.auths.Contains("StationOverview_InverterInfo")
|| ViewBag.auths.Contains("StationOverview_Inverter")
|| ViewBag.auths.Contains("StationOverview_History")
|| ViewBag.auths.Contains("StationOverview_Exception")
|| ViewBag.auths.Contains("StationOverview_OperationRecord"))
{
<li class="@(ViewData["MainNum"] == "1" && ViewData["SubNum"] == "2" ? "active" : "")">
<a asp-controller="StationOverview" asp-action="Index" title="電站總覽" data-filter-tags="utilities disabled item">
@ -196,13 +196,13 @@
}
<!-- Example of open and active states -->
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin
|| ViewBag.auths.Contains("StationOverview_UpToDate")
|| ViewBag.auths.Contains("StationOverview_Info")
|| ViewBag.auths.Contains("StationOverview_InverterInfo")
|| ViewBag.auths.Contains("StationOverview_Inverter")
|| ViewBag.auths.Contains("StationOverview_History")
|| ViewBag.auths.Contains("StationOverview_Exception")
|| ViewBag.auths.Contains("StationOverview_OperationRecord"))
|| ViewBag.auths.Contains("StationOverview_UpToDate")
|| ViewBag.auths.Contains("StationOverview_Info")
|| ViewBag.auths.Contains("StationOverview_InverterInfo")
|| ViewBag.auths.Contains("StationOverview_Inverter")
|| ViewBag.auths.Contains("StationOverview_History")
|| ViewBag.auths.Contains("StationOverview_Exception")
|| ViewBag.auths.Contains("StationOverview_OperationRecord"))
{
<li class="@(ViewData["MainNum"] == "2" ? "active open" : "")">
<a href="javascript:void(0);" title="電站資訊" data-filter-tags="category">
@ -236,17 +236,17 @@
}
@*<li class="@(ViewData["MainNum"] == "2" && ViewData["SubNum"].ToString() == ViewBag.myPowerStationSummaries.Count.ToString() ? "active" : "")">
<a asp-controller="PowerStation" asp-action="Index" title="電站管理" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">電站管理</span>
</a>
</li>*@
<a asp-controller="PowerStation" asp-action="Index" title="電站管理" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">電站管理</span>
</a>
</li>*@
</ul>
</li>
}
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin
|| ViewBag.auths.Contains("AnalysisStationCombine")
|| ViewBag.auths.Contains("AnalysisStationInfo")
|| ViewBag.auths.Contains("AnalysisInverter"))
|| ViewBag.auths.Contains("AnalysisStationCombine")
|| ViewBag.auths.Contains("AnalysisStationInfo")
|| ViewBag.auths.Contains("AnalysisInverter"))
{
<li class="@(ViewData["MainNum"] == "3" ? "active open" : "")">
<a href="#" title="交叉分析" data-filter-tags="category">
@ -282,10 +282,10 @@
</li>
}
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin
|| ViewBag.auths.Contains("StationReport")
|| ViewBag.auths.Contains("ElectricitySoldRecord")
|| ViewBag.auths.Contains("PowerGeneration")
|| ViewBag.auths.Contains("NoticeSchedule"))
|| ViewBag.auths.Contains("StationReport")
|| ViewBag.auths.Contains("ElectricitySoldRecord")
|| ViewBag.auths.Contains("PowerGeneration")
|| ViewBag.auths.Contains("NoticeSchedule"))
{
<li class="@(ViewData["MainNum"] == "4" ? "active open" : "")">
<a href="#" title="報表查詢" data-filter-tags="category">
@ -295,38 +295,38 @@
<ul>
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("StationReport"))
{
<li class="@(ViewData["MainNum"] == "4" && ViewData["SubNum"].ToString() == "1" ? "active" : "")">
<a asp-controller="StationReport" asp-action="Index" title="電站報表" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">電站報表</span>
</a>
</li>
<li class="@(ViewData["MainNum"] == "4" && ViewData["SubNum"].ToString() == "1" ? "active" : "")">
<a asp-controller="StationReport" asp-action="Index" title="電站報表" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">電站報表</span>
</a>
</li>
}
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("ElectricitySoldRecord"))
{
<li class="@(ViewData["MainNum"] == "4" && ViewData["SubNum"].ToString() == "2" ? "active" : "")">
<a asp-controller="ElectricitySoldRecord" asp-action="Index" title="台電售電記錄" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">台電售電記錄</span>
</a>
</li>
<li class="@(ViewData["MainNum"] == "4" && ViewData["SubNum"].ToString() == "2" ? "active" : "")">
<a asp-controller="ElectricitySoldRecord" asp-action="Index" title="台電售電記錄" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">台電售電記錄</span>
</a>
</li>
}
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("PowerGeneration"))
{
<li class="@(ViewData["MainNum"] == "4" && ViewData["SubNum"].ToString() == "3" ? "active" : "")">
<a asp-controller="PowerGeneration" asp-action="Index" title="電站發電收入" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">電廠發電效能統計</span>
</a>
</li>
<li class="@(ViewData["MainNum"] == "4" && ViewData["SubNum"].ToString() == "3" ? "active" : "")">
<a asp-controller="PowerGeneration" asp-action="Index" title="電站發電收入" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">電廠發電效能統計</span>
</a>
</li>
}
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("NoticeSchedule"))
{
<li class="@(ViewData["MainNum"] == "4" && ViewData["SubNum"].ToString() == "4" ? "active" : "")">
<a asp-controller="NoticeSchedule" asp-action="Index" title="報告發送記錄" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">報告發送記錄</span>
</a>
</li>
<li class="@(ViewData["MainNum"] == "4" && ViewData["SubNum"].ToString() == "4" ? "active" : "")">
<a asp-controller="NoticeSchedule" asp-action="Index" title="報告發送記錄" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">報告發送記錄</span>
</a>
</li>
}
</ul>
</li>
@ -348,8 +348,23 @@
</ul>
</li>
}
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("PowerStation") || ViewBag.auths.Contains("Operation") || ViewBag.auths.Contains("OperationRecord"))
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("PowerStationManager"))
{
<li class="@(ViewData["MainNum"] == "8" ? "active open" : "")">
<a href="#" title="電站管理" data-filter-tags="category">
<i class="fal fa-cogs"></i>
<span class="nav-link-text" data-i18n="nav.category">電站管理</span>
</a>
<ul>
<li class="@(ViewData["MainNum"] == "8" && ViewData["SubNum"].ToString() == "1" ? "active" : "")">
<a asp-controller="PowerStation" asp-action="Index" title="電站管理" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">電站管理</span>
</a>
</li>
</ul>
</li>
}
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("Operation") || ViewBag.auths.Contains("OperationRecord"))
{
<li class="@(ViewData["MainNum"] == "6" ? "active open" : "")">
<a href="#" title="運維管理" data-filter-tags="category">
@ -357,14 +372,7 @@
<span class="nav-link-text" data-i18n="nav.category">運維管理</span>
</a>
<ul>
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("PowerStation"))
{
<li class="@(ViewData["MainNum"] == "6" && ViewData["SubNum"].ToString() == "1" ? "active" : "")">
<a asp-controller="PowerStation" asp-action="Index" title="電站管理" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">電站管理</span>
</a>
</li>
}
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("Operation"))
{
<li class="@(ViewData["MainNum"] == "6" && ViewData["SubNum"] == "2" ? "active" : "")">
@ -410,21 +418,21 @@
</li>
}
@*@if (ViewBag.auths.Contains("User"))
{
<li class="">
<a href="javascript:void(0);" title="功能清單" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">功能清單</span>
</a>
</li>
}
@if (ViewBag.auths.Contains("User"))
{
<li class="">
<a href="javascript:void(0);" title="定時任務設定" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">定時任務設定</span>
</a>
</li>
}*@
{
<li class="">
<a href="javascript:void(0);" title="功能清單" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">功能清單</span>
</a>
</li>
}
@if (ViewBag.auths.Contains("User"))
{
<li class="">
<a href="javascript:void(0);" title="定時任務設定" data-filter-tags="utilities disabled item">
<span class="nav-link-text" data-i18n="nav.utilities_disabled_item">定時任務設定</span>
</a>
</li>
}*@
</ul>
</li>
}

View File

@ -94,7 +94,7 @@
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p>即時平均日照度</p>
<p>今日日照度</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_irradiance">0.00</span></p>
</div>
<div class="d-flex justify-content-between">
@ -110,7 +110,7 @@
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p>即時平均 PR 值</p>
<p>今日 PR 值</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_PR">0.00</span></p>
</div>
<div class="d-flex justify-content-between">
@ -126,7 +126,7 @@
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p>即時平均有效日照時數</p>
<p>今日有效日照時數(kwh/kwp)</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_kwhkwp">0.00</span></p>
</div>
<div class="d-flex justify-content-between">
@ -432,7 +432,7 @@
@if (ViewBag.myUser.Role.Auths.Contains("ShowMoney"))
{
<text>
$('#card_' + val.id).find('#PowerRate').html((val.today_kWh * val.powerRate).toFixed());
$('#card_' + val.id).find('#PowerRate').html((val.today_Money).toFixed());
</text>
}
$('#card_' + val.id).find('#PR').html(val.today_PR);

View File

@ -1,6 +1,6 @@
@{
ViewData["MainNum"] = "1";
ViewData["SubNum"] = "2";
ViewData["MainNum"] = "2";
//ViewData["SubNum"] = "2";
ViewData["Title"] = "電站總覽";
}
@using SolarPower.Models.Role
@ -19,15 +19,15 @@
<div class="panel-container show">
<div class="panel-content">
<div class="row subheader d-flex justify-content-between">
<div class="col-xl-2">
<div class="col-xl-4">
<h1 class="subheader-title">
<span id="power-station-healthStatus"></span>
<span id="power-station-title">新竹巨城站</span>
<span id="power-station-title">電站名稱</span>
</h1>
</div>
<div class="col-xl-3 d-flex justify-content-start">
<p class="card-text px-3"><i class="fal fa-cloud-sun-rain fa-3x" id="weather-icon"></i></p>
<p class="font-weight-bold" id="weather-temp">27°C<br>降雨幾率: 15%</p>
<p class="font-weight-bold" id="weather-temp">27°C<br>降雨幾率: 0%</p>
</div>
</div>
<ul class="nav nav-tabs mb-5" role="tablist">
@ -319,7 +319,7 @@
labels: chartToday.labels,
datasets: [{
type: 'bar',
label: '輸出功率',
label: '發電量',
yAxisID: 'A',
backgroundColor: 'rgb(103, 180, 172)',
order: 3,
@ -411,7 +411,7 @@
labels: chart7day.labels,
datasets: [{
type: 'bar',
label: '輸出功率',
label: '發電量',
yAxisID: 'A',
backgroundColor: 'rgb(103, 180, 172)',
order: 3,
@ -503,7 +503,7 @@
labels: chartMonth.labels,
datasets: [{
type: 'bar',
label: '輸出功率',
label: '發電量',
yAxisID: 'A',
backgroundColor: 'rgb(103, 180, 172)',
order: 3,
@ -595,7 +595,7 @@
labels: chartYear.labels,
datasets: [{
type: 'bar',
label: '輸出功率',
label: '發電量',
yAxisID: 'A',
backgroundColor: 'rgb(103, 180, 172)',
order: 2,
@ -951,6 +951,32 @@
$("#work_person_select_modal").val(record.workPersonId);
}
}
$("#work_person_select_modal").select2({ dropdownParent: $('#record-form-modal') });
});
//查詢該電站的廠商
var url_power_station_firm = "/PowerStation/GetFirmSelectOptionList";
$.post(url_power_station_firm, send_data, function (rel) {
if (rel.code != "0000") {
toast_error(rel.msg);
return;
}
$("#fix_firm_select_modal").empty();
if (rel.data.length > 0) {
$.each(rel.data, function (index, val) {
$("#fix_firm_select_modal").append($("<option />").val(val.value).text(val.text));
});
}
$("#fix_firm_select_modal").val($("#fix_firm_select_modal option:first").val()).trigger('change');
if (record != undefined && record != null) {
$("#fix_firm_select_modal").val(record.fixFirm)
}
});
});
//#endregion
@ -1510,7 +1536,7 @@
status = 1;
}
$("input[name=status_modal_opRecord][value='" + status + "']").prop('checked', true); //狀態
$('#work_person_select_modal').val(record.workPersonId);
$('#work_person_select_modal').val(record.workPersonId).trigger("change");;
if (work_type != 2) {
$(".fix-div").hide();
} else {
@ -1518,6 +1544,7 @@
$("#error_code_modal").val(record.errorCode);
$("#fix_do_modal").val(record.fixDo);
}
$("#fix_firm_select_modal").val(record.fixFirm).trigger("change");
$("#notice_textarea_modal").val(record.notice);
$("#description_textarea_modal").val(record.description);
@ -1528,12 +1555,22 @@
record.recordFiles.forEach(function (value, index) {
CreateRecordFileBox(RecordFileBox, value, true);
});
$("#EmailcheckBox").prop("checked", false);
$("#record-form-modal").modal();
}, 'json');
});
//#endregion
//#region 表單驗證
$("#record-form").validate({
rules: {
work_time_modal: {
required: true
}
},
});
//#endregion
//#region 表單檔案資料(運維)
Dropzone.autoDiscover = false;
recordFileDropzone = new Dropzone("#record-file-form", {
@ -1582,65 +1619,96 @@
}
//#endregion
$('#work_person_select_modal').change(function () {
if ($('#work_person_select_modal').val().length == 0) {
$('#work_person_select_modal-error').show();
} else {
$('#work_person_select_modal-error').hide();
}
});
$('#work_time_modal').change(function () {
$("#work_time_modal-error").hide();
});
//#region 儲存表單資料(運維)
function SaveRecord() {
if ($('#work_person_select_modal').val().length > 0 && $("#work_time_modal").val() != "")
{
if ($("#record-form").valid()) {
var url = "/Operation/SaveOperationRecord";
if ($("#record-form").valid()) {
var url = "/Operation/SaveOperationRecord";
var formData = new FormData();
var formData = new FormData();
formData.append("Id", selected_id);
formData.append("PowerStationId", $("#power_station_select_modal").val());
formData.append("WorkType", selected_work_type);
formData.append("ErrorCode", $("#error_code_modal").val());
formData.append("FixDo", $("#fix_do_modal").val());
formData.append("FixFirm", $("#fix_firm_select_modal").val());
formData.append("Status", $("input[name=status_modal_opRecord]:checked").val());
$("#work_person_select_modal").val().forEach(function (item) {
formData.append("WorkPersonIds", parseInt(item));
});
formData.append("WorkTime", $("#work_time_modal").val());
formData.append("Notice", $("#notice_textarea_modal").val());
formData.append("Description", $("#description_textarea_modal").val());
if (document.querySelector('[id=EmailcheckBox]:checked')) {
formData.append("Emailcheck", 1);
}
else {
formData.append("Emailcheck", 0);
}
$.ajax({
type: "POST",
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (rel) {
if (rel.code != "0000") {
toast_error(rel.msg);
return;
}
formData.append("Id", selected_id);
formData.append("PowerStationId", $("#power_station_select_modal").val());
formData.append("WorkType", selected_work_type);
formData.append("ErrorCode", $("#error_code_modal").val());
formData.append("FixDo", $("#fix_do_modal").val());
formData.append("Status", $("input[name=status_modal_opRecord]:checked").val());
formData.append("WorkPersonId", $("#work_person_select_modal").val());
formData.append("WorkTime", $("#work_time_modal").val());
formData.append("Notice", $("#notice_textarea_modal").val());
formData.append("Description", $("#description_textarea_modal").val());
var myDropzone = Dropzone.forElement("#record-file-form");
$.ajax({
type: "POST",
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (rel) {
if (rel.code != "0000") {
toast_error(rel.msg);
return;
}
if (myDropzone.files.length > 0) {
selected_id = rel.data;
myDropzone.processQueue();
var myDropzone = Dropzone.forElement("#record-file-form");
myDropzone.on("successmultiple", function (file, rel) {
if (rel.code != "0000") {
toast_error(rel.msg);
return;
}
if (myDropzone.files.length > 0) {
selected_id = rel.data;
myDropzone.processQueue();
toast_ok(rel.msg);
$('#record-form-modal').modal('hide');
recordFileDropzone.removeAllFiles();
myDropzone.on("successmultiple", function (file, rel) {
if (rel.code != "0000") {
toast_error(rel.msg);
return;
}
toast_ok(rel.msg);
operationRecordTable.ajax.reload();
});
} else {
$('#record-form-modal').modal('hide');
recordFileDropzone.removeAllFiles();
myDropzone.removeAllFiles();
operationRecordTable.ajax.reload();
});
} else {
$('#record-form-modal').modal('hide');
myDropzone.removeAllFiles();
operationRecordTable.ajax.reload();
}
}
}
});
});
}
}
else {
if ($('#work_person_select_modal').val().length == 0) {
$('#work_person_select_modal-error').show();
}
if ($("#work_time_modal").val() == "") {
$("#work_time_modal-error").show();
}
}
}
//#endregion
@ -2010,7 +2078,7 @@
},
title: {
text: '逆變器單日kWhkWp'
text: '各逆變器當日有效日照時數'
},
xAxis: {
categories: HeatMap.xAxis,
@ -2744,9 +2812,15 @@
return;
}
$("#Invertercard-Name").html(rel.data.name);
$("#Invertercard-kwh").html(rel.data.kwh);
$("#Invertercard-money").html(rel.data.today_Money.toFixed());
$("#Invertercard-pr").html(rel.data.today_PR);
$("#Invertercard-kwh").html(rel.data.kwh.toFixed(2));
@if (ViewBag.myUser.Role.Auths.Contains("ShowMoney"))
{
<text>
$("#Invertercard-money").html(rel.data.today_Money.toFixed());
</text>
}
$("#Invertercard-Capacity").html(rel.data.generatingCapacity.toFixed(3));
$("#Invertercard-pr").html(rel.data.today_PR.toFixed(2));
var str = "<div class='progress progress-sm ' id='prbar'>" +
"<div class='progress-bar bg-info' role = 'progressbar' style = 'width: " + rel.data.today_PR + "%;' aria - valuenow='" + rel.data.today_PR + "' aria - valuemin='0' aria - valuemax='100' ></div > </div >"
$('#prbar').remove();
@ -2764,9 +2838,9 @@
break;
}
$("#Invertercard-type").html(TypeName);
var time = new Date(rel.data.createdAt);
$("#Invertercard-date").html(time.getMonth() + "/" + time.getDate() + " " + time.getHours() + ":" + time.getMinutes());
@*var time = new Date(rel.data.createdAt);
$("#Invertercard-date").html(time.getMonth() + "/" + time.getDate() + " " + time.getHours() + ":" + time.getMinutes());*@
$("#Invertercard-date").html(rel.data.electricityMeterAt);
var urlPath = "../upload/power_station/" + rel.data.id + "/" + rel.data.mainDisplay;
var xmlhttp;

View File

@ -131,7 +131,7 @@
<div class="row mb-3">
<div class="col-lg-12">
<div class="form-group">
<label class="form-label" for="notice_textarea_modal_exc">巡檢注意事項</label>
<label class="form-label" for="notice_textarea_modal_exc">項目內容</label>
<textarea class="form-control" id="notice_textarea_modal_exc" rows="5"></textarea>
</div>
</div>

View File

@ -120,7 +120,7 @@
<div class="col-xl-3 row justify-content-center align-items-center">
<label class="col-xl-4 form-label" id="coordinate_label" for="coordinate">Line Token</label>
<div class="col-xl-8">
<label id="line_token_text" class="color-info-600"></label>
<label id="line_token_text" class="color-info-600" style="word-break: break-all"></label>
</div>
</div>
</div>

View File

@ -6,25 +6,43 @@
<div class="card border m-auto m-lg-0" id="Invertercard">
<div> <img src="img/card-backgrounds/cover-3-lg.png" class="card-img-top" alt="..."> </div>
<div class="card-body d-flex justify-content-between pb-0 px-2">
<h4 class="font-weight-bold" style="line-height: 27px;" id="Invertercard-Name"> <a href="javascript:void(0);" class="btn btn-success btn-sm btn-icon rounded-circle waves-effect waves-themed"> <i class="fal fa-check"></i> </a> 新竹巨城站</h4>
<p class="card-text"><i class="fal fa-cloud-sun-rain fa-2x" id="Invertercard-weathericon"></i></p>
<h4 class="font-weight-bold" style="line-height: 27px;" id="Invertercard-Name">新竹巨城站</h4>
<div class="d-flex">
<p id="Temp" class="mr-2">27°C</p><i class="fal fa-cloud-sun-rain fa-2x" id="weathericon"></i>
</div>
</div>
<div class="list-group list-group-flush">
<div class="list-group-item px-2">
<div class=" d-flex justify-content-between">
<p>發電量</p>
<p><span class="color-info-700 font-weight-bold" id="Invertercard-kwh">185</span> kWh</p>
<p id="Invertercard-Temp">27°C</p>
<div class="d-flex justify-content-between" style="width:60%">
<p>發電量</p>
<p><span class="color-info-700 font-weight-bold" id="Invertercard-kwh">0.00</span> kWh</p>
</div>
@if (ViewBag.myUser.Role.Auths.Contains("ShowMoney"))
{
<div class="d-flex justify-content-end" style="width:40%">
@*<p>發電金額</p>*@
<p><span class="color-info-700 font-weight-bold" id="Invertercard-money">0</span> NT</p>
</div>
}
</div>
<div class=" d-flex justify-content-between">
<p>發電金額</p>
<p><span class="color-info-700 font-weight-bold" id="Invertercard-money">2,5840</span> NT</p>
<p class="color-info-700 font-weight-bold" id="Invertercard-type">自建躉售</p>
<div class="d-flex justify-content-between" style="width:60%">
<p>裝置容量</p>
<p><span class="color-info-700 font-weight-bold" id="Invertercard-Capacity">0.00</span> kWp</p>
</div>
<div class="d-flex justify-content-end" style="width:40%">
<p><span class="color-info-700 font-weight-bold" id="Invertercard-type">自建躉售</span></p>
</div>
</div>
<div class=" d-flex justify-content-between">
<p>PR值</p>
<p><span class="color-info-700 font-weight-bold" id="Invertercard-pr">90</span> %</p>
<p class="small" id="Invertercard-date">17:50:36</p>
<div class="d-flex justify-content-between" style="width:60%">
<p>PR值</p>
<p><span class="color-info-700 font-weight-bold" id="Invertercard-pr">0</span> %</p>
</div>
<div class="d-flex justify-content-end" style="width:40%">
<p class="small" id="Invertercard-date">06-30 17:50</p>
</div>
</div>
</div>
</div>
@ -32,7 +50,6 @@
</div>
</div>
<ul id="ullist">
</ul>
</li>
</ul>

View File

@ -79,7 +79,7 @@
<div class="row mb-3">
<div class="col-lg-6">
<div class="form-group">
<label class="form-label" for="power_station_select_modal">電站</label>
<label class="form-label" for="power_station_select_modal"><span class="text-danger">*</span>電站</label>
@*<input class="form-control" id="power_station_select_modal" type="text" name="power_station_select_modal" />*@
<select class="form-control" id="power_station_select_modal">
</select>
@ -87,8 +87,9 @@
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="form-label" for="work_time_modal">作業日期</label>
<label class="form-label" for="work_time_modal"><span class="text-danger">*</span>作業日期</label>
<input class="form-control" id="work_time_modal" type="date" name="work_time_modal" />
<label id="work_time_modal-error" class="" style="z-index:1;color:red;display:none">此為必填欄位</label>
</div>
</div>
</div>
@ -96,7 +97,7 @@
<div class="row mb-3">
<div class="col-lg-6">
<div class="form-group">
<label class="form-label" for="example-select">狀態</label>
<label class="form-label" for="example-select"><span class="text-danger">*</span>狀態</label>
<div>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" class="custom-control-input ml-auto" id="status_none_complete" name="status_modal_opRecord" value="0" />
@ -111,11 +112,13 @@
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="form-label" for="work_person_select_modal">執行人員</label>
<select class="form-control" id="work_person_select_modal">
<label class="form-label" for="work_person_select_modal"><span class="text-danger">*</span>執行人員</label>
<select class="form-control" id="work_person_select_modal" multiple="multiple">
</select>
<label id="work_person_select_modal-error" class="" style="z-index:1;color:red;display:none">此為必填欄位</label>
</div>
</div>
</div>
<div class="row mb-3 fix-div">
@ -123,7 +126,7 @@
<div class="form-group">
<div class="form-group">
<label class="form-label" for="error_code_modal">異常編號</label>
<input class="form-control" id="error_code_modal" type="text" name="error_code_modal" />
<input class="form-control" id="error_code_modal" type="text" name="error_code_modal" disabled/>
</div>
</div>
</div>
@ -135,10 +138,25 @@
</div>
</div>
<div class="row mb-3">
<div class="col-lg-6">
<div class="form-group">
<label class="form-label" for="fix_firm_modal">負責廠商</label>
<select class="form-control" id="fix_firm_select_modal"></select>
</div>
</div>
<div class="col-lg-6 mt-5">
<div class="custom-control custom-checkbox d-flex align-content-center">
<input type="checkbox" class="custom-control-input" id="EmailcheckBox">
<label class="custom-control-label" for="EmailcheckBox">發送Email通知</label>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-12">
<div class="form-group">
<label class="form-label" for="notice_textarea_modal">巡檢注意事項</label>
<label class="form-label" for="notice_textarea_modal">項目內容</label>
<textarea class="form-control" id="notice_textarea_modal" rows="5"></textarea>
</div>
</div>

View File

@ -39,7 +39,7 @@
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p>即時平均日照度</p>
<p>即時日照度</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_irradiance">0.00</span></p>
</div>
<div class="d-flex justify-content-between">
@ -55,7 +55,7 @@
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p>即時平均 PR 值</p>
<p>今日 PR 值</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_PR">0.00</span></p>
</div>
<div class="d-flex justify-content-between">
@ -71,7 +71,7 @@
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<p>即時平均有效日照時數</p>
<p>今日有效日照時數(kwh/kwp)</p>
<p><span class="color-info-700 fs-xl font-weight-bold" id="today_kwhkwp">0.00</span></p>
</div>
<div class="d-flex justify-content-between">

View File

@ -266,7 +266,7 @@
<tr>
<th>縣市</th>
<th>平均發電量(kWp)</th>
<th>發電時間(小時)</th>
<th>有效發電小時</th>
</tr>
</thead>
<tbody id="maxtableBody">
@ -303,7 +303,7 @@
var haveinvertName = [];
var nowform;
var xxx;
var button;
$(function () {
//#region 預設初始值
$('#collapse').trigger("click");
@ -533,7 +533,7 @@
}
$(e).removeClass("btn-outline-success").addClass("btn-success");
if (nowform != null && nowform != 2) {
Dateform(nowform);
Dateform(nowform, button);
}
}
//#endregion
@ -783,7 +783,7 @@
str += "<th>日<br />發電量<br />(kWh)</th>";
str += "<th>日<br />發電量<br />百分比<br />(%)</th>";
str += "<th>日照小時(hr)</th>";
str += "<th>kWH/kWP</th>";
str += "<th>有效發電小時</th>";
str += "<th>PR%</th>";
str += "<th>日<br />平均<br />日照度<br />(W/㎡)</th>";
str += "<th>日<br />平均<br />模組溫度<br />(°C)</th>";
@ -795,7 +795,7 @@
str += "<th>區域</th>";
str += "<th>電站名稱</th>";
str += "<th>發電量</th>";
str += "<th>發電小時</th>";
str += "<th>有效發電小時</th>";
str += "<th>平均日照</th>";
str += "<th>PR</th>";
if (rel.data.showMoney == 1) {
@ -813,7 +813,7 @@
str += "<th>月<br />發電量<br />(kWh)</th>";
str += "<th>月<br />發電量<br />百分比<br />(%)</th>";
str += "<th>日照小時(hr)</th>";
str += "<th>kWH/kWP</th>";
str += "<th>有效發電小時</th>";
str += "<th>PR%</th>";
str += "<th>月<br />平均<br />日照度<br />(W/㎡)</th>";
str += "<th>月<br />平均<br />模組溫度<br />(°C)</th>";
@ -838,7 +838,7 @@
$(".btn-report").removeClass("btn-success").addClass("btn-primary");
}
$(e).removeClass("btn-primary").addClass("btn-success");
button = e;
$('#hiretable').hide();
@ -897,11 +897,12 @@
}
$('#TableBody').empty();
$('#totbody').empty();
haveinvertName = [];
return;
}
var sta = "";
$('#TableBody').empty();
//var sta = "";
$('#totbody').empty();
$('#tothead').empty();
if (form == 0) {//日報表
@ -911,7 +912,7 @@
var kWhkwp = 0;
var ntd = 0;
var ntdone = 0;
var sta = "";
$.each(rel.data, function (index, inverter) {
sta += "<tr>";
sta += "<td>" + inverter.report_date + "</td>";
@ -939,7 +940,7 @@
})
var stc = "<tr>";
stc += "<th>" + '日照小時' + "</th>";
stc += "<th>" + 'kWH/kWP' + "</th>";
stc += "<th>" + '有效發電小時' + "</th>";
stc += "<th>" + 'PR%' + "</th>";
stc += "<th>" + '日發電量(kWh)' + "</th>";
if (showmoney == 1) {
@ -961,6 +962,7 @@
stb += "</tr>";
$('#TableBody').empty();
$('#TableBody').append(sta);
$('#totbody').append(stb);
$('#tothead').append(stc);
@ -974,7 +976,7 @@
var monthmoney = 0;
var monthmoneyone = 0;
var monthday = 0;
var sta = "";
var check_hire = false;
var sitedb = "";
$.each(rel.data, function (index, inverter) {
@ -988,10 +990,10 @@
}
});
sta += "<td>" + inverter.dayKWH + "</td>";
sta += "<td>" + inverter.dayKWHp + "</td>";
sta += "<td>" + ((inverter.dayKWHp == null) ? 0 : inverter.dayKWHp) + "</td>";
sta += "<td>" + inverter.tothour + "</td>";
sta += "<td>" + inverter.KWHKWP + "</td>";
sta += "<td>" + inverter.PR.toFixed(2) + "</td>";
sta += "<td>" + ((inverter.PR == null) ? 0 : inverter.PR.toFixed(2)) + "</td>";
sta += "<td>" + inverter.irradiance + "</td>";
sta += "<td>" + inverter.temperature + "</td>";
if (showmoney == 1) {
@ -1016,7 +1018,7 @@
var stc = "<tr>";
stc += "<th>" + '日照平均(日)' + "</th>";
stc += "<th>" + 'kWH/kWP(日)' + "</th>";
stc += "<th>" + '有效發電小時(日)' + "</th>";
stc += "<th>" + '發電量平均(kWh)(日)' + "</th>";
stc += "<th>" + '發電量(kWh)(月)' + "</th>";
if (showmoney == 1) {
@ -1078,7 +1080,7 @@
})
}
$('#TableBody').empty();
$('#TableBody').append(sta);
$('#totbody').append(stb);
$('#tothead').append(stc);
@ -1094,7 +1096,7 @@
var monthmoney = 0;
var monthmoneyone = 0;
var monthday = 0;
var sta = "";
var check_hire = false;
var sitedb = "";
$.each(rel.data, function (index, inverter) {
@ -1136,7 +1138,7 @@
var stc = "<tr>";
stc += "<th>" + '日照平均(月)' + "</th>";
stc += "<th>" + 'kWH/kWP(月)' + "</th>";
stc += "<th>" + '有效發電小時(月)' + "</th>";
stc += "<th>" + '發電量平均(kWh)(月)' + "</th>";
stc += "<th>" + '發電量(kWh)(年)' + "</th>";
if (showmoney == 1) {
@ -1198,7 +1200,7 @@
})
}
$('#TableBody').empty();
$('#TableBody').append(sta);
$('#totbody').append(stb);
$('#tothead').append(stc);
@ -1223,7 +1225,25 @@
PowerStation: selecterd_invert
}
if (send_data.FormType != null && send_data.PowerStation.length != 0 && send_data.FormType != 2) {
window.location = "/StationReport/ExportExcel?post=" + JSON.stringify(send_data);
$.post("/StationReport/CheckExcel", send_data, function (rel) {
if (rel.code == "0000") {
window.location = "/StationReport/ExportExcel?post=" + JSON.stringify(send_data);
return;
}
else
{
var text = "原因如下:<br\>";
$.each(rel.data, function (index, val) {
text += index + 1 + "." + val + "<br\>";
});
Swal.fire(
{
title: "Excel匯出失敗",
icon: 'warning',
html: text,
});
}
}, 'json');
}
else
{
@ -1295,6 +1315,7 @@
city: data.cityName,
kwp: data.kwh,
hour: data.solarHour,
kwhkwp: data.avgKWHKWP,
count : 1
}
if (CityArray.length == 0) {
@ -1308,6 +1329,7 @@
n.kwp += cityinfo.kwp;
n.hour += cityinfo.hour;
n.count += cityinfo.count;
n.kwhkwp += cityinfo.kwhkwp
npush = false;
}
});
@ -1321,7 +1343,7 @@
StrInfoBody += "<td>" + data.cityName + data.areaName + "</td>";
StrInfoBody += "<td>" + data.powerstationName + "</td>";
StrInfoBody += "<td>" + data.kwh.toFixed(2) + "</td>";
StrInfoBody += "<td>" + data.solarHour.toFixed(2) + "</td>";
StrInfoBody += "<td>" + data.avgKWHKWP.toFixed(2) + "</td>";
StrInfoBody += "<td>" + data.avgIrradiance.toFixed(2) + "</td>";
StrInfoBody += "<td>" + data.avgPR.toFixed(2) + "</td>";
if (showmoney == 1) {
@ -1344,7 +1366,7 @@
CityInfoBody += "<tr>";
CityInfoBody += "<td>" + data.city + "</td>";
CityInfoBody += "<td>" + (data.kwp / data.count).toFixed(2) + "</td>";
CityInfoBody += "<td>" + (data.hour / data.count).toFixed(2) + "</td>";
CityInfoBody += "<td>" + (data.kwhkwp / data.count).toFixed(2) + "</td>";
CityInfoBody += "</tr>";
})
//上面

View File

@ -37,7 +37,9 @@
"UserName": "shanghohui@gmail.com",
"Password": "wswgnluvoodfexrb",
"EnableSsl": true
}
},
"ExceptionTimes": 240 //()
//"SMTPConfig": {
// "Host": "smtp.gmail.com",
// "Port": 25,

View File

@ -38,5 +38,6 @@
"UserName": "ficgreen01@gmail.com",
"Password": "qwe2015qwe",
"EnableSsl": true
}
},
"ExceptionTimes": 240 //()
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

View File

@ -6,11 +6,15 @@ using System.Text;
using System.Runtime.InteropServices;
using System.Data;
using Microsoft.Office.Interop;
using MySql.Data.MySqlClient;
using System.Configuration;
using Dapper;
namespace solarApp.Service
{
public class excelHelper
{
string Connection1 = ConfigurationManager.ConnectionStrings["mySql"].ConnectionString;
void readExcel(string fname, ref System.Data.DataTable dt) {
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fname);
@ -60,6 +64,179 @@ namespace solarApp.Service
Marshal.ReleaseComObject(xlApp);
}
public bool insertDay2DB(DataTable dt, string filename, string inverterID)
{
bool result = false;
StringBuilder ss = new StringBuilder();
using (MySqlConnection conn = new MySqlConnection(Connection1))
{
conn.Open();
int i = 0;
foreach (DataRow row in dt.Rows)
{
//ss.Append(@"INSERT INTO solar_import.auo_taiping(`No.`, `雲端收到時間`, `資料取得時間`, `交流電壓`, `交流電流`, `交流功率`, `溫度`, `累積發電量`, `頻率`, `狀態`, saveDate, filename, inverterID)
ss.Append(@"INSERT INTO solar_import.auo_aimai(`No.`, `雲端收到時間`, `資料取得時間`, `交流電壓`, `交流電流`, `交流功率`, `溫度`, `累積發電量`, `頻率`, `狀態`, saveDate, filename, inverterID)
values( '"
+ row.Field<string>("1").ToString() + "' ,'"
+ row.Field<string>("2").ToString() + "' ,'"
+ row.Field<string>("3").ToString() + "' ,'"
+ row.Field<string>("4").ToString() + "' ,'"
+ row.Field<string>("5").ToString() + "' ,'"
+ row.Field<string>("6").ToString() + "' ,'"
+ row.Field<string>("7").ToString() + "' ,'"
+ row.Field<string>("8").ToString() + "' ,'"
+ row.Field<string>("9").ToString() + "' ,'"
+ row.Field<string>("10").ToString() + "', now(), '"+ filename + "', '" + inverterID + "');");
if (i % 10 == 0)
{
conn.Execute(ss.ToString());
ss.Clear();
}
i++;
}
if (ss.Length > 0)
{
conn.Execute(ss.ToString());
ss.Clear();
}
conn.Clone();
}
return result;
}
public bool insertFile2DB(string[] filename, string station_name)
{
bool result = false;
StringBuilder ss = new StringBuilder();
using (MySqlConnection conn = new MySqlConnection(Connection1))
{
conn.Open();
int i = 0;
foreach (var fullfileName in filename)
{
string[] ff = fullfileName.Split("\\");
string fname = string.Empty;
fname += ff[ff.Length - 1]; //只抓最後的檔名
string inverterID = string.Empty;
string[] str = fname.Split("_");
inverterID = str[str.Length - 3] + "_" + str[str.Length - 2];
str = inverterID.Split(" ");
inverterID = str[str.Length -1];
fname = fullfileName.Replace("\\", "/");
//if (fullfileName == "D:AUO台中太平inverter110") {
// str[0] = "123";
//}
ss.Append(@"insert into `solar_import`.`auo_file_list`( `station_name`, `filename`, inverterid, `inser_date`)
values( '"
+ station_name + "' ,'"
+ fname + "' ,'"
+ inverterID + "' , now() );");
if (i % 10 == 0)
{
conn.Execute(ss.ToString());
ss.Clear();
}
i++;
}
if (ss.Length > 0)
{
conn.Execute(ss.ToString());
ss.Clear();
}
conn.Clone();
}
return result;
}
public bool insertDay2DB_enlux_gong34(DataTable dt, string filename)
{
bool result = false;
StringBuilder ss = new StringBuilder();
using (MySqlConnection conn = new MySqlConnection(Connection1))
{
conn.Open();
int i = 0;
foreach (DataRow row in dt.Rows)
{
//ss.Append(@"INSERT INTO solar_import.auo_taiping(`No.`, `雲端收到時間`, `資料取得時間`, `交流電壓`, `交流電流`, `交流功率`, `溫度`, `累積發電量`, `頻率`, `狀態`, saveDate, filename, inverterID)
ss.Append(@"INSERT INTO solar_import.enlux_gong34(UploadTime, S1_AC, S1_DC, S2_AC, S2_DC, S3_AC, S3_DC, S4_AC, S4_DC, sunshine, temperature, saveDate, filename)
values( '"
+ row.Field<string>("1").ToString() + "' ,'"
+ row.Field<string>("2").ToString() + "' ,'"
+ row.Field<string>("3").ToString() + "' ,'"
+ row.Field<string>("4").ToString() + "' ,'"
+ row.Field<string>("5").ToString() + "' ,'"
+ row.Field<string>("6").ToString() + "' ,'"
+ row.Field<string>("7").ToString() + "' ,'"
+ row.Field<string>("8").ToString() + "' ,'"
+ row.Field<string>("9").ToString() + "' ,'"
+ row.Field<string>("10").ToString() + "' ,'"
+ row.Field<string>("11").ToString() + "' , now(), '" + filename + "');");
if (i % 10 == 0)
{
conn.Execute(ss.ToString());
ss.Clear();
}
i++;
}
if (ss.Length > 0)
{
conn.Execute(ss.ToString());
ss.Clear();
}
conn.Clone();
}
return result;
}
public bool insertFile2DB__enlux_gong34(string[] filename, string station_name)
{
bool result = false;
StringBuilder ss = new StringBuilder();
using (MySqlConnection conn = new MySqlConnection(Connection1))
{
conn.Open();
int i = 0;
foreach (var fullfileName in filename)
{
string[] ff = fullfileName.Split("\\");
string fname = string.Empty;
fname += ff[ff.Length - 1]; //只抓最後的檔名
//string inverterID = string.Empty;
//string[] str = fname.Split("_");
//inverterID = str[str.Length - 3] + "_" + str[str.Length - 2];
//str = inverterID.Split(" ");
//inverterID = str[str.Length - 1];
fname = fullfileName.Replace("\\", "/");
//if (fullfileName == "D:AUO台中太平inverter110") {
// str[0] = "123";
//}
ss.Append(@"insert into `solar_import`.`enlux_file_list`( `station_name`, `filename`, `inser_date`)
values( '"
+ station_name + "' ,'"
+ fname + "' , now() );");
if (i % 10 == 0)
{
conn.Execute(ss.ToString());
ss.Clear();
}
i++;
}
if (ss.Length > 0)
{
conn.Execute(ss.ToString());
ss.Clear();
}
conn.Clone();
}
return result;
}
//public void ReadSample()
//{
// Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

View File

@ -248,6 +248,100 @@ namespace solarApp.Service
}
public void taoYuan_createColumnHour(ref DataTable mycsvdt, string filepath)
{
string strpath = filepath; //csv檔案的路徑
try
{
int intColCount = 0;
bool blnFlag = true;
DataColumn mydc;
string strline;
string[] aryline;
StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.Default);
int rowIndex = 0;
while ((strline = mysr.ReadLine()) != null)
{
rowIndex += 1;
if (rowIndex < 4) continue;
aryline = strline.Split(new char[] { ',' });
//給datatable加上列名
if (blnFlag)
{
blnFlag = false;
intColCount = aryline.Length;
int col = 0;
for (int i = 0; i < aryline.Length; i++)
{
col = i + 1;
mydc = new DataColumn(col.ToString());
mycsvdt.Columns.Add(mydc);
}
}
break;
}
}
catch (Exception e)
{
//throw (Stack.GetErrorStack(strpath + "讀取CSV檔案中的資料出錯." + e.Message, "OpenCSVFile("));
//return false;
}
}
/// <summary>
/// 太陽能光電 桃園全虹
/// </summary>
/// <param name="mycsvdt"></param>
/// <param name="filepath"></param>
/// <param name="InvID"></param>
/// <param name="intColCount"></param>
/// <param name="readTitle"></param>
/// <returns></returns>
public bool taoYuan_readCsvFile(ref DataTable mycsvdt, string filepath, int intColCount, bool readTitle)
{
string strpath = filepath; //csv檔案的路徑
try
{
DataColumn mydc;
DataRow mydr;
string strline;
string[] aryline;
StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.Default);
int rowIndex = 0;
while ((strline = mysr.ReadLine()) != null)
{
rowIndex += 1;
if (readTitle && rowIndex == 1) {
readTitle = false;
continue;
}
aryline = strline.Split(new char[] { ',' });
//填充資料並加入到datatable中
mydr = mycsvdt.NewRow();
for (int i = 0; i < intColCount - 1; i++)
{
mydr[i] = aryline[i];
}
mycsvdt.Rows.Add(mydr);
}
}
catch (Exception ex)
{
//throw (Stack.GetErrorStack(strpath + "讀取CSV檔案中的資料出錯." + e.Message, " readCsvFile"));
throw ex;
return false;
}
return true;
}
public bool clear_inv(string timeType)
{
bool result = false;
@ -266,6 +360,98 @@ namespace solarApp.Service
return false;
}
public void taoYuan_insertHour2DB(ref DataTable dt, string dest_table)
{
List<src_inv_count> ds;
StringBuilder ss = new StringBuilder();
using (MySqlConnection conn = new MySqlConnection(Connection1))
{
conn.Open();
ss.Clear();
int i = 0;
foreach (DataRow row in dt.Rows) //sun_taoyuan
{
ss.Append(@"insert into solar_import."+ dest_table + @"(c1 , c2 , c3 , c4 , c5 , c6 , c7 , c8 , c9 , c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, c40, c41, c42, c43, c44, c45, c46, c47, c48, c49, c50, c51, c52, c53, c54, c55, c56, c57, c58)
values( '" + row.Field<string>("1").ToString() + "', " +
"'" + row.Field<string>("2").ToString() + "' , " +
"'" + row.Field<string>("3").ToString() + "' , " +
"'" + row.Field<string>("4").ToString() + "' , " +
"'" + row.Field<string>("5").ToString() + "' , " +
"'" + row.Field<string>("6").ToString() + "' , " +
"'" + row.Field<string>("7").ToString() + "' , " +
"'" + row.Field<string>("8").ToString() + "' , " +
"'" + row.Field<string>("9").ToString() + "' , " +
"'" + row.Field<string>("10").ToString() + "' ," +
"'" + row.Field<string>("11").ToString() + "' ," +
"'" + row.Field<string>("12").ToString() + "' ," +
"'" + row.Field<string>("13").ToString() + "' ," +
"'" + row.Field<string>("14").ToString() + "' ," +
"'" + row.Field<string>("15").ToString() + "' ," +
"'" + row.Field<string>("16").ToString() + "' ," +
"'" + row.Field<string>("17").ToString() + "' ," +
"'" + row.Field<string>("18").ToString() + "' ," +
"'" + row.Field<string>("19").ToString() + "' ," +
"'" + row.Field<string>("20").ToString() + "' ," +
"'" + row.Field<string>("21").ToString() + "' ," +
"'" + row.Field<string>("22").ToString() + "' ," +
"'" + row.Field<string>("23").ToString() + "' ," +
"'" + row.Field<string>("24").ToString() + "' ," +
"'" + row.Field<string>("25").ToString() + "' ," +
"'" + row.Field<string>("26").ToString() + "' ," +
"'" + row.Field<string>("27").ToString() + "' ," +
"'" + row.Field<string>("28").ToString() + "' ," +
"'" + row.Field<string>("29").ToString() + "' ," +
"'" + row.Field<string>("30").ToString() + "' ," +
"'" + row.Field<string>("31").ToString() + "' ," +
"'" + row.Field<string>("32").ToString() + "' ," +
"'" + row.Field<string>("33").ToString() + "' ," +
"'" + row.Field<string>("34").ToString() + "' ," +
"'" + row.Field<string>("35").ToString() + "' ," +
"'" + row.Field<string>("36").ToString() + "' ," +
"'" + row.Field<string>("37").ToString() + "' ," +
"'" + row.Field<string>("38").ToString() + "' ," +
"'" + row.Field<string>("39").ToString() + "' ," +
"'" + row.Field<string>("40").ToString() + "' ," +
"'" + row.Field<string>("41").ToString() + "' ," +
"'" + row.Field<string>("42").ToString() + "' ," +
"'" + row.Field<string>("43").ToString() + "' ," +
"'" + row.Field<string>("44").ToString() + "' ," +
"'" + row.Field<string>("45").ToString() + "' ," +
"'" + row.Field<string>("46").ToString() + "' ," +
"'" + row.Field<string>("47").ToString() + "' ," +
"'" + row.Field<string>("48").ToString() + "' ," +
"'" + row.Field<string>("49").ToString() + "' ," +
"'" + row.Field<string>("50").ToString() + "' ," +
"'" + row.Field<string>("51").ToString() + "' ," +
"'" + row.Field<string>("52").ToString() + "' ," +
"'" + row.Field<string>("53").ToString() + "' ," +
"'" + row.Field<string>("54").ToString() + "' ," +
"'" + row.Field<string>("55").ToString() + "' ," +
"'" + row.Field<string>("56").ToString() + "' ," +
"'" + row.Field<string>("57").ToString() + "' ," +
"'" + row.Field<string>("58").ToString() + "' );");
if (i % 100 == 0)
{
conn.Execute(ss.ToString());
ss.Clear();
}
i++;
}
if (ss.Length > 0)
{
conn.Execute(ss.ToString());
ss.Clear();
}
//ss.Clear();
//ss.Append(@"select inv, left(c1, 10) date, count(*) ct from src_inv where c1 <> '欄位名稱' group by inv, left(c1, 10)");
//ds = conn.Query<src_inv_count>(ss.ToString()).AsList<src_inv_count>();
conn.Clone();
}
//return ds;
}
public List<src_inv_count> insertHour2DB(ref DataTable dt) {
List<src_inv_count> ds;
StringBuilder ss = new StringBuilder();

View File

@ -129,7 +129,7 @@ namespace solarApp.Service
string sql = @" select id as PowerStationID from solar_master.power_station where `code` = @siteID";
var ds = conn.Query<string>(sql, new { siteID = _siteID }).AsList<string>();
_powerStationID = (ds.Count > 0) ? ds[0][0].ToString() : "0";
_powerStationID = (ds.Count > 0) ? ds[0].ToString() : "0";
#region hour -- solar_type 0 1 2 ------------ 1

View File

@ -34,7 +34,7 @@ namespace solarApp
this.lbSiteID_sensor = new System.Windows.Forms.Label();
this.bt_archive = new System.Windows.Forms.Button();
this.bt_inv_hour_hj = new System.Windows.Forms.Button();
this.bt_clear_station = new System.Windows.Forms.Button();
this.bt_read_taiping = new System.Windows.Forms.Button();
this.bt_inv_day_hj = new System.Windows.Forms.Button();
this.fp_site = new System.Windows.Forms.FlowLayoutPanel();
this.btVerifyData = new System.Windows.Forms.Button();
@ -42,10 +42,15 @@ namespace solarApp
this.panel1 = new System.Windows.Forms.Panel();
this.lbSiteName_sensor = new System.Windows.Forms.Label();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.bt_sun_taoyuan = new System.Windows.Forms.Button();
this.bt_gong34 = new System.Windows.Forms.Button();
this.bt_AUO_aimai = new System.Windows.Forms.Button();
this.bt_hour_archive_hj = new System.Windows.Forms.Button();
this.bt_day_archive_hj = new System.Windows.Forms.Button();
this.rt1 = new System.Windows.Forms.RichTextBox();
this.tb1 = new System.Windows.Forms.TabPage();
this.tabControl = new System.Windows.Forms.TabControl();
this.bt_sun_yadong = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
@ -91,13 +96,14 @@ namespace solarApp
// bt_archive
//
this.bt_archive.Font = new System.Drawing.Font("Microsoft JhengHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.bt_archive.Location = new System.Drawing.Point(5, 528);
this.bt_archive.Location = new System.Drawing.Point(3, 640);
this.bt_archive.Name = "bt_archive";
this.bt_archive.Size = new System.Drawing.Size(282, 100);
this.bt_archive.TabIndex = 8;
this.bt_archive.Text = "單日歸檔";
this.bt_archive.UseVisualStyleBackColor = true;
this.bt_archive.Visible = false;
this.bt_archive.Click += new System.EventHandler(this.bt_archive_Click);
//
// bt_inv_hour_hj
//
@ -110,16 +116,16 @@ namespace solarApp
this.bt_inv_hour_hj.UseVisualStyleBackColor = true;
this.bt_inv_hour_hj.Click += new System.EventHandler(this.bt_inv_hour_hj_Click);
//
// bt_clear_station
// bt_read_taiping
//
this.bt_clear_station.Font = new System.Drawing.Font("Microsoft JhengHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.bt_clear_station.Location = new System.Drawing.Point(3, 418);
this.bt_clear_station.Name = "bt_clear_station";
this.bt_clear_station.Size = new System.Drawing.Size(135, 44);
this.bt_clear_station.TabIndex = 6;
this.bt_clear_station.Text = "AUO Insert ";
this.bt_clear_station.UseVisualStyleBackColor = true;
this.bt_clear_station.Click += new System.EventHandler(this.bt_clear_station_Click);
this.bt_read_taiping.Font = new System.Drawing.Font("Microsoft JhengHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.bt_read_taiping.Location = new System.Drawing.Point(0, 337);
this.bt_read_taiping.Name = "bt_read_taiping";
this.bt_read_taiping.Size = new System.Drawing.Size(192, 47);
this.bt_read_taiping.TabIndex = 6;
this.bt_read_taiping.Text = "AUO 太平 Read";
this.bt_read_taiping.UseVisualStyleBackColor = true;
this.bt_read_taiping.Click += new System.EventHandler(this.bt_clear_station_Click);
//
// bt_inv_day_hj
//
@ -154,12 +160,12 @@ namespace solarApp
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Left;
this.dataGridView1.Location = new System.Drawing.Point(0, 125);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowHeadersWidth = 51;
this.dataGridView1.RowTemplate.Height = 29;
this.dataGridView1.Size = new System.Drawing.Size(1458, 687);
this.dataGridView1.Size = new System.Drawing.Size(629, 687);
this.dataGridView1.TabIndex = 1;
//
// panel1
@ -195,16 +201,21 @@ namespace solarApp
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.BackColor = System.Drawing.Color.PaleGoldenrod;
this.splitContainer1.Panel1.Controls.Add(this.bt_sun_yadong);
this.splitContainer1.Panel1.Controls.Add(this.bt_sun_taoyuan);
this.splitContainer1.Panel1.Controls.Add(this.bt_gong34);
this.splitContainer1.Panel1.Controls.Add(this.bt_AUO_aimai);
this.splitContainer1.Panel1.Controls.Add(this.bt_hour_archive_hj);
this.splitContainer1.Panel1.Controls.Add(this.bt_day_archive_hj);
this.splitContainer1.Panel1.Controls.Add(this.bt_archive);
this.splitContainer1.Panel1.Controls.Add(this.bt_inv_hour_hj);
this.splitContainer1.Panel1.Controls.Add(this.bt_clear_station);
this.splitContainer1.Panel1.Controls.Add(this.bt_read_taiping);
this.splitContainer1.Panel1.Controls.Add(this.bt_inv_day_hj);
this.splitContainer1.Panel1.Controls.Add(this.fp_site);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.rt1);
this.splitContainer1.Panel2.Controls.Add(this.dataGridView1);
this.splitContainer1.Panel2.Controls.Add(this.panel1);
this.splitContainer1.Size = new System.Drawing.Size(1768, 812);
@ -212,6 +223,39 @@ namespace solarApp
this.splitContainer1.SplitterWidth = 10;
this.splitContainer1.TabIndex = 0;
//
// bt_sun_taoyuan
//
this.bt_sun_taoyuan.Font = new System.Drawing.Font("Microsoft JhengHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.bt_sun_taoyuan.Location = new System.Drawing.Point(3, 523);
this.bt_sun_taoyuan.Name = "bt_sun_taoyuan";
this.bt_sun_taoyuan.Size = new System.Drawing.Size(213, 47);
this.bt_sun_taoyuan.TabIndex = 13;
this.bt_sun_taoyuan.Text = "太陽能光電-桃園全虹";
this.bt_sun_taoyuan.UseVisualStyleBackColor = true;
this.bt_sun_taoyuan.Click += new System.EventHandler(this.bt_sun_taoyuan_Click);
//
// bt_gong34
//
this.bt_gong34.Font = new System.Drawing.Font("Microsoft JhengHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.bt_gong34.Location = new System.Drawing.Point(0, 443);
this.bt_gong34.Name = "bt_gong34";
this.bt_gong34.Size = new System.Drawing.Size(189, 47);
this.bt_gong34.TabIndex = 12;
this.bt_gong34.Text = "Envision 工34";
this.bt_gong34.UseVisualStyleBackColor = true;
this.bt_gong34.Click += new System.EventHandler(this.bt_gong34_Click);
//
// bt_AUO_aimai
//
this.bt_AUO_aimai.Font = new System.Drawing.Font("Microsoft JhengHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.bt_AUO_aimai.Location = new System.Drawing.Point(0, 390);
this.bt_AUO_aimai.Name = "bt_AUO_aimai";
this.bt_AUO_aimai.Size = new System.Drawing.Size(189, 47);
this.bt_AUO_aimai.TabIndex = 11;
this.bt_AUO_aimai.Text = "AUO 愛買 read";
this.bt_AUO_aimai.UseVisualStyleBackColor = true;
this.bt_AUO_aimai.Click += new System.EventHandler(this.bt_AUO_Insert_Click);
//
// bt_hour_archive_hj
//
this.bt_hour_archive_hj.Font = new System.Drawing.Font("Microsoft JhengHei UI", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
@ -234,6 +278,17 @@ namespace solarApp
this.bt_day_archive_hj.UseVisualStyleBackColor = true;
this.bt_day_archive_hj.Click += new System.EventHandler(this.bt_day_archive_hj_Click);
//
// rt1
//
this.rt1.BackColor = System.Drawing.SystemColors.MenuText;
this.rt1.Dock = System.Windows.Forms.DockStyle.Fill;
this.rt1.ForeColor = System.Drawing.SystemColors.Window;
this.rt1.Location = new System.Drawing.Point(629, 125);
this.rt1.Name = "rt1";
this.rt1.Size = new System.Drawing.Size(829, 687);
this.rt1.TabIndex = 2;
this.rt1.Text = "";
//
// tb1
//
this.tb1.Controls.Add(this.splitContainer1);
@ -257,6 +312,17 @@ namespace solarApp
this.tabControl.Size = new System.Drawing.Size(1782, 853);
this.tabControl.TabIndex = 1;
//
// bt_sun_yadong
//
this.bt_sun_yadong.Font = new System.Drawing.Font("Microsoft JhengHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.bt_sun_yadong.Location = new System.Drawing.Point(5, 576);
this.bt_sun_yadong.Name = "bt_sun_yadong";
this.bt_sun_yadong.Size = new System.Drawing.Size(213, 47);
this.bt_sun_yadong.TabIndex = 14;
this.bt_sun_yadong.Text = "太陽能光電-亞東觀音";
this.bt_sun_yadong.UseVisualStyleBackColor = true;
this.bt_sun_yadong.Click += new System.EventHandler(this.bt_sun_yadong_Click);
//
// fmExcel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 19F);
@ -285,7 +351,7 @@ namespace solarApp
private System.Windows.Forms.Label lbSiteID_sensor;
private System.Windows.Forms.Button bt_archive;
private System.Windows.Forms.Button bt_inv_hour_hj;
private System.Windows.Forms.Button bt_clear_station;
private System.Windows.Forms.Button bt_read_taiping;
private System.Windows.Forms.Button bt_clear_inv;
private System.Windows.Forms.FlowLayoutPanel fp_site;
private System.Windows.Forms.Button btVerifyData;
@ -296,8 +362,12 @@ namespace solarApp
private System.Windows.Forms.TabPage tb1;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.Button bt_inv_day_hj;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button bt_AUO_aimai;
private System.Windows.Forms.Button bt_hour_archive_hj;
private System.Windows.Forms.Button bt_day_archive_hj;
private System.Windows.Forms.RichTextBox rt1;
private System.Windows.Forms.Button bt_gong34;
private System.Windows.Forms.Button bt_sun_taoyuan;
private System.Windows.Forms.Button bt_sun_yadong;
}
}

View File

@ -67,40 +67,62 @@ namespace solarApp
dataGridView1.DataSource = csvSvc.insertHour2DB(ref dt);
MessageBox.Show("OK");
}
protected void ImporExcel()
protected void ImporExcel(string site_name)
{
string fname = "";
OpenFileDialog fdlg = new OpenFileDialog();
//OpenFileDialog fdlg = new OpenFileDialog();
//fdlg.Title = "Excel File Dialog";
//fdlg.InitialDirectory = @"d:\temp\";
//fdlg.InitialDirectory = @"d:\";
//fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
//fdlg.FilterIndex = 2;
//fdlg.RestoreDirectory = true;
//if (fdlg.ShowDialog() == DialogResult.OK)
//{
// fname = fdlg.FileName;
//}
//else return;
string[] fileEntries = new string[0];
Array.Clear(fileEntries, 0, fileEntries.Length);
//取得選取檔案的路徑
//string dir = Path.GetDirectoryName(fname);
string dir;//= Path.GetDirectoryName(fname);
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
//dir = Path.GetDirectoryName(fname);
//fileEntries = Directory.GetFiles(fbd.SelectedPath);
fileEntries = Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories);
MessageBox.Show("Files found: " + fileEntries.Length.ToString(), "Message");
}
}
// 取得路徑下所有檔案
//string[] fileEntries = System.IO.Directory.GetFiles(dir);
string[] fileEntries = Directory.GetFiles(@"D:\temp\AUO\台中太平\台中太平\inverter", "*.*", SearchOption.AllDirectories);
//string[] fileEntries = System.IO.Directory.GetFiles(dir); //D:\temp\AUO\台中太平\台中太平\inverter
//string[] fileEntries = Directory.GetFiles(@"D:\AUO\台中太平\inverter", "*.*", SearchOption.AllDirectories);
// dt.Column = colCount;
solarApp.Service.excelHelper xlsSvc = new Service.excelHelper();
System.Data.DataTable dt = new System.Data.DataTable();
DataColumn mydc;
bool isFirst = true; bool isFirstData = true;
int x = 0;
foreach (string fileName in fileEntries)
#region save file list
xlsSvc.insertFile2DB(fileEntries, site_name);
#endregion
foreach (string fullfileName in fileEntries)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileName);
if (fullfileName.Contains("~$")) { rt1.AppendText("\n -- contain ~$ in filename: " + fullfileName.ToString()); continue; }
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fullfileName);
Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
//dataGridView1.ColumnCount = colCount;
//dataGridView1.RowCount = rowCount;
string[] ff = fullfileName.Split("\\");
string filename = string.Empty;
filename += ff[ff.Length-1]; //只抓最後的檔名
rt1.AppendText(filename.ToString() + " ");
rt1.SelectionStart = rt1.Text.Length;
rt1.ScrollToCaret();
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
@ -111,7 +133,7 @@ namespace solarApp
for (int j = 1; j <= colCount; j++)
{
int col = 0;
col = j + 1;
col = j;
mydc = new DataColumn(col.ToString());
dt.Columns.Add(mydc);
isFirst = false;
@ -119,6 +141,11 @@ namespace solarApp
}
#endregion
DataRow row = dt.NewRow();
//只需要 10個欄位的版本 ---------------------------------
if (colCount != 10) {
rt1.AppendText("\n -- unable read file: " + fullfileName.ToString());
break;
}
for (int j = 0; j <= colCount-1; j++)
{
@ -126,16 +153,33 @@ namespace solarApp
{
Microsoft.Office.Interop.Excel.Range range = xlRange.Cells[i, j+1] as Microsoft.Office.Interop.Excel.Range;
row[j] = range.Value.ToString();
isFirstData = false;
if (j == 9) isFirstData = false;
}
else if (i == 0) continue;
// else if (i == 1) continue;// 第二個檔案之後的 firstRow 不需要, start from 1
else //從第二個檔案 開始都從第二個 row 開始
{
Microsoft.Office.Interop.Excel.Range range = xlRange.Cells[i, j+1] as Microsoft.Office.Interop.Excel.Range;
if (string.IsNullOrEmpty(range.Value) || string.IsNullOrWhiteSpace(range.Value))
MessageBox.Show("got it!");
//string ss = range.Value.ToString();
//ss = ss.Replace("[", "").Replace("]", "");
row[j] = range.Value.ToString();
}
if (j == colCount)
{
if (string.IsNullOrEmpty(row[j].ToString()) || string.IsNullOrWhiteSpace(row[j].ToString()))
MessageBox.Show("empty!");
}
}
if (string.IsNullOrEmpty(row[5].ToString()) || string.IsNullOrWhiteSpace(row[5].ToString()))
{
MessageBox.Show("empty!");
}
else
{
if (i == 1) continue;// 第二個檔案之後的 firstRow 不需要, start from 1
dt.Rows.Add(row);
}
dt.Rows.Add(row);
}
//release com objects to fully kill excel process from running in the background
Marshal.ReleaseComObject(xlRange);
@ -148,13 +192,25 @@ namespace solarApp
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
//if (x ==3) break;
string[] str = filename.Split("_");
string inverterID = str[str.Length - 3] + "_" + str[str.Length - 2];
str = inverterID.Split(" ");
inverterID = str[str.Length - 1];
xlsSvc.insertDay2DB(dt, filename, inverterID);
dt.Rows.Clear();
x++;
}
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
dataGridView1.DataSource = dt;
//MessageBox.Show(" dt.Rows.Count = " + dt.Rows.Count.ToString());
MessageBox.Show(" dt.Rows.Count = " + dt.Rows.Count.ToString());
MessageBox.Show(" ok ");
//rule of thumb for releasing com objects:
// never use two dots, all COM objects must be referenced and released individually
// ex: [somthing].[something].[something] is bad
@ -224,7 +280,280 @@ namespace solarApp
private void bt_clear_station_Click(object sender, EventArgs e)
{
ImporExcel();
ImporExcel("auo_taiping");
}
private void bt_archive_Click(object sender, EventArgs e)
{
}
private void bt_AUO_Insert_Click(object sender, EventArgs e)
{
ImporExcel("auo_aimai");
}
/// <summary>
/// 台中工34
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bt_gong34_Click(object sender, EventArgs e)
{
string fname = "";
//OpenFileDialog fdlg = new OpenFileDialog();
//fdlg.Title = "Excel File Dialog";
//fdlg.InitialDirectory = @"d:\";
//fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
//fdlg.FilterIndex = 2;
//fdlg.RestoreDirectory = true;
string[] fileEntries = new string[0];
Array.Clear(fileEntries, 0, fileEntries.Length);
//取得選取檔案的路徑
string dir;//= Path.GetDirectoryName(fname);
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
//dir = Path.GetDirectoryName(fname);
//fileEntries = Directory.GetFiles(fbd.SelectedPath);
fileEntries = Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories);
MessageBox.Show("Files found: " + fileEntries.Length.ToString(), "Message");
}
}
// 取得路徑下所有檔案
//string[] fileEntries = System.IO.Directory.GetFiles(dir); //D:\temp\AUO\台中太平\台中太平\inverter
//string[] fileEntries = Directory.GetFiles(@"D:\AUO\台中太平\inverter", "*.*", SearchOption.AllDirectories);
// dt.Column = colCount;
solarApp.Service.excelHelper xlsSvc = new Service.excelHelper();
System.Data.DataTable dt = new System.Data.DataTable();
DataColumn mydc;
bool isFirst = true; bool isFirstData = true;
int x = 0;
#region save file list
xlsSvc.insertFile2DB__enlux_gong34(fileEntries, "gong34");
#endregion
foreach (string fullfileName in fileEntries)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (fullfileName.Contains("~$")) { rt1.AppendText("\n -- contain ~$ in filename: " + fullfileName.ToString()); continue; }
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fullfileName);
//Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
//xl.Worksheet ws = (xl.Worksheet)wb.Sheets[1];
//foreach (xl.Worksheet ws1 in wb.Sheets)
//{
// MessageBox.Show(ws1.Name);
// // or whatever you want to do with the worksheet
//}
string[] ff = fullfileName.Split("\\");
string filename = string.Empty;
filename += ff[ff.Length - 1]; //只抓最後的檔名
rt1.AppendText(filename.ToString() + " ");
rt1.SelectionStart = rt1.Text.Length;
rt1.ScrollToCaret();
foreach (Microsoft.Office.Interop.Excel._Worksheet xlWorksheet in xlWorkbook.Sheets)
{
// MessageBox.Show(xlWorksheet.Name);
Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
//dataGridView1.ColumnCount = colCount;
//dataGridView1.RowCount = rowCount;
rt1.AppendText(" - " + xlWorksheet.Name);
rt1.SelectionStart = rt1.Text.Length;
rt1.ScrollToCaret();
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
#region dt add column
if (isFirst)
{
for (int j = 1; j <= colCount; j++)
{
int col = 0;
col = j;
mydc = new DataColumn(col.ToString());
dt.Columns.Add(mydc);
isFirst = false;
}
}
#endregion
DataRow row = dt.NewRow();
//只需要 11個欄位的版本 ---------------------------------
if (colCount != 11)
{
rt1.AppendText("\n -- unable read file: " + fullfileName.ToString());
break;
}
for (int j = 0; j <= colCount - 1; j++)
{
if (isFirstData) // 第一筆資料為 欄位名稱
{
Microsoft.Office.Interop.Excel.Range range = xlRange.Cells[i, j + 1] as Microsoft.Office.Interop.Excel.Range;
row[j] = range.Value.ToString();
if (j == 11) isFirstData = false;
}
// else if (i == 1) continue;// 第二個檔案之後的 firstRow 不需要, start from 1
else //從第二個檔案 開始都從第二個 row 開始
{
Microsoft.Office.Interop.Excel.Range range = xlRange.Cells[i, j + 1] as Microsoft.Office.Interop.Excel.Range;
if (string.IsNullOrEmpty(range.Value) || string.IsNullOrWhiteSpace(range.Value))
MessageBox.Show("got it!");
//string ss = range.Value.ToString();
//ss = ss.Replace("[", "").Replace("]", "");
row[j] = range.Value.ToString();
}
if (j == colCount)
{
if (string.IsNullOrEmpty(row[j].ToString()) || string.IsNullOrWhiteSpace(row[j].ToString()))
MessageBox.Show("empty!");
}
}
if (string.IsNullOrEmpty(row[5].ToString()) || string.IsNullOrWhiteSpace(row[5].ToString()))
{
MessageBox.Show("empty!");
}
else
{
if (i == 1) continue;// 第二個檔案之後的 firstRow 不需要, start from 1
dt.Rows.Add(row);
}
}
//release com objects to fully kill excel process from running in the background
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
xlsSvc.insertDay2DB_enlux_gong34(dt, filename);
dt.Rows.Clear();
} //foreach excel.sheet
//close and release
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
x++;
}// foreach files
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
dataGridView1.DataSource = dt;
//MessageBox.Show(" dt.Rows.Count = " + dt.Rows.Count.ToString());
MessageBox.Show(" ok ");
//rule of thumb for releasing com objects:
// never use two dots, all COM objects must be referenced and released individually
// ex: [somthing].[something].[something] is bad
}
private void bt_sun_taoyuan_Click(object sender, EventArgs e)
{
string fname = "";
string[] fileEntries = new string[0];
Array.Clear(fileEntries, 0, fileEntries.Length);
//取得選取檔案的路徑
string dir;//= Path.GetDirectoryName(fname);
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
//dir = Path.GetDirectoryName(fname);
//fileEntries = Directory.GetFiles(fbd.SelectedPath);
fileEntries = Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories);
MessageBox.Show("Files found: " + fileEntries.Length.ToString(), "Message");
}
}
Service.operateCSV csvSvc = new Service.operateCSV(); // readCsvTxt
System.Data.DataTable dt = new System.Data.DataTable();
bool isFirst = true;
foreach (string fileName in fileEntries)
{
#region filename InvID
string fName = Path.GetFileName(fileName);
rt1.AppendText(fName + " ");
rt1.SelectionStart = rt1.Text.Length;
rt1.ScrollToCaret();
#endregion
if (isFirst)
{
//csvSvc.clear_inv("hour");
csvSvc.taoYuan_createColumnHour(ref dt, fileName);
csvSvc.taoYuan_readCsvFile(ref dt, fileName, dt.Columns.Count, isFirst);
isFirst = false;
}
else
csvSvc.taoYuan_readCsvFile(ref dt, fileName, dt.Columns.Count, isFirst);
}
MessageBox.Show(" 共 " + dt.Rows.Count.ToString());
//System.Data.DataTable dt = solarApp.Service.csvHelper.OpenCSV(fname);
csvSvc.taoYuan_insertHour2DB(ref dt, "sun_taoyuan");
MessageBox.Show("OK");
}
private void bt_sun_yadong_Click(object sender, EventArgs e)
{
string fname = "";
string[] fileEntries = new string[0];
Array.Clear(fileEntries, 0, fileEntries.Length);
//取得選取檔案的路徑
string dir;//= Path.GetDirectoryName(fname);
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
//dir = Path.GetDirectoryName(fname);
//fileEntries = Directory.GetFiles(fbd.SelectedPath);
fileEntries = Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories);
MessageBox.Show("Files found: " + fileEntries.Length.ToString(), "Message");
}
}
Service.operateCSV csvSvc = new Service.operateCSV(); // readCsvTxt
System.Data.DataTable dt = new System.Data.DataTable();
bool isFirst = true;
foreach (string fileName in fileEntries)
{
#region filename InvID
string fName = Path.GetFileName(fileName);
rt1.AppendText(fName + " ");
rt1.SelectionStart = rt1.Text.Length;
rt1.ScrollToCaret();
#endregion
if (isFirst)
{
//csvSvc.clear_inv("hour");
csvSvc.taoYuan_createColumnHour(ref dt, fileName);
csvSvc.taoYuan_readCsvFile(ref dt, fileName, dt.Columns.Count, isFirst);
isFirst = false;
}
else
csvSvc.taoYuan_readCsvFile(ref dt, fileName, dt.Columns.Count, isFirst);
}
//MessageBox.Show(" 共 " + dt.Rows.Count.ToString());
lbSiteName_sensor.Text = " sun 亞東觀音 共:" + dt.Rows.Count.ToString();
//System.Data.DataTable dt = solarApp.Service.csvHelper.OpenCSV(fname);
csvSvc.taoYuan_insertHour2DB(ref dt, "sun_yadong");
MessageBox.Show("OK");
}
}
}