新增頁面: 裝置管理 (系統管理底下)

This commit is contained in:
wanling040@gmail.com 2022-07-13 18:40:36 +08:00
parent 003efa79f6
commit f248541655
7 changed files with 619 additions and 16 deletions

View File

@ -0,0 +1,132 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SolarPower.Repository.Interface;
using SolarPower.Services.Interface;
using System.IO;
using SolarPower.Models;
using SolarPower.Models.SensorType;
namespace SolarPower.Controllers
{
public class SensorTypeController : MyBaseController<SensorTypeController>
{
private readonly ISensorTypeRepository sensorRepository;
private string boeFilePath = "/upload/power_station/boe_file/";
private string stationImageFilePath = "/upload/power_station/";
private string powerSationSaveAsPath = "";
public SensorTypeController(ISensorTypeRepository sensorRepository) : base()
{
this.sensorRepository = sensorRepository;
powerSationSaveAsPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "power_station");
}
public IActionResult Index()
{
sensorRepository.GetAllSensorAsync();
return View();
}
/// <summary>
/// 新增 / 修改 設備資料
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
[HttpPost]
public async Task<ApiResult<string>> SaveSensorType(SensorTypeInfo post)
{
ApiResult<string> apiResult = new ApiResult<string>();
SensorType sensor = null;
try
{
sensor = await sensorRepository.GetOneAsync(post.Id);
if (sensor == null)
{
if (post.Id != 0)
{
apiResult.Code = "9998";//待定
apiResult.Msg = errorCode.GetString(apiResult.Code);
return apiResult;
}
#region
sensor = new SensorType()
{
UId = post.UId,
Enabled = post.Enabled,
SensorName = post.SensorName,
SensorNameEn = post.SensorNameEn,
CreatedBy = myUser.Id,
};
List<string> properties = new List<string>()
{
"UId",
"Enabled",
"SensorName",
"SensorNameEn",
"CreatedBy",
};
var id = await sensorRepository.AddOneAsync(sensor, properties);
//var website_url = await powerStationRepository.GetOneVariableByName("WebSiteUrl");
//var sendSubject = "新增設備成功";
apiResult.Code = "0000";
apiResult.Msg = "儲存成功";
#endregion
}
else
{
#region
SensorType update = new SensorType()
{
Id = sensor.Id,
Enabled = post.Enabled,
SensorName = post.SensorName,
SensorNameEn = post.SensorNameEn,
UpdatedBy = myUser.Id
};
List<string> properties = new List<string>()
{
"Id",
"Enabled",
"SensorName",
"SensorNameEn",
"UpdatedBy",
};
await sensorRepository.UpdateSensorInfo(update, properties);
apiResult.Code = "0000";
apiResult.Msg = "儲存成功";
#endregion
}
}
catch (Exception exception)
{
apiResult.Code = "9999";
apiResult.Msg = errorCode.GetString(apiResult.Code);
string json = System.Text.Json.JsonSerializer.Serialize(post);
Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
}
return apiResult;
}
}
}

View File

@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SolarPower.Models.SensorType
{
//Base Class。如由其餘需求使用繼承
public class SensorType : SensorTypeInfo
{
//public int Id { get; set; } //編號
public byte Deleted { get; set; } //是否刪除
//public int UId { get; set; } //設備編號
//public int Enabled { get; set; } //啟用
//public string SensorName { get; set; } //sensor名稱
//public string SensorNameEn { get; set; } //sensor英文名稱
}
/// <summary>
/// 設備
/// </summary>
public class SensorTypeInfo : UserInfo
{
public int UId { get; set; }//設備編號
public string SensorName { get; set; }//傳感器名稱
public string SensorNameEn { get; set; }//傳感器英文名稱
public int Enabled { get; set; }//啟用
}
}

View File

@ -0,0 +1,142 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SolarPower.Models;
using SolarPower.Models.SensorType;
using SolarPower.Repository.Interface;
using Dapper;
using SolarPower.Helper;
using System.Data;
namespace SolarPower.Repository.Implement
{
public class SensorTypeRepository : RepositoryBase<SensorType>, ISensorTypeRepository
{
public SensorTypeRepository(IDatabaseHelper databaseHelper) : base(databaseHelper)
{
tableName = "sensor_type";
}
public async Task<List<SensorType>> GetAllSensorAsync()
{
List<SensorType> result;
using (IDbConnection conn = this._databaseHelper.GetConnection())
{
try
{
var sql = $"SELECT Id, Deleted, Enabled, UID, SensorName, SensorNameEn FROM solar_master.sensor_type WHERE deleted = 0";
result = (await conn.QueryAsync<SensorType>(sql)).ToList();
}
catch (Exception exception)
{
throw exception;
}
return result;
}
}
/// <summary>
/// 新增裝置資料
/// </summary>
/// <param name="SensorInfo"></param>
/// <param name="properties"></param>
/// <returns></returns>
public async Task AddSensor(SensorType sensorInfo, List<string> properties)
{
using (IDbConnection conn = _databaseHelper.GetConnection())
{
conn.Open();
//var trans = conn.BeginTransaction();
using (var trans = conn.BeginTransaction())
{
try
{
//string sql = GenerateInsertQueryWithCustomDBNameAndTable(properties, db_name, "device");
//await conn.ExecuteAsync(sql, DeviceInfo);
//trans.Commit();
//var sql2 = GenerateUpdateQuery(properties);
var sql = GenerateInsertQueryWithCustomTable(properties, "sensor_type");
await conn.ExecuteAsync(sql, sensorInfo, trans);
trans.Commit();
//string sql = $"INSERT INTO company_auth_page (CompanyId, AuthCode, CreatedBy) VALUES (@CompanyId, @AuthCode, @CreatedBy)";
//await conn.ExecuteAsync(sql, trans);
//trans.Commit();
}
catch (Exception exception)
{
trans.Rollback();
throw exception;
}
finally
{
conn.Close();
}
}
}
}
/// <summary>
/// 透過sensorNameEn取得單一筆資料
/// </summary>
/// <param name="sensorNameEn"></param>
/// <returns></returns>
public async Task<SensorType> GetOneByEnglishNameAsync(string sensorNameEn)
{
SensorType result;
using (IDbConnection conn = _databaseHelper.GetConnection())
{
try
{
var sql = $"SELECT * FROM solar_master.sensor_type WHERE deleted = 0 AND sensorNameEn = @SensorNameEn";
result = await conn.QueryFirstOrDefaultAsync<SensorType>(sql, new { SensorName_En = sensorNameEn });
}
catch (Exception exception)
{
throw exception;
}
return result;
}
}
/// <summary>
/// 修改設備資料
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public async Task UpdateSensorInfo(SensorType entity, List<string> properties)
{
GetProperties = typeof(SensorType).GetProperties();
using (IDbConnection conn = _databaseHelper.GetConnection())
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
try
{
var sql = GenerateUpdateQuery(properties);
await conn.ExecuteAsync(sql, entity, trans);
trans.Commit();
}
catch (Exception exception)
{
trans.Rollback();
throw exception;
}
finally
{
conn.Close();
}
}
}
}
}
}

View File

@ -0,0 +1,40 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SolarPower.Models;
using SolarPower.Models.SensorType;
using SolarPower.Repository.Interface;
namespace SolarPower.Repository.Interface
{
public interface ISensorTypeRepository : IRepositoryBase<SensorType>
{
Task<List<SensorType>> GetAllSensorAsync();
/// <summary>
/// 新增 設備
/// </summary>
/// <param name=""></param>
/// <returns></returns>
Task AddSensor(SensorType SensorInfo, List<string> properties);
/// <summary>
/// 透過sensorNameEn取得單一筆資料
/// </summary>
/// <param name="sensorNameEn"></param>
/// <returns></returns>
Task<SensorType> GetOneByEnglishNameAsync(string sensorNameEn);
/// <summary>
/// 修改設備資料
/// </summary>
/// <param name="entity"></param>
/// <param name="properties"></param>
/// <returns></returns>
Task UpdateSensorInfo(SensorType entity, List<string> properties);
}
}

View File

@ -82,6 +82,7 @@ namespace SolarPower
services.AddTransient<IStationReportRepository, StationReportRepository>();
services.AddTransient<INoticeScheduleRepository, NoticeScheduleRepository>();
services.AddTransient<IElectricitySoldRecordRepository, ElectricitySoldRecordRepository>();
services.AddTransient<ISensorTypeRepository, SensorTypeRepository>();
#endregion
double loginExpireMinute = this.Configuration.GetValue<double>("LoginExpireMinute");

View File

@ -0,0 +1,249 @@
@{
ViewData["MainNum"] = "7";
ViewData["SubNum"] = "3";
ViewData["Title"] = "裝置管理";
}
@using SolarPower.Models.Role
@model RoleLayerEnum
<ol class="breadcrumb page-breadcrumb">
<li class="breadcrumb-item"><a href="javascript:void(0);">系統管理</a></li>
<li class="breadcrumb-item active">@ViewData["Title"]</li>
<li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
</ol>
<div class="subheader">
<h1 class="subheader-title">
<i class='subheader-icon fal fa-globe'></i> @ViewData["Title"]
</h1>
</div>
<!-- Your main content goes below here: -->
<div class="row">
<div class="col-xl-12">
<div id="panel-5" class="panel">
<div class="panel-container show">
<div class="panel-content">
@*只有平台人員可以新增公司*@
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformUser)
{
<button type="button" class="btn btn-success waves-effect waves-themed mb-3" onclick="AddSensor()">
<span class="fal fa-plus mr-1"></span>
新增
</button>
}
<div class="card-body">
<div class="w-100">
<table id="SensorType_table" class="table table-bordered table-hover m-0 text-center">
<thead class="thead-themed">
<tr>
<th>設備編號</th>
<th>啟用</th>
<th>Sensor名稱</th>
<th>Sensor英文名稱</th>
<th>建立時間</th>
<th>功能</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="SensorType-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">
裝置資料 - 新增
</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><i class="fal fa-times"></i></span>
</button>
</div>
<div class="modal-body">
<form class="SensorType-form" id="SensorType-form">
<div class="row">
<div class="form-group col-lg-6">
<label class="form-label" for="Sensor_Device_modal"><span class="text-danger">*</span>設備編號</label>
<input type="text" id="Sensor_Device_modal" name="Sensor_Device_modal" class="form-control">
</div>
<div class="form-group col-lg-6">
<label class="form-label" for="Sensor_Name_modal"><span class="text-danger">*</span>設備名稱</label>
<input type="text" id="Sensor_Name_modal" name="Sensor_Name_modal" class="form-control">
</div>
<div class="form-group col-lg-6">
<label class="form-label" for="Sensor_EName_modal"><span class="text-danger">*</span>設備英文名稱</label>
<input type="text" id="Sensor_EName_modal" name="Sensor_EName_modal" class="form-control">
</div>
<div class="form-group col-lg-3">
<label class="form-label" for="Sensor_Enabled_modal">啟用</label>
<select class="form-control" id="Sensor_Enabled_modal">
<option value="0" action>未啟用</option>
<option value="1">啟用</option>
</select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" onclick="SaveSensorType()">確定</button>
</div>
</div>
</div>
</div>
@section Scripts {
<script>
//var userTable; var roleTable; var roleAuthTable; var roleAuthNotJoinTable;
//var selected_id = 0, selected_role_id = 0, selected_company_id = 0;
//var selected_tab = "";
//#region 新增裝置資料
function AddSensor() {
selected_id = 0;
document.getElementById('Sensor_Enabled_modal').disabled = false;
$("#SensorType-modal .modal-title").html("裝置資料 - 新增");
$("#SensorType-form").trigger("reset");
$("#SensorType-modal").modal();
}
//#endregion
//#region 使用者列表 DataTable
//userTable = $("#SensorType_table").DataTable({
// "paging": true,
// "lengthChange": false,
// "searching": false,
// "ordering": true,
// "info": true,
// "autoWidth": false,
// "responsive": false,
// "deferLoading": 0,
// "order": [[4, "desc"]],
// "columns": [{
// "data": "uId"
// }, {
// "data": "enabled"
// }, {
// "data": "name"
// }, {
// "data": "englishName"
// }, {
// "data": "createdAt"
// }, {
// "data": null,
// "defaultContent": '<button class="btn btn-primary edit-btn">修改</button> <button class="btn btn-danger del-btn">刪除</button>'
// }
// ],
// "columnDefs": [{
// 'targets': 2,
// 'searchable': false,
// 'orderable': false,
// 'render': function (data, type, full, meta) {
// return '<a href="javascript:void(0);" onclick="GetUserPowerStation(' + full.id + ')">' + data + '</a>';
// }
// }],
// "language": {
// "emptyTable": "查無資料",
// "processing": "處理中...",
// "loadingRecords": "載入中...",
// "lengthMenu": "顯示 _MENU_ 項結果",
// "zeroRecords": "沒有符合的結果",
// "info": "顯示第 _START_ 至 _END_ 項結果,共 _TOTAL_ 項",
// "infoEmpty": "顯示第 0 至 0 項結果,共 0 項",
// "infoFiltered": "(從 _MAX_ 項結果中過濾)",
// "infoPostFix": "",
// "search": "搜尋:",
// "paginate": {
// "first": "第一頁",
// "previous": "上一頁",
// "next": "下一頁",
// "last": "最後一頁"
// },
// "aria": {
// "sortAscending": ": 升冪排列",
// "sortDescending": ": 降冪排列"
// }
// },
// 'createdRow': function (row, data, dataIndex) {
// $(row).attr('data-id', data.id);
// },
// "ajax": {
// "url": "/User/UserList",
// "type": "POST",
// "data": function (d) {
// d.SelectedCompanyId = $('#select_user_company_userManager_tab').val();
// d.Name = $('#user_name').val();
// d.SelectedRoleId = $('#select_company_role_userManager_tab').val();
// },
// "dataSrc": function (rel) {
// if (rel.data.code == "9999") {
// toast_error(rel.data.msg);
// return;
// }
// data = rel.data.data;
// if (data == null || data.length == 0) {
// this.data = [];
// }
// return data;
// }
// },
// "error": function (xhr, error, thrown) {
// console.log(xhr);
// }
//});
//#endregion
//#region 儲存裝置資料
//function SaveSensorType() {
// if ($("#SensorType-form").valid()) {
// var url = "/SensorType/SaveSensorType";
// var a = padLeft($("#Device_ColName_modal").val(), 2);
// var send_data = {
// Id: selected_id,
// PowerStationId: stationId,
// Name: $("#Device_Name_modal").val(),
// ControllerId: $("#Device_Controller_modal").val(),
// Type: $("#Device_Type_modal").val(),
// TypeName: $("#Device_Type_modal :selected").text(),
// Brand: $("#Device_Brand_modal").val(),
// ProductModel: $("#Device_ProductModel_modal").val(),
// //DBName: $("#Device_DBName_modal").val(),
// TableName: $("#SensorType_TableName_modal").val(),
// ColName: "SENSORAVG" + a,
// InstallDate: $("#Device_InstallDate_modal").val(),
// Status: $("#Device_Status_modal").val(),
// Enabled: $("#Device_Enabled_modal").val(),
// WarrantyDate: $("#Device_WarrantyDate_modal").val()
// }
// $.post(url, send_data, function (rel) {
// if (rel.code != "0000") {
// toast_error(rel.msg);
// return;
// }
// else {
// toast_ok(rel.msg);
// $('#Device-modal').modal('hide');
// DeviceTable.ajax.reload();
// return;
// }
// }, 'json');
// }
//}
//#endregion
</script>
}

View File

@ -394,7 +394,7 @@
</li>
}
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("Company") || ViewBag.auths.Contains("User") || ViewBag.auths.Contains("Role") || ViewBag.auths.Contains("User"))@*TODO修改定時任務權限*@
@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("Company") || ViewBag.auths.Contains("User") || ViewBag.auths.Contains("Role") || ViewBag.auths.Contains("User") || ViewBag.auths.Contains("SensorType"))@*TODO修改定時任務權限*@
{
<li class="@(ViewData["MainNum"] == "7" ? "active open" : "")">
<a href="#" title="系統管理" data-filter-tags="category">
@ -418,22 +418,30 @@
</a>
</li>
}
@*@if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.auths.Contains("SensorType"))
{
<li class="@(ViewData["MainNum"] == "7" && ViewData["SubNum"] == "3" ? "active" : "")">
<a asp-controller="SensorType" 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.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>
}