commit 93f1fb558ef6673dd8f3bfebdd22b49de7dddad0 Author: keke Date: Thu Aug 3 10:47:34 2023 +0800 first commit carviolation 後端專案上傳 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1c9a181 --- /dev/null +++ b/.gitignore @@ -0,0 +1,242 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +[Xx]64/ +[Xx]86/ +[Bb]uild/ +bld/ +[Bb]in/ +[Oo]bj/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml + +# TODO: Un-comment the next line if you do not want to checkin +# your web deploy settings because they may include unencrypted +# passwords +#*.pubxml +*.publishproj + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directory +AppPackages/ +BundleArtifacts/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# LightSwitch generated files +GeneratedArtifacts/ +ModelManifest.xml + +# Paket dependency manager +.paket/paket.exe + +# FAKE - F# Make +.fake/ diff --git a/Traffic.Api/Controllers/AccountController.cs b/Traffic.Api/Controllers/AccountController.cs new file mode 100644 index 0000000..07e295d --- /dev/null +++ b/Traffic.Api/Controllers/AccountController.cs @@ -0,0 +1,305 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using Traffic.Data.Enums; +using Traffic.Data.ViewModels; +using Traffic.Service.Filter; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + [Route("api/user")] + [Authorize] + [ApiController] + [ServiceFilter(typeof(LogFilter))] + public class AccountController : ControllerBase + { + private readonly IAccountService _service; + private readonly ILogger _logger; + + public AccountController(IAccountService service, ILogger logger) + { + _service = service; + _logger = logger; + } + + /// + /// 取得 使用者資訊 + /// + /// 使用者 Id + /// + [HttpGet("{id}")] + public IActionResult GetAccountUser(int id) + { + try + { + var result = _service.GetAccountUser(id); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得 UserData 列表 + /// + /// + /// + /// + [HttpGet("GetUserDataList")] + public IActionResult GetUserDataList([FromQuery] SearchModelViewModel searchModel, int? Id) + { + try + { + var result = new Response(); + var model = Util.GetSearchModel(searchModel); + result.Result = _service.GetUserDataList(model, Id); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 新增使用者 + /// + /// 新增的使用者資訊 + /// + /// 管理者Admin RoleCodeId = 0, 一般User RoleCodeId = 1 + [HttpPost("PostUserDataList")] + public IActionResult InserAccountUser(UserData account) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var mID = new ParserForUserFromClaim(userIdentity).GetUserId(); + + var result = _service.InserAccountUser(mID, account); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 管理者修改使用者狀態 + /// + /// + /// 狀態 + /// + /// 0:Disable, 1:Enable + [HttpPut("PutUserStatus/{id}")] + public IActionResult PutUserStatus(int id, int status) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var byWho = new ParserForUserFromClaim(userIdentity).GetUserId(); + var result = _service.PutUserbyAdmin(byWho, id, status); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 管理者修改使用者 + /// + /// + /// 管理者欲修改的使用者資訊 + /// + /// 管理者Admin RoleCodeId = 0, 一般User RoleCodeId = 1 + [HttpPut("PutUserData/{id}")] + public IActionResult UpdateAccountbyAdmin(int id, UserData account) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var byWho = new ParserForUserFromClaim(userIdentity).GetUserId(); + account.Id = id; + var result = _service.UpdateAccountbyAdmin(byWho, account); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 管理者修改使用者密碼 + /// + /// 使用者Id + /// + /// 管理者Admin RoleCodeId = 0, 一般User RoleCodeId = 1 + [HttpPut("PutUserPassword/{id}")] + public IActionResult UpdateAccountPasswordbyAdmin(int id) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var byWho = new ParserForUserFromClaim(userIdentity).GetUserId(); + + var result = _service.UpdateAccountPasswordbyAdmin(id, byWho); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + ///// + ///// 使用者修改自己的帳號資訊 + ///// + ///// 使用者自己欲修改的資訊 + ///// + //[HttpPut("")] + //public IActionResult UpdateAccountbyUser(UserData account) + //{ + // var userIdentity = (ClaimsIdentity)User.Identity; + // var byWho = new ParserForUserFromClaim(userIdentity).GetUserId(); + + // var result = _service.UpdateAccountbyUser(byWho, account); + // return result.Success ? Ok(result) : BadRequest(result); + //} + + /// + /// 修改密碼 + /// + /// 修改前後的密碼 + /// + [HttpPut("PutUserPassword")] + public IActionResult UpdateAccountPassword(UserData account) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var byWho = new ParserForUserFromClaim(userIdentity).GetUserId(); + var byWhoAccount = new ParserForUserFromClaim(userIdentity).GetAccount(); + + account.Id = byWho; + account.Account = byWhoAccount; + + var result = _service.UpdateAccountPasswordByUser(byWho, account); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception ex) + { + return BadRequest(ex.ToString()); + } + } + + /// + /// 刪除使用者帳號 + /// + /// + /// + [HttpDelete("DeleteUserData")] + public IActionResult DeleteUserData(int id) + { + try + { + return Ok(_service.DeleteUserData(id)); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 是否存在此User + /// + /// + /// + [HttpGet("GetExistUser")] + public IActionResult GetExistUser(string account) + { + try + { + var result = _service.GetExistUser(account); + return Ok(new { Result = result }); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得使用者名稱列表 + /// + /// + [HttpGet("GetUserNameList")] + public IActionResult GetUserNameList() + { + try + { + var result = _service.GetUserNameList(); + return Ok(new { Result = result }); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得使用者站點列表 + /// + /// + [HttpGet("GetUserSite")] + public IActionResult GetUserSite() + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var id = new ParserForUserFromClaim(userIdentity).GetUserId(); + + var result = _service.GetUserSite(id); + return Ok(new { Result = result }); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得使用者站點資訊列表 + /// + /// + [HttpGet("GetUserSiteInfo")] + public IActionResult GetUserSiteInfo() + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var id = new ParserForUserFromClaim(userIdentity).GetUserId(); + + var result = _service.GetUserSiteInfo(id); + return Ok(new { Result = result }); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/AnnounceController.cs b/Traffic.Api/Controllers/AnnounceController.cs new file mode 100644 index 0000000..5204163 --- /dev/null +++ b/Traffic.Api/Controllers/AnnounceController.cs @@ -0,0 +1,137 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Filter; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + /// + /// 公佈欄管理 + /// + [Route("api/announce")] + [Authorize] + [ApiController] + [ServiceFilter(typeof(LogFilter))] + public class AnnounceController : ControllerBase + { + private readonly IAnnounceService _service; + + public AnnounceController(IAnnounceService service) + { + _service = service; + } + + /// + /// 取得公告列表 + /// + /// + /// + [HttpGet("")] + public IActionResult GetAnnounces([FromQuery] SearchModelViewModel searchModel) + { + try + { + var result = new Response(); + var model = Util.GetSearchModel(searchModel); + result.Result = _service.GetAnnounces(model); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得公告 by id + /// + /// + /// + [HttpGet("{id}")] + public IActionResult GetAnnounce(int id) + { + try + { + var result = new Response(); + result.Result = _service.GetAnnounceById(id); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 新增公告 + /// + /// + /// + [HttpPost("")] + public IActionResult InsertAnnounce(AnnounceInsertViewModel vm) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var byWho = new ParserForUserFromClaim(userIdentity).GetUserId(); + + var result = _service.InsertAnnounce(byWho, vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 修改公告 + /// + /// 公告的流水號 + /// + /// + [HttpPut("{id}")] + public IActionResult UpdateAnnounce(int id, AnnounceInsertViewModel vm) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var byWho = new ParserForUserFromClaim(userIdentity).GetUserId(); + + var result = _service.UpdatAnnounce(id, vm, byWho); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 刪除公告 + /// + /// 公告的流水號 + /// + [HttpDelete("{id}")] + public IActionResult DeleteAnnounce(int id) + { + try + { + var result = _service.DeleteAnnounce(id); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/CompanyInformationController.cs b/Traffic.Api/Controllers/CompanyInformationController.cs new file mode 100644 index 0000000..8dffedc --- /dev/null +++ b/Traffic.Api/Controllers/CompanyInformationController.cs @@ -0,0 +1,162 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + /// + /// 廠商資料設定 + /// + [Route("api/companyInformation")] + [Authorize] + [ApiController] + public class CompanyInformationController : ControllerBase + { + private readonly ICompanyInformationService _service; + + public CompanyInformationController(ICompanyInformationService service) + { + _service = service; + } + + /// + /// 取得廠商資料設定列表 + /// + [AllowAnonymous] + [HttpGet("all")] + public IActionResult GetCompanyInformations() + { + try + { + var result = new Response(); + result.Result = _service.GetCompanyInformations(); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得廠商資料設定列表 (Email 空白的不顯示) + /// + [AllowAnonymous] + [HttpGet("all/emailNotNull")] + public IActionResult GetCompanyInformationsEmailNotNull() + { + try + { + var result = new Response(); + result.Result = _service.GetCompanyInformationsEmailNotNull(); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得廠商資料設定列表 + /// + /// + /// + [HttpGet("")] + public IActionResult GetCompanyInformations([FromQuery] SearchModelViewModel searchModel) + { + try + { + var result = new Response(); + var model = Util.GetSearchModel(searchModel); + result.Result = _service.GetCompanyInformations(model); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得廠商資料 by id + /// + /// + /// + [HttpGet("{id}")] + public IActionResult GetCompanyInformation(int id) + { + try + { + var result = new Response(); + result.Result = _service.GetCompanyInformationById(id); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 新增廠商資料設定 + /// + /// + /// + [HttpPost("")] + public IActionResult InsertCompanyInformation(CompanyInformationViewModel vm) + { + try + { + var result = _service.InsertCompanyInformation(vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 修改廠商資料設定 + /// + /// 廠商資料的流水號 + /// + /// + [HttpPut("{id}")] + public IActionResult UpdateCompanyInformation(int id, CompanyInformationViewModel vm) + { + try + { + var result = _service.UpdatCompanyInformation(id, vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 刪除廠商資料 + /// + /// 廠商資料的流水號 + /// + [HttpDelete("{id}")] + public IActionResult DeleteCompanyInformation(int id) + { + try + { + var result = _service.DeleteCompanyInformation(id); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/EventController.cs b/Traffic.Api/Controllers/EventController.cs new file mode 100644 index 0000000..f4ce02f --- /dev/null +++ b/Traffic.Api/Controllers/EventController.cs @@ -0,0 +1,441 @@ +using ClosedXML.Excel; +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + /// + /// 事件 + /// + [Route("api/event")] + [Authorize] + [ApiController] + public class EventController : ControllerBase + { + private readonly IEventService _service; + private readonly IFileService _fileService; + private readonly IEventTypeService _eventTypeService; + + public EventController(IFileService fileService, IEventService service, IEventTypeService eventTypeService) + { + _fileService = fileService; + _service = service; + _eventTypeService = eventTypeService; + } + + /// + /// 取得事件列表 Term = 車牌號碼(Number) + /// + /// + /// + /// Term = 車牌號碼(Number) + [HttpGet("")] + public IActionResult GetEvents([FromQuery] SearchModelViewModel searchModel) + { + try + { + var result = new Response(); + var model = Util.GetSearchModel(searchModel); + result.Result = _service.GetEventsByCar(model); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + ///// + ///// 取得某站點的事件列表 + ///// + ///// + ///// + ///// + ///// Term = 車牌號碼(Number) + //[HttpGet("siteId/{siteId}")] + //public IActionResult GetEventBySites(string siteId, [FromQuery] SearchModelViewModel searchModel) + //{ + // var result = new Response(); + // var model = Util.GetSearchModel(searchModel); + // result.Result = _service.GetEventBySites(siteId, model); + // return Ok(result); + //} + + /// + /// 取得開單畫面的事件 + /// + /// 違規項目 + /// 起始時間 + /// 結束時間 + /// 站點 + /// 狀態 + /// 違停時間 + /// 速度 + /// 0 : 查詢, 1:匯出 + /// + [HttpGet("eventType/{eventType}")] + public IActionResult GetEventByEventType(string eventType, string startTime, string endTime, string site = "ALL", string status = "ALL", string time = "ALL", string speed = "ALL", string method = "0") + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var id = new ParserForUserFromClaim(userIdentity).GetUserId(); + var result = new Response(); + + startTime = startTime.Replace("undefined", "00:00:00"); + endTime = endTime.Replace("undefined", "23:59:59"); + //if (startTime == endTime || (startTime.Length == 10 && endTime.Length == 10)) + //{ + // startTime = startTime.Substring(0, 10) + " 00:00:00"; + // endTime = endTime.Substring(0, 10) + " 23:59:59"; + //} + + var events = _service.GetEventsByEventType(id, eventType, startTime, endTime, site, status, time, speed); + if (events == null) + { + var res = new TradeResultModel(); + res.Success = false; + res.Message = "查詢筆數過多,請重新查詢。"; + return BadRequest(res); + } + + var eventTypeViewModel = _eventTypeService.GetEventTypeByEventType(eventType); + var eventName = string.Empty; + if (eventTypeViewModel != null) + { + eventName = eventTypeViewModel.EventName; + }; + result.Result = events; + + if (method == "1") + { + var url = _fileService.ExportEvent( + Convert.ToDateTime(startTime).ToString("yyMMdd"), + Convert.ToDateTime(endTime).ToString("yyMMdd"), + eventName, events); + return Ok(url); + } + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得今年累計處理案件數 (punished = 1) + /// + /// + [HttpGet("count/thisYear")] + public IActionResult GetThisYearEventsCount() + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var account = new ParserForUserFromClaim(userIdentity).GetAccount(); + var result = new Response + { + Result = _service.GetThisYearEventsCount(account) + }; + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得本月新增案件數量 + /// + /// + [HttpGet("count/thisMonth")] + public IActionResult GetThisMonthEventsCount() + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var account = new ParserForUserFromClaim(userIdentity).GetAccount(); + var result = new Response + { + Result = _service.GetThisMonthEventsCount(account) + }; + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得處理進度 by 時間區間 + /// + /// + /// 時間格式 yyyy-MM-dd + [HttpGet("count/interval")] + public IActionResult GetEventsby(string startDatetime, string endDatetime) + { + try + { + var result = new Response(); + result.Result = _service.GetEventsCount(startDatetime, endDatetime); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得事件 by id + /// + /// + /// + [HttpGet("{id}")] + public IActionResult GetEvent(int id) + { + try + { + var result = new Response(); + result.Result = _service.GetEventById(id); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + ///// + ///// 新增事件 + ///// + ///// + ///// + //[HttpPost("")] + //public IActionResult InsertEvent(EventViewModel vm) + //{ + // var result = _service.InsertEvent(vm); + // return result.Success ? Ok(result) : BadRequest(result); + //} + + ///// + ///// 修改事件 + ///// + ///// 事件的流水號 + ///// + ///// + //[HttpPut("{id}")] + //public IActionResult UpdateEvent(int id, EventViewModel vm) + //{ + // var result = _service.UpdatEvent(id, vm); + // return result.Success ? Ok(result) : BadRequest(result); + //} + + /// + /// 修改事件 成 CheckPunish (確認開單) + /// + /// 事件的流水號 + /// 違規法條 + /// + [HttpPut("{eventId}/checkPunish")] + public IActionResult UpdatEventCheckPunish(int eventId, string law) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var account = new ParserForUserFromClaim(userIdentity).GetAccount(); + var result = _service.UpdatEventCheckPunish(account, eventId, "1", law); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 批次確認開單 + /// + /// + /// 違規法條 + /// + [HttpPut("muti/checkPunish")] + public IActionResult UpdatEventCheckPunish(List eventId, string law) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var account = new ParserForUserFromClaim(userIdentity).GetAccount(); + var result = _service.UpdatEventCheckPunishList(account, eventId, "1", law); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + + ///// + ///// 修改事件 取消開單 + ///// + ///// 事件的流水號 + ///// + //[HttpPut("{id}/checkPunishRollback")] + //public IActionResult UpdatEventCheckPunishRollback(int id) + //{ + // var userIdentity = (ClaimsIdentity)User.Identity; + // var account = new ParserForUserFromClaim(userIdentity).GetAccount(); + // var result = _service.UpdatEventCheckPunish(account, id, "0"); + // return result.Success ? Ok(result) : BadRequest(result); + //} + + /// + /// 修改事件 成 不開單 + /// + /// 事件的流水號 + /// + /// + [HttpPut("{eventId}/nopunish")] + public IActionResult UpdatEventNoPunish(int eventId, string reason) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var account = new ParserForUserFromClaim(userIdentity).GetAccount(); + var result = _service.UpdatEventNoPunish(account, eventId, reason); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取消開單 + /// + /// 事件的流水號 + /// + [HttpPut("{eventId}/cancel")] + public IActionResult UpdatEventCancel(int eventId) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var account = new ParserForUserFromClaim(userIdentity).GetAccount(); + var result = _service.UpdatEventCancel(account, eventId); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + ///// + ///// 刪除事件 + ///// + ///// 事件的流水號 + ///// + //[HttpDelete("{id}")] + //public IActionResult DeleteEvent(int id) + //{ + // var result = _service.DeleteEvent(id); + // return result.Success ? Ok(result) : BadRequest(result); + //} + + /// + /// 修改事件的車子類型 + /// + /// 事件的流水號 + /// + /// + [HttpPut("{eventId}/vehicleType")] + public IActionResult UpdateEventVehicleType(int eventId, string vehicleType) + { + try + { + var result = _service.UpdatEventVehicleType(eventId, vehicleType); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 修改事件的車牌號碼 + /// + /// 事件的流水號 + /// + /// + [HttpPut("{eventId}/vehicleNumber")] + public IActionResult UpdateEventVehicleNumber(int eventId, string vehicleNumber) + { + try + { + var result = _service.UpdatEventVehicleNumber(eventId, vehicleNumber); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 修改事件的車牌號碼和車子類型 + /// + /// 事件的流水號 + /// + /// + /// + [HttpPut("{eventId}/vehicle")] + public IActionResult UpdateEventVehicle(int eventId, string vehicleType, string vehicleNumber) + { + try + { + var result = _service.UpdatEventVehicle(eventId, vehicleType, vehicleNumber); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + [HttpGet("vehicle/all")] + public IActionResult GetVehicleTypes() + { + try + { + var result = new Response(); + result.Result = _service.GetVehicleTypes(); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/EventTypeController.cs b/Traffic.Api/Controllers/EventTypeController.cs new file mode 100644 index 0000000..47a5a8a --- /dev/null +++ b/Traffic.Api/Controllers/EventTypeController.cs @@ -0,0 +1,166 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + /// + /// 違規事件 + /// + [Route("api/eventType")] + [Authorize] + [ApiController] + public class EventTypeController : ControllerBase + { + private readonly IEventTypeService _service; + + public EventTypeController(IEventTypeService service) + { + _service = service; + } + + /// + /// 取得所有違規列表 (EventType) + /// + /// + [HttpGet("all")] + public IActionResult GetEventTypes() + { + try + { + var result = new Response(); + result.Result = _service.GetEventTypes(); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得所有違規列表 (EventType1) + /// + /// + [HttpGet("1/all")] + public IActionResult GetEventType1s() + { + try + { + var result = new Response(); + result.Result = _service.GetEventType1s(); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得 EventType 列表 + /// + /// + /// + [HttpGet("")] + public IActionResult GetEventTypes([FromQuery] SearchModelViewModel searchModel) + { + try + { + var result = new Response(); + var model = Util.GetSearchModel(searchModel); + result.Result = _service.GetEventTypes(model); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得 EventType by id + /// + /// + /// + [HttpGet("{id}")] + public IActionResult GetEventType(int id) + { + try + { + var result = new Response(); + result.Result = _service.GetEventTypeById(id); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 新增 EventType + /// + /// + /// + [HttpPost("")] + public IActionResult InsertEventType(EventTypeViewModel vm) + { + try + { + var result = _service.InsertEventType(vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 修改 EventType + /// + /// EventType 的流水號 + /// + /// + [HttpPut("{id}")] + public IActionResult UpdateEventType(int id, EventTypeViewModel vm) + { + try + { + var result = _service.UpdatEventType(id, vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 刪除 EventType + /// + /// EventType 的流水號 + /// + [HttpDelete("{id}")] + public IActionResult DeleteEventType(int id) + { + try + { + var result = _service.DeleteEventType(id); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/LoginController.cs b/Traffic.Api/Controllers/LoginController.cs new file mode 100644 index 0000000..72c3e4a --- /dev/null +++ b/Traffic.Api/Controllers/LoginController.cs @@ -0,0 +1,108 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Helpers; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + [Route("api/login")] + [ApiController] + public class LoginController : ControllerBase + { + private readonly ILoginService _service; + private readonly JwtHelpers _jwt; + private IHttpContextAccessor _accessor; + private readonly IConfiguration _configuration; + public LoginController(ILoginService service, JwtHelpers jwt, IHttpContextAccessor accessor, IConfiguration configuration) + { + _service = service; + _jwt = jwt; + _accessor = accessor; + _configuration = configuration; + } + + /// + /// 登入 + /// + /// + /// + [HttpPost("PostLogin")] + public LoginResultModel PostLogin(LoginViewModel loginData) + { + var ip = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString(); + var result = new LoginResultModel(); + var user = this._service.Login(loginData.Account, loginData.Password, ip); + if (user == null) + { + result.Success = false; + result.Message = "查無此使用者,請洽管理員。"; + return result; + } + + if (user.Status == 0) + { + result.Success = false; + result.Message = "此使用者已被禁用,請洽管理員。"; + return result; + } + + if ((DateTime.Now - user.ChangePwdOn).Days > Convert.ToInt16(_configuration["User:NeedChangePwdDay"])) + { + result.Success = false; + result.Message = $"已超過{_configuration["User:NeedChangePwdDay"]}天未更改密碼,請洽管理員。"; + return result; + } + + var errorCount = Convert.ToInt16(_configuration["User:LoginErrorCount"]); + if (user.ErrorCount > errorCount) + { + result.Success = false; + result.Message = $"輸入密碼已累積超過錯誤{errorCount}次,請洽管理員。"; + return result; + } + + if (user.ErrorCount != 0) + { + result.Success = false; + result.Message = $"輸入密碼已累積錯誤{user.ErrorCount}次。"; + return result; + } + + if ((DateTime.Now - user.ChangePwdOn).Days > Convert.ToInt16(_configuration["User:AlarmChangePwdDay"])) + { + result.Success = true; + result.Message = $"已超過{_configuration["User:AlarmChangePwdDay"]}天未更改密碼,請立即更改密碼。"; + result.Token = this._jwt.GenerateToken(user); + result.Role = user.Role; + result.Name = user.Name; + result.Id = user.Id; + return result; + } + + if (loginData.Password == "000000") + { + result.Success = true; + result.Message = $"請立即更改密碼。"; + result.Token = this._jwt.GenerateToken(user); + result.Role = user.Role; + result.Name = user.Name; + result.Id = user.Id; + return result; + } + + result.Success = true; + result.Message = "success!"; + result.Token = this._jwt.GenerateToken(user); + result.Role = user.Role; + result.Name = user.Name; + result.Id = user.Id; + return result; + } + } +} diff --git a/Traffic.Api/Controllers/MalfunctionController.cs b/Traffic.Api/Controllers/MalfunctionController.cs new file mode 100644 index 0000000..703c5a9 --- /dev/null +++ b/Traffic.Api/Controllers/MalfunctionController.cs @@ -0,0 +1,71 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + [Route("api/malfunction")] + [Authorize] + [ApiController] + public class MalfunctionController : ControllerBase + { + private readonly IMalfunctionService _service; + + public MalfunctionController(IMalfunctionService service) + { + _service = service; + } + + ///// + ///// 取得設備狀態 + ///// + ///// + //[HttpGet("old")] + //public IActionResult GetMalfunctionsOld() + //{ + // try + // { + // var userIdentity = (ClaimsIdentity)User.Identity; + // var userid = new ParserForUserFromClaim(userIdentity).GetUserId(); + + // var result = new Response(); + // result.Result = _service.GetMalfunctionsOld(userid); + // return Ok(result); + // } + // catch (Exception ex) + // { + // return BadRequest(); + // } + //} + + /// + /// 取得設備狀態 + /// + /// + [HttpGet("")] + public IActionResult GetMalfunctions() + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var userid = new ParserForUserFromClaim(userIdentity).GetUserId(); + + var result = new Response(); + result.Result = _service.GetMalfunctions(userid); + return Ok(result); + } + catch (Exception ex) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/NotPunishController.cs b/Traffic.Api/Controllers/NotPunishController.cs new file mode 100644 index 0000000..c03bb4b --- /dev/null +++ b/Traffic.Api/Controllers/NotPunishController.cs @@ -0,0 +1,147 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + /// + /// 不開單原因設定 + /// + [Route("api/notPunish")] + [Authorize] + [ApiController] + public class NotPunishController : ControllerBase + { + private readonly INotPunishService _service; + + public NotPunishController(INotPunishService service) + { + _service = service; + } + + /// + /// 取得所有不開單原因 + /// + /// + [HttpGet("all")] + public IActionResult GetNotPunishs() + { + try + { + var result = new Response(); + result.Result = _service.GetNotPunishs(); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得不開單原因列表by條件 + /// + /// + /// + [HttpGet("")] + public IActionResult GetNotPunishs([FromQuery] SearchModelViewModel searchModel) + { + try + { + var result = new Response(); + var model = Util.GetSearchModel(searchModel); + result.Result = _service.GetNotPunishs(model); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得不開單原因 by id + /// + /// + /// + [HttpGet("{id}")] + public IActionResult GetNotPunish(int id) + { + try + { + var result = new Response(); + result.Result = _service.GetNotPunishById(id); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 新增不開單原因 + /// + /// + /// + [HttpPost("")] + public IActionResult InsertNotPunish(NotPunishViewModel vm) + { + try + { + var result = _service.InsertNotPunish(vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 修改不開單原因 + /// + /// 不開單原因的流水號 + /// + /// + [HttpPut("{id}")] + public IActionResult UpdateNotPunish(int id, NotPunishViewModel vm) + { + try + { + var result = _service.UpdatNotPunish(id, vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 刪除不開單原因 + /// + /// 不開單原因的流水號 + /// + [HttpDelete("{id}")] + public IActionResult DeleteNotPunish(int id) + { + try + { + var result = _service.DeleteNotPunish(id); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/PoliceStationController.cs b/Traffic.Api/Controllers/PoliceStationController.cs new file mode 100644 index 0000000..8773e3e --- /dev/null +++ b/Traffic.Api/Controllers/PoliceStationController.cs @@ -0,0 +1,145 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + [Route("api/group")] + [Authorize] + [ApiController] + public class PoliceStationController : ControllerBase + { + private readonly IPoliceStationService _service; + + public PoliceStationController(IPoliceStationService service) + { + _service = service; + } + + /// + /// 取得 PoliceStation 列表 + /// + /// + /// + [HttpGet("GetGroupDataList")] + public IActionResult GetPoliceStations([FromQuery] SearchModelViewModel searchModel) + { + try + { + var result = new Response(); + var model = new SearchModel + { + Term = searchModel.Term, + Page = Convert.ToInt32(string.IsNullOrWhiteSpace(searchModel.Page) ? "1" : searchModel.Page), + PageSize = Convert.ToInt32(string.IsNullOrWhiteSpace(searchModel.PageSize) ? "1" : searchModel.PageSize), + IsAsc = searchModel.IsAsc == "true" ? true : false, + Order = string.IsNullOrWhiteSpace(searchModel.Order) ? "id" : searchModel.Order, + }; + result.Result = _service.GetPoliceStations(model); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得 PoliceStation by id + /// + /// + /// + [HttpGet("GetGroupData/{id}")] + public IActionResult GetPoliceStation(int id) + { + try + { + var result = new Response(); + result.Result = _service.GetPoliceStationById(id); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + [HttpGet("GetGroupNameList")] + public IActionResult GetGroupNameList() + { + try + { + var result = new Response(); + result.Result = _service.GetGroupNameList(); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 新增 PoliceStation + /// + /// + /// + [HttpPost("PostGroupData")] + public IActionResult InsertPoliceStation(PoliceStationViewModel vm) + { + try + { + var result = _service.InsertPoliceStation(vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 修改 PoliceStation + /// + /// + /// + [HttpPut("PutGroupData")] + public IActionResult UpdatePoliceStation(PoliceStationViewModel vm) + { + try + { + var result = _service.UpdatPoliceStation(vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 刪除 PoliceStation + /// + /// PoliceStation 的流水號 + /// + [HttpDelete("DeleteGroupData/{id}")] + public IActionResult DeletePoliceStation(int id) + { + try + { + var result = _service.DeletePoliceStation(id); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/RepairController.cs b/Traffic.Api/Controllers/RepairController.cs new file mode 100644 index 0000000..1f350c1 --- /dev/null +++ b/Traffic.Api/Controllers/RepairController.cs @@ -0,0 +1,142 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class RepairController : ControllerBase + { + private readonly IRepairService _service; + + public RepairController(IRepairService service) + { + _service = service; + } + + /// + /// 取得所有線上報修 + /// + /// + [HttpGet("all")] + public IActionResult GetRepairs() + { + try + { + var result = new Response(); + result.Result = _service.GetRepairs(); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得線上報修列表by條件 + /// + /// + /// + [HttpGet("")] + public IActionResult GetRepairs([FromQuery] SearchModelViewModel searchModel) + { + try + { + var result = new Response(); + var model = Util.GetSearchModel(searchModel); + result.Result = _service.GetRepairs(model); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得線上報修by id + /// + /// + /// + [HttpGet("{id}")] + public IActionResult GetRepair(int id) + { + try + { + var result = new Response(); + result.Result = _service.GetRepairById(id); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 新增線上報修 + /// + /// + /// + [HttpPost("")] + public IActionResult InsertRepair(RepairViewModel vm) + { + try + { + var result = _service.InsertRepair(vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 修改線上報修 + /// + /// 線上報修的流水號 + /// + /// + [HttpPut("{id}")] + public IActionResult UpdateRepair(int id, RepairViewModel vm) + { + try + { + var result = _service.UpdatRepair(id, vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 刪除線上報修 + /// + /// 線上報修的流水號 + /// + [HttpDelete("{id}")] + public IActionResult DeleteRepair(int id) + { + try + { + var result = _service.DeleteRepair(id); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/ReportController.cs b/Traffic.Api/Controllers/ReportController.cs new file mode 100644 index 0000000..8560d1b --- /dev/null +++ b/Traffic.Api/Controllers/ReportController.cs @@ -0,0 +1,300 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + [Route("api/report")] + [Authorize] + [ApiController] + public class ReportController : ControllerBase + { + private readonly IFileService _fileService; + private readonly IReportService _service; + public ReportController(IFileService fileService, IReportService service) + { + _fileService = fileService; + _service = service; + } + + /// + /// 取得 API 資料顯示 的 TableName + /// + [HttpGet("tycg/tableName")] + public IActionResult GetTycgLog() + { + try + { + var data = _service.GetTycgTableName(); + var result = new Response + { + Result = data + }; + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + + /// + /// 取得 API 資料顯示 + /// + /// + /// + /// + /// + /// 需要給Table名稱 + /// tycg_logases + /// tycg_logbigcarviolation + /// tycg_logchecked + /// tycg_logcrossroad + /// tycg_logmalfunctionhttp + /// tycg_logrejected + /// tycg_logtraffichttp + /// tycg_loguploaded + [HttpGet("tycg")] + public IActionResult GetTycgLog(string tycgTableName, [FromQuery] SearchModelViewModel searchModel, string method = "0") + { + try + { + if (method == "1") + { + var data = _service.GetTycgLogAll(tycgTableName); + var url = _fileService.ExportGetTycgLog(tycgTableName, data); + return Ok(url); + } + else + { + SearchModel model = Util.GetSearchModel(searchModel); + var data = _service.GetTycgLog(tycgTableName, model); + + var result = new Response + { + Result = data + }; + return !string.IsNullOrWhiteSpace(tycgTableName) ? Ok(result) : BadRequest("請輸入 TableName"); + } + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 違規事件統計站店違規數統計表 + /// + /// + /// 0 : 查詢, 1:匯出 + /// + [HttpPost("site/eventTypes")] + public IActionResult GetEvent(SiteAndEventTypeViewModel viewModel, string method = "0") + { + try + { + var data = _service.GetReportSiteEventTypes(viewModel.Sites, viewModel.EventTypes, viewModel.StartTime, viewModel.EndTime); + + var result = new Response + { + Result = data + }; + + if (method == "1") + { + var start = viewModel.StartTime.Replace("undefined", "00:00:00"); + var end = viewModel.EndTime.Replace("undefined", "23:59:59"); + var url = _fileService.ExportGetSiteEvent( + Convert.ToDateTime(start).ToString("yyMMdd"), + Convert.ToDateTime(end).ToString("yyMMdd"), + data); + return Ok(url); + } + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 違規類型統計表 違規停車 + /// + /// + /// 0 : 查詢, 1:匯出 + /// + [HttpPost("eventType/1")] + public IActionResult GetEventType1(ReportRequestViewModel viewModel, string method = "0") + { + try + { + var data = _service.GetEventType1(viewModel); + var result = new Response + { + Result = data + }; + + if (method == "1") + { + var url = _fileService.ExportGetEventType1( + Convert.ToDateTime(viewModel.StartDate).ToString("yyMMdd"), + Convert.ToDateTime(viewModel.EndDate).ToString("yyMMdd"), + data); + return Ok(url); + } + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 違規類型統計表 區間測速 + /// + /// + /// 0 : 查詢, 1:匯出 + /// + [HttpPost("eventType/2")] + public IActionResult GetEventType2(ReportRequestViewModel viewModel, string method = "0") + { + try + { + var data = _service.GetEventType2(viewModel); + + var result = new Response + { + Result = data + }; + + if (method == "1") + { + var url = _fileService.ExportGetEventType2( + Convert.ToDateTime(viewModel.StartDate).ToString("yyMMdd"), + Convert.ToDateTime(viewModel.EndDate).ToString("yyMMdd"), + data); + return Ok(url); + } + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 違規類型統計表 未依標線行駛_路口淨空_闖紅燈 未保持路口淨空 + /// + /// + /// 0 : 查詢, 1:匯出 + /// + [HttpPost("eventType/34")] + public IActionResult GetEventType34(ReportRequestViewModel viewModel, string method = "0") + { + try + { + var data = _service.GetEventType34(viewModel); + + var result = new Response + { + Result = data + }; + + if (method == "1") + { + var url = _fileService.ExportGetEventType34( + Convert.ToDateTime(viewModel.StartDate).ToString("yyMMdd"), + Convert.ToDateTime(viewModel.EndDate).ToString("yyMMdd"), + data); + return Ok(url); + } + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 違規類型統計表 大貨車禁行 + /// + /// + /// 0 : 查詢, 1:匯出 + /// + [HttpPost("eventType/6")] + public IActionResult GetEventType6(ReportRequestViewModel viewModel, string method = "0") + { + try + { + var data = _service.GetEventType6(viewModel); + + var result = new Response + { + Result = data + }; + + if (method == "1") + { + var url = _fileService.ExportGetEventType6( + Convert.ToDateTime(viewModel.StartDate).ToString("yyMMdd"), + Convert.ToDateTime(viewModel.EndDate).ToString("yyMMdd"), + data); + return Ok(url); + } + + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 設備故障報表 + /// + /// + /// 0 : 查詢, 1:匯出 + /// + [HttpPost("malfunction")] + public IActionResult GetMalfunction(ReportRequestViewModel viewModel, string method = "0") + { + try + { + var data = _service.GetMalfunction(viewModel); + + var result = new Response + { + Result = data + }; + + if (method == "1") + { + var url = _fileService.ExportGetMalfunction( + Convert.ToDateTime(viewModel.StartDate).ToString("yyMMdd"), + Convert.ToDateTime(viewModel.EndDate).ToString("yyMMdd"), + data); + return Ok(url); + } + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/RoleController.cs b/Traffic.Api/Controllers/RoleController.cs new file mode 100644 index 0000000..9fa6115 --- /dev/null +++ b/Traffic.Api/Controllers/RoleController.cs @@ -0,0 +1,123 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + [Route("api/role")] + [Authorize] + [ApiController] + public class RoleController : ControllerBase + { + private readonly IRoleService _service; + + public RoleController(IRoleService service) + { + this._service = service; + } + + [HttpPost("PostRoleDataList")] + public IActionResult PostRoleDataList(RoleData roleData) + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var mID = new ParserForUserFromClaim(userIdentity).GetUserId(); + + return Ok(_service.PostRoleDataList(mID, roleData)); + } + catch (Exception) + { + return BadRequest(); + } + } + + [HttpGet("GetRoleDataList")] + public IActionResult GetRoleDataList([FromQuery] SearchModelViewModel searchModel) + { + try + { + var result = new Response(); + var model = new SearchModel + { + Term = searchModel.Term, + Page = Convert.ToInt32(string.IsNullOrWhiteSpace(searchModel.Page) ? "1" : searchModel.Page), + PageSize = Convert.ToInt32(string.IsNullOrWhiteSpace(searchModel.PageSize) ? "1" : searchModel.PageSize), + IsAsc = searchModel.IsAsc == "true" ? true : false, + Order = string.IsNullOrWhiteSpace(searchModel.Order) ? "id" : searchModel.Order, + }; + result.Result = _service.GetRoleDataList(model); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + [HttpGet("GetRoleInfoList")] + public IActionResult GetRoleInfoList() + { + try + { + var result = new Response(); + result.Result = _service.GetRoleInfoList(); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + [HttpGet("GetRolePermissionInfo/{id}")] + public IActionResult GetRolePermissionInfo(int? Id) + { + try + { + return Ok(new { Result = _service.GetRolePermissionInfo(Id) }); + } + catch (Exception) + { + return BadRequest(); + } + } + + [HttpGet("GetAllPagePermission/{id}")] + public IActionResult GetAllPagePermission(int id) + { + try + { + var re = new Response(); + re.Result = _service.GetAllPagePermission(id); + return Ok(re); + } + catch (Exception) + { + return BadRequest(); + } + } + + [HttpPut("PutPageRoleStatus")] + public IActionResult PutPageRoleStatus(PagePermissionData pagePermission) + { + try + { + return Ok(new { Result = _service.PutPageRoleStatus(pagePermission) }); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/SiteInformationController.cs b/Traffic.Api/Controllers/SiteInformationController.cs new file mode 100644 index 0000000..6a553b1 --- /dev/null +++ b/Traffic.Api/Controllers/SiteInformationController.cs @@ -0,0 +1,210 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + /// + /// 行政區管理 + /// + [Route("api/siteInformation")] + [Authorize] + [ApiController] + public class SiteInformationController : ControllerBase + { + private readonly ISiteInformationService _service; + + public SiteInformationController(ISiteInformationService service) + { + _service = service; + } + + /// + /// 取得所有行政區列表 by 員警 + /// + [HttpGet("user")] + public IActionResult GetSiteInformationsByUser() + { + try + { + var userIdentity = (ClaimsIdentity)User.Identity; + var userId = new ParserForUserFromClaim(userIdentity).GetUserId(); + + var result = new Response(); + result.Result = _service.GetSiteInformationsByUser(userId); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得所有行政區列表 + /// + [AllowAnonymous] + [HttpGet("emailNoNull")] + public IActionResult GetSiteInformationsEmailNoNull() + { + try + { + var result = new Response(); + result.Result = _service.GetSiteInformations().Where(i => !string.IsNullOrWhiteSpace(i.CompanyEmail)); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得所有行政區列表 + /// + [AllowAnonymous] + [HttpGet("all")] + public IActionResult GetSiteInformations() + { + try + { + var result = new Response(); + result.Result = _service.GetSiteInformations(); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得行政區列表 by EventType + /// + /// + /// + [HttpPost("eventType")] + public IActionResult GetSiteInformationsByEventTypes(List eventTypes) + { + try + { + var result = new Response + { + Result = _service.GetSiteInformationsByEventTypes(eventTypes) + }; + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得行政區列表 by 條件 + /// + /// + /// + [HttpGet("")] + public IActionResult GetSiteInformations([FromQuery] SearchModelViewModel searchModel) + { + try + { + var result = new Response(); + var model = Util.GetSearchModel(searchModel); + result.Result = _service.GetSiteInformations(model); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 取得行政區 by id + /// + /// + /// + [HttpGet("{id}")] + public IActionResult GetSiteInformation(int id) + { + try + { + var result = new Response(); + result.Result = _service.GetSiteInformationById(id); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 新增行政區 + /// + /// + /// + [HttpPost("")] + public IActionResult InsertSiteInformation(SiteInformationViewModel vm) + { + try + { + var result = _service.InsertSiteInformation(vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 修改行政區 + /// + /// 行政區的流水號 + /// + /// + [HttpPut("{id}")] + public IActionResult UpdateSiteInformation(int id, SiteInformationViewModel vm) + { + try + { + var result = _service.UpdatSiteInformation(id, vm); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + /// + /// 刪除行政區 + /// + /// 行政區的流水號 + /// + [HttpDelete("{id}")] + public IActionResult DeleteSiteInformation(int id) + { + try + { + var result = _service.DeleteSiteInformation(id); + return result.Success ? Ok(result) : BadRequest(result); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/Controllers/SystemController.cs b/Traffic.Api/Controllers/SystemController.cs new file mode 100644 index 0000000..7eb557c --- /dev/null +++ b/Traffic.Api/Controllers/SystemController.cs @@ -0,0 +1,87 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Api.Controllers +{ + [Route("api/system")] + [Authorize] + [ApiController] + public class SystemController : ControllerBase + { + private readonly IPageListService _service; + + public SystemController(IPageListService service) + { + this._service = service; + } + + [HttpGet("GetPageDataList")] + public IActionResult GetPageDataList([FromQuery] SearchModelViewModel searchModel) + { + try + { + var result = new Response(); + var model = new SearchModel + { + Term = searchModel.Term, + Page = Convert.ToInt32(string.IsNullOrWhiteSpace(searchModel.Page) ? "1" : searchModel.Page), + PageSize = Convert.ToInt32(string.IsNullOrWhiteSpace(searchModel.PageSize) ? "1" : searchModel.PageSize), + IsAsc = searchModel.IsAsc == "true" ? true : false, + Order = string.IsNullOrWhiteSpace(searchModel.Order) ? "id" : searchModel.Order + }; + result.Result = _service.GetPageDataList(model); + return Ok(result); + } + catch (Exception) + { + return BadRequest(); + } + } + + [HttpPost("PostPageListData")] + public IActionResult PostPageListData(PageData pageData) + { + try + { + return Ok(_service.PostPageDataList(pageData)); + } + catch (Exception) + { + return BadRequest(); + } + } + + [HttpPut("PutPageData")] + public IActionResult PutPageData(PageData pageData) + { + try + { + return Ok(_service.PutPageData(pageData)); + } + catch (Exception) + { + return BadRequest(); + } + } + + [HttpDelete("DeletePageData")] + public IActionResult DeletePageData(int id) + { + try + { + return Ok(_service.DeletePageData(id)); + } + catch (Exception) + { + return BadRequest(); + } + } + } +} diff --git a/Traffic.Api/NLog.config b/Traffic.Api/NLog.config new file mode 100644 index 0000000..fef54aa --- /dev/null +++ b/Traffic.Api/NLog.config @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Traffic.Api/Program.cs b/Traffic.Api/Program.cs new file mode 100644 index 0000000..5e0093a --- /dev/null +++ b/Traffic.Api/Program.cs @@ -0,0 +1,65 @@ +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using NLog.Web; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Traffic.Api +{ + public class Program + { + //Trace 0 LogTrace() Logs messages only for tracing purposes for the developers. + // Log q`Ω}oqA}oHˬdƨϥΡAi|]t@DZbKXӷPơAAX]ӥX{bҪ Log C (w]|X) + + //Debug 1 LogDebug() Logs messages for short-term debugging purposes. w]|X + // o Log OFbҰϥΡA`Ӷ}ҡAקK Log qӤjAϦӷ|yҪDC (w]|X) + + //Information 2 LogInformation() Logs messages for the flow of the application. + // ` Log ADnO{չB檺y{C + + //Warning 3 LogWarning() Logs messages for abnormal or unexpected events in the application flow. + // iw~Ϊ̮įणΪƥF藍|AF|nDC + + //Error 4 LogError() Logs error messages. + // Dw~Aӵoͦoo͡AӭnקKƵoͪ~ƥC + + //Critical 5 LogCritical() Logs failures messages that require immediate attention. + // unoʹNdzƨWҪ~ƥAҦp|ɭPҡAtαY쪺ƥC + public static void Main(string[] args) + { + // NLog: setup the logger first to catch all errors + var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); + try + { + logger.Debug("init main"); + BuildWebHost(args).Build().Run(); + } + catch (Exception ex) + { + //NLog: catch setup errors + logger.Error(ex, "Stopped program because of exception"); + throw; + } + finally + { + // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) + NLog.LogManager.Shutdown(); + } + } + + public static IWebHostBuilder BuildWebHost(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup() + .ConfigureLogging(logging => + { + logging.ClearProviders(); + logging.SetMinimumLevel(LogLevel.Trace); + }) + .UseNLog(); // NLog: setup NLog for Dependency injection + } +} diff --git a/Traffic.Api/Properties/PublishProfiles/FolderProfile.pubxml b/Traffic.Api/Properties/PublishProfiles/FolderProfile.pubxml new file mode 100644 index 0000000..040b013 --- /dev/null +++ b/Traffic.Api/Properties/PublishProfiles/FolderProfile.pubxml @@ -0,0 +1,16 @@ + + + + + False + False + True + Release + Any CPU + FileSystem + bin\Release\net5.0\publish\ + FileSystem + + \ No newline at end of file diff --git a/Traffic.Api/Properties/launchSettings.json b/Traffic.Api/Properties/launchSettings.json new file mode 100644 index 0000000..a2222d7 --- /dev/null +++ b/Traffic.Api/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:5301", + "sslPort": 44306 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "Traffic.Api": { + "commandName": "Project", + "dotnetRunMessages": "true", + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Traffic.Api/Startup.cs b/Traffic.Api/Startup.cs new file mode 100644 index 0000000..d1eadaa --- /dev/null +++ b/Traffic.Api/Startup.cs @@ -0,0 +1,192 @@ +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.HttpsPolicy; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.IdentityModel.Tokens; +using Microsoft.OpenApi.Models; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Filter; +using Traffic.Service.Helpers; +using Traffic.Service.Implements; +using Traffic.Service.Interfaces; + +namespace Traffic.Api +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddControllers(); + services.AddSingleton(); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + services.AddScoped(); + services.AddLogging(builder => + { + builder.AddConfiguration(Configuration.GetSection("Logging")) + .AddFilter("Microsoft", LogLevel.Warning) + .AddConsole() + .AddDebug(); + }); + SetCors(services); + + SetSwagger(services); + + SetJwtBearer(services); + } + + private static void SetCors(IServiceCollection services) + { + services.AddCors(o => o.AddPolicy("Traffic", builder => + { + builder.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + })); + } + + private static void SetJwtBearer(IServiceCollection services) + { + services + .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + // ҥѮɡA^Y|]t WWW-Authenticate YAo̷|ܥѪԲӿ~] + options.IncludeErrorDetails = true; // w]Ȭ trueAɷ|SO + + options.TokenValidationParameters = new TokenValidationParameters + { + // zLoŧiANiHq "sub" Ȩó]w User.Identity.Name + NameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", + // zLoŧiANiHq "roles" ȡAåi [Authorize] P_ + RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", + + // @ڭ̳| Issuer + ValidateIssuer = true, + ValidIssuer = "Traffic", + + // q`ӻݭn Audience + ValidateAudience = false, + //ValidAudience = "JwtAuthDemo", // ҴNݭng + + // @ڭ̳| Token Ĵ + ValidateLifetime = true, + + // pG Token ]t key ~ݭnҡA@볣uñӤw + ValidateIssuerSigningKey = false, + + // "1234567890123456" ӱq IConfiguration o + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("wgQWt6kNQR3dyYoCopq1")) + }; + }); + } + + private static void SetSwagger(IServiceCollection services) + { + services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", new OpenApiInfo { Title = "Traffic.Api", Version = "v1" }); + c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme + { + Description = $@"JWT Authorization header using the Bearer scheme. \r\n\r\n + Enter 'Bearer' [space] and then your token in the text input below. \r\n\r\n + Example: 'Bearer 12345abcdef'", + Name = "Authorization", + In = ParameterLocation.Header, + Type = SecuritySchemeType.ApiKey, + Scheme = "Bearer" + }); + + //Set the comments path for the Swagger JSON and UI. + + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); + + c.AddSecurityRequirement(new OpenApiSecurityRequirement() + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Bearer" + }, + Scheme = "oauth2", + Name = "Bearer", + In = ParameterLocation.Header, + }, + new List() + } + }); + }); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + + app.UseSwagger(); + app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Traffic.Api v1")); + } + + app.UseHttpsRedirection(); + + app.UseRouting(); + + app.UseCors("Traffic"); + + app.UseAuthentication();// + + app.UseAuthorization(); //Av + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git a/Traffic.Api/Traffic.Api.csproj b/Traffic.Api/Traffic.Api.csproj new file mode 100644 index 0000000..2c6b933 --- /dev/null +++ b/Traffic.Api/Traffic.Api.csproj @@ -0,0 +1,34 @@ + + + + net5.0 + + + + C:\Users\littlec315\Desktop\個人\專案\桃園違規開單系統\.net 5\Traffic\Traffic.Api\Traffic.Api.xml + 1701;1702;1591 + + + + + + + + + + + + + + + + + + + PreserveNewest + + + + + + diff --git a/Traffic.Api/Traffic.Api.xml b/Traffic.Api/Traffic.Api.xml new file mode 100644 index 0000000..4e9fb19 --- /dev/null +++ b/Traffic.Api/Traffic.Api.xml @@ -0,0 +1,22 @@ + + + + Traffic.Api + + + + + 新增使用者 + + + + + + + 登入 + + + + + + diff --git a/Traffic.Api/appsettings.Development.json b/Traffic.Api/appsettings.Development.json new file mode 100644 index 0000000..8983e0f --- /dev/null +++ b/Traffic.Api/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/Traffic.Api/appsettings.json b/Traffic.Api/appsettings.json new file mode 100644 index 0000000..0d2a6be --- /dev/null +++ b/Traffic.Api/appsettings.json @@ -0,0 +1,43 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Trace", + "Microsoft": "Trace" + } + }, + "ConnectionStrings": { + "DefaultConnection": "server=127.0.0.1;port=3306;user id=root;password=123456;database=traffic;charset=utf8;" + }, + "JwtSettings": { + "Issuer": "Traffic", + "SignKey": "wgQWt6kNQR3dyYoCopq1" + }, + "User": { + "LoginErrorCount": "3", + "AlarmChangePwdDay": "80", + "NeedChangePwdDay": "90" + }, + "EventStatus": { + "Count": "300", + "Cancel": "C:\\File\\Cancel\\", + "Upload": "C:\\uploadFile\\", + "ExportExcel": "C:\\localFile\\", + "ExportExcelUrl": "http://localhost/LocalFile/", + "ImagePath": "C:\\localFile\\Images\\", + "VideoPath": "C:\\localFile\\Videos\\" + }, + "Mode": { + "IsTest": "True" + }, + "Repair": { + "Email": "littlec315@gmail.com" + }, + "MailServer": { + "IsTest": "True", + "Host": "smtp.gmail.com", + "Port": 587, + "Account": "tycg@rage.com.tw", + "Password": "Traffic1118!@#$" + }, + "AllowedHosts": "*" +} diff --git a/Traffic.Data/Enums/Auth.cs b/Traffic.Data/Enums/Auth.cs new file mode 100644 index 0000000..6265b96 --- /dev/null +++ b/Traffic.Data/Enums/Auth.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Traffic.Data.Enums +{ + public enum Auth + { + Admin = 1, + User = 2, + } +} diff --git a/Traffic.Data/Enums/EnumVehicleType.cs b/Traffic.Data/Enums/EnumVehicleType.cs new file mode 100644 index 0000000..68f1d59 --- /dev/null +++ b/Traffic.Data/Enums/EnumVehicleType.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Enums +{ + public enum EnumVehicleType + { + [Description("兩輪車")] + Motorcycle = 1, + [Description("汽車")] + Car = 2, + [Description("大車")] + Cart = 3, + [Description("貨車")] + Truck = 4, + [Description("大卡車")] + BigTruck = 5, + [Description("大客車")] + Coach = 6, + [Description("堆高機")] + Stacker = 7, + [Description("水泥攪拌車")] + CementMixer = 8, + [Description("計程車")] + Taxi = 9, + [Description("人")] + people = 10, + [Description("其他")] + Other = -1, + } +} diff --git a/Traffic.Data/Enums/Message.cs b/Traffic.Data/Enums/Message.cs new file mode 100644 index 0000000..4a22f1c --- /dev/null +++ b/Traffic.Data/Enums/Message.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Threading.Tasks; + +namespace Traffic.Data.Enums +{ + public enum Message + { + [Description("取得成功")] + GetSuccess, + [Description("取得失敗")] + GetFail, + + [Description("新增成功。")] + InsertSuccess, + [Description("新增失敗。")] + InsertFail, + + [Description("修改成功。")] + UpdateSuccess, + [Description("修改失敗。")] + UpdateFail, + + [Description("刪除成功。")] + DeleteSuccess, + [Description("刪除失敗。")] + DeleteFail, + + [Description("註冊成功。")] + RegisterSuccess, + [Description("註冊失敗。")] + RegisterFail, + + [Description("Page Size 或 Page Number 需大於 0")] + PageMustBeGreaterThan0, + + [Description("查無此帳號,請重新選擇。")] + NoThisAccount, + [Description("已存在此帳號。")] + ThisAccountAlreadyExists, + [Description("請選擇身分別。")] + PleaseChooseRole, + [Description("不存在此權限, 請再確認一次。")] + ThisAccountNoAuth, + } +} diff --git a/Traffic.Data/Models/AccountGroup.cs b/Traffic.Data/Models/AccountGroup.cs new file mode 100644 index 0000000..94d2fb4 --- /dev/null +++ b/Traffic.Data/Models/AccountGroup.cs @@ -0,0 +1,15 @@ +using System; + +namespace Traffic.Data.Models +{ + public class AccountGroup + { + public int Id { get; set; } + + public string GroupName { get; set; } + + public string CreatorId { get; set; } + + public DateTime CreatedOn { get; set; } + } +} diff --git a/Traffic.Data/Models/AccountPwd.cs b/Traffic.Data/Models/AccountPwd.cs new file mode 100644 index 0000000..9f9cdfe --- /dev/null +++ b/Traffic.Data/Models/AccountPwd.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class AccountPwd + { + public int Id { get; set; } + + public string Account { get; set; } + + public string Password { get; set; } + + public DateTime CreatedOn { get; set; } + } +} diff --git a/Traffic.Data/Models/AccountRole.cs b/Traffic.Data/Models/AccountRole.cs new file mode 100644 index 0000000..985c350 --- /dev/null +++ b/Traffic.Data/Models/AccountRole.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; + +namespace Traffic.Data.Models +{ + public class AccountRole + { + public int Id { get; set; } + + public string RoleName { get; set; } + + public int CreatorId { get; set; } + + public DateTime CreatedOn { get; set; } + } +} diff --git a/Traffic.Data/Models/AccountUser.cs b/Traffic.Data/Models/AccountUser.cs new file mode 100644 index 0000000..26c8d8f --- /dev/null +++ b/Traffic.Data/Models/AccountUser.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class AccountUser + { + public int Id { get; set; } + + public string Account { get; set; } + + public string UserName { get; set; } + + public string Password { get; set; } + + public string Email { get; set; } + + public string PhoneNumber { get; set; } + + public int RoleCodeId { get; set; } + + public int PoliceStationId { get; set; } + + public int CreatorId { get; set; } + + public DateTime CreatedOn { get; set; } + + public int UpdatorId { get; set; } + + public DateTime UpdatedOn { get; set; } + + public int ErrorCount { get; set; } + + public DateTime ChangePwdOn { get; set; } + + public int Status { get; set; } + } +} diff --git a/Traffic.Data/Models/AccountUserSite.cs b/Traffic.Data/Models/AccountUserSite.cs new file mode 100644 index 0000000..00d2bad --- /dev/null +++ b/Traffic.Data/Models/AccountUserSite.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class AccountUserSite + { + /// + /// 流水號 + /// + public int Id { get; set; } + + /// + /// 違規代碼 + /// + public int UserId { get; set; } + + /// + /// 違規名稱 + /// + public int SiteId { get; set; } + } +} diff --git a/Traffic.Data/Models/Announce.cs b/Traffic.Data/Models/Announce.cs new file mode 100644 index 0000000..5e43b45 --- /dev/null +++ b/Traffic.Data/Models/Announce.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class Announce + { + /// + /// 流水號 + /// + public int Id { get; set; } + + /// + /// 標題 + /// + public string Title { get; set; } + + /// + /// 內文 + /// + public string Content { get; set; } + + /// + /// 起始時間 + /// + public DateTime StartOn { get; set; } + + /// + /// 狀態 + /// + public int Status { get; set; } + + public int CreatorId { get; set; } + + public DateTime CreatedOn { get; set; } + + public int UpdatorId { get; set; } + + public DateTime UpdatedOn { get; set; } + } +} diff --git a/Traffic.Data/Models/CompanyInformation.cs b/Traffic.Data/Models/CompanyInformation.cs new file mode 100644 index 0000000..67db337 --- /dev/null +++ b/Traffic.Data/Models/CompanyInformation.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class CompanyInformation + { + /// + /// 流水號 + /// + public int Id { get; set; } + + /// + /// 廠商代碼 + /// + public string CompanyCode { get; set; } + + /// + /// 廠商名稱 + /// + public string CompanyName { get; set; } + + /// + /// 廠商Email + /// + public string Email { get; set; } + } +} diff --git a/Traffic.Data/Models/Event.cs b/Traffic.Data/Models/Event.cs new file mode 100644 index 0000000..6f1d826 --- /dev/null +++ b/Traffic.Data/Models/Event.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class Event + { + public int Id { get; set; } + public string SiteID { get; set; } + public string EventID { get; set; } + public string Channel { get; set; } + public string Slot { get; set; } + public string Number { get; set; } + public string PlateNumber { get; set; } + public string EventType { get; set; } + public string VehicleType { get; set; } + public string Distance { get; set; } + public string Speed { get; set; } + public string TotalPassTime { get; set; } + public string LimitTon { get; set; } + public string Ton { get; set; } + public string InTime { get; set; } + public string AlarmTime { get; set; } + public string OutTime { get; set; } + public string LPRTime { get; set; } + public string IMGPath1 { get; set; } + public string IMGPath2 { get; set; } + public string IMGPath3 { get; set; } + public string IMGPath4 { get; set; } + public string IMGPath5 { get; set; } + public string IMGPath6 { get; set; } + public string VideoPath1 { get; set; } + public string VideoPath2 { get; set; } + public string IsStay { get; set; } + public string Unsure { get; set; } + public string CheckPunish { get; set; } + public string Punished { get; set; } + public string Rejected { get; set; } + public string CompanyCode { get; set; } + public string Ps { get; set; } + public string HandlingTime { get; set; } + public string UploadTime { get; set; } + public string Account { get; set; } + } + + public class JoinEventSite + { + public int Id { get; set; } + public string County { get; set; } + public string Area { get; set; } + public string SiteId { get; set; } + public string SiteName { get; set; } + public string EventType { get; set; } + public string VehicleType { get; set; } + public string Laws { get; set; } + public string SiteID { get; set; } + public string EventID { get; set; } + public string Channel { get; set; } + public string Slot { get; set; } + public string Number { get; set; } + public string PlateNumber { get; set; } + public string Distance { get; set; } + public string Speed { get; set; } + public string TotalPassTime { get; set; } + public string LimitTon { get; set; } + public string Ton { get; set; } + public string InTime { get; set; } + public string AlarmTime { get; set; } + public string OutTime { get; set; } + public string LPRTime { get; set; } + public string IMGPath1 { get; set; } + public string IMGPath2 { get; set; } + public string IMGPath3 { get; set; } + public string IMGPath4 { get; set; } + public string IMGPath5 { get; set; } + public string IMGPath6 { get; set; } + public string VideoPath1 { get; set; } + public string VideoPath2 { get; set; } + public string IsStay { get; set; } + public string Unsure { get; set; } + public string CheckPunish { get; set; } + public string Punished { get; set; } + public string Rejected { get; set; } + public string CompanyCode { get; set; } + public string Ps { get; set; } + public string HandlingTime { get; set; } + public string UploadTime { get; set; } + public string Account { get; set; } + } + + public class JoinEventSiteAndUser + { + public int Id { get; set; } + public string UserID { get; set; } + public string County { get; set; } + public string Area { get; set; } + public string SiteId { get; set; } + public string SiteName { get; set; } + public string EventType { get; set; } + public string VehicleType { get; set; } + public string Laws { get; set; } + public string SiteID { get; set; } + public string EventID { get; set; } + public string Channel { get; set; } + public string Slot { get; set; } + public string Number { get; set; } + public string PlateNumber { get; set; } + public string Distance { get; set; } + public string Speed { get; set; } + public string TotalPassTime { get; set; } + public string LimitTon { get; set; } + public string Ton { get; set; } + public string InTime { get; set; } + public string AlarmTime { get; set; } + public string OutTime { get; set; } + public string LPRTime { get; set; } + public string IMGPath1 { get; set; } + public string IMGPath2 { get; set; } + public string IMGPath3 { get; set; } + public string IMGPath4 { get; set; } + public string IMGPath5 { get; set; } + public string IMGPath6 { get; set; } + public string VideoPath1 { get; set; } + public string VideoPath2 { get; set; } + public string IsStay { get; set; } + public string Unsure { get; set; } + public string CheckPunish { get; set; } + public string Punished { get; set; } + public string Rejected { get; set; } + public string CompanyCode { get; set; } + public string Ps { get; set; } + public string HandlingTime { get; set; } + public string UploadTime { get; set; } + public string Account { get; set; } + } +} diff --git a/Traffic.Data/Models/EventType.cs b/Traffic.Data/Models/EventType.cs new file mode 100644 index 0000000..c6a1bc3 --- /dev/null +++ b/Traffic.Data/Models/EventType.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class EventTypeData + { + /// + /// 流水號 + /// + public int Id { get; set; } + + /// + /// 違規代碼 + /// + public string EventType { get; set; } + + /// + /// 違規名稱 + /// + public string EventName { get; set; } + } +} diff --git a/Traffic.Data/Models/ExceptionNumber.cs b/Traffic.Data/Models/ExceptionNumber.cs new file mode 100644 index 0000000..c5b6e59 --- /dev/null +++ b/Traffic.Data/Models/ExceptionNumber.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class ExceptionNumber + { + public int Id { get; set; } + + public string Number { get; set; } + + public string Date { get; set; } + } +} diff --git a/Traffic.Data/Models/JoinRolePageInfo.cs b/Traffic.Data/Models/JoinRolePageInfo.cs new file mode 100644 index 0000000..55fc9ce --- /dev/null +++ b/Traffic.Data/Models/JoinRolePageInfo.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class JoinRolePageInfo + { + public int RoleId { get; set; } + + public int PageId { get; set; } + + public string RoleName { get; set; } + + public string PageName { get; set; } + } +} diff --git a/Traffic.Data/Models/JoinRolePageList.cs b/Traffic.Data/Models/JoinRolePageList.cs new file mode 100644 index 0000000..cc85bc7 --- /dev/null +++ b/Traffic.Data/Models/JoinRolePageList.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class JoinRolePageList + { + public int? RoleId { get; set; } + + public int PageId { get; set; } + + public string PageModule { get; set; } + + public string PageName { get; set; } + + public string PageURL { get; set; } + } +} diff --git a/Traffic.Data/Models/Log_Mapping.cs b/Traffic.Data/Models/Log_Mapping.cs new file mode 100644 index 0000000..447d1eb --- /dev/null +++ b/Traffic.Data/Models/Log_Mapping.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class Log_Mapping + { + public int Id { get; set; } + public string LogName { get; set; } + public string APIName { get; set; } + } +} diff --git a/Traffic.Data/Models/Malfunction.cs b/Traffic.Data/Models/Malfunction.cs new file mode 100644 index 0000000..f585410 --- /dev/null +++ b/Traffic.Data/Models/Malfunction.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class Malfunction + { + public int UserId { get; set; } + public string County { get; set; } + public string Area { get; set; } + public string Siteid { get; set; } + public string SiteName { get; set; } + public string EventType { get; set; } + public string CompanyCode { get; set; } + public string DeviceType { get; set; } + public string DeviceID { get; set; } + public string Message { get; set; } + public int Timestamp { get; set; } + } +} diff --git a/Traffic.Data/Models/NotPunish.cs b/Traffic.Data/Models/NotPunish.cs new file mode 100644 index 0000000..321078e --- /dev/null +++ b/Traffic.Data/Models/NotPunish.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class NotPunish + { + public int Id { get; set; } + + public int EventTypeId { get; set; } + + public int NotPunishType { get; set; } + + public string NotPunishReason { get; set; } + } +} diff --git a/Traffic.Data/Models/PageList.cs b/Traffic.Data/Models/PageList.cs new file mode 100644 index 0000000..2aa01a9 --- /dev/null +++ b/Traffic.Data/Models/PageList.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class PageList + { + public int Id { get; set; } + + public string PageModule { get; set; } + + public string PageName { get; set; } + + public string PageURL { get; set; } + } +} diff --git a/Traffic.Data/Models/PoliceStation.cs b/Traffic.Data/Models/PoliceStation.cs new file mode 100644 index 0000000..787b356 --- /dev/null +++ b/Traffic.Data/Models/PoliceStation.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class PoliceStation + { + public int Id { get; set; } + public string Area { get; set; } + public string StationName { get; set; } + } +} diff --git a/Traffic.Data/Models/Repair.cs b/Traffic.Data/Models/Repair.cs new file mode 100644 index 0000000..80a3f2b --- /dev/null +++ b/Traffic.Data/Models/Repair.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class Repair + { + public int Id { get; set; } + public int QuestionType { get; set; } + public string SendTo { get; set; } + public string Title { get; set; } + public string Content { get; set; } + } +} diff --git a/Traffic.Data/Models/RolePage.cs b/Traffic.Data/Models/RolePage.cs new file mode 100644 index 0000000..0fdae92 --- /dev/null +++ b/Traffic.Data/Models/RolePage.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class RolePage + { + public int Id { get; set; } + + public int RoleId { get; set; } + + public int PageId { get; set; } + } +} diff --git a/Traffic.Data/Models/SiteInformation.cs b/Traffic.Data/Models/SiteInformation.cs new file mode 100644 index 0000000..31d7797 --- /dev/null +++ b/Traffic.Data/Models/SiteInformation.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class SiteInformation + { + public int Id { get; set; } + public string County { get; set; } + public string Area { get; set; } + public string SiteID { get; set; } + public string SiteName { get; set; } + public string EventType { get; set; } + public string Ip { get; set; } + public string DbName { get; set; } + public string TableName { get; set; } + public string User { get; set; } + public string Password { get; set; } + public int FinalRecord { get; set; } + public string Target { get; set; } + public string ClusterHead { get; set; } + public int ARHFinalRecord { get; set; } + public string Laws { get; set; } + public string CompanyCode { get; set; } + + } +} diff --git a/Traffic.Data/Models/Tycg.cs b/Traffic.Data/Models/Tycg.cs new file mode 100644 index 0000000..4185f74 --- /dev/null +++ b/Traffic.Data/Models/Tycg.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class Tycg + { + public int Id { get; set; } + public Int64 Timestamp { get; set; } + public int Trendflags { get; set; } + public int Status { get; set; } + public string Value { get; set; } + public string Trendflags_Tag { get; set; } + public string Status_tag { get; set; } + } +} diff --git a/Traffic.Data/Models/UserLoginLog.cs b/Traffic.Data/Models/UserLoginLog.cs new file mode 100644 index 0000000..00699e8 --- /dev/null +++ b/Traffic.Data/Models/UserLoginLog.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class UserLoginLog + { + public int Id { get; set; } + public int UserId { get; set; } + public string LoginIP { get; set; } + public DateTime LoginOn { get; set; } + public int Status { get; set; } + } +} diff --git a/Traffic.Data/Models/VehicleType.cs b/Traffic.Data/Models/VehicleType.cs new file mode 100644 index 0000000..271e5ee --- /dev/null +++ b/Traffic.Data/Models/VehicleType.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class VehicleTypeTable + { + /// + /// 流水號 + /// + public int Id { get; set; } + + /// + /// 車型代碼 + /// + public string VehicleType { get; set; } + + /// + /// 車型名稱 + /// + public string VehicleName { get; set; } + } +} diff --git a/Traffic.Data/Traffic.Data.csproj b/Traffic.Data/Traffic.Data.csproj new file mode 100644 index 0000000..f208d30 --- /dev/null +++ b/Traffic.Data/Traffic.Data.csproj @@ -0,0 +1,7 @@ + + + + net5.0 + + + diff --git a/Traffic.Data/ViewModels/AccountUpdatePasswordViewModel.cs b/Traffic.Data/ViewModels/AccountUpdatePasswordViewModel.cs new file mode 100644 index 0000000..6836a62 --- /dev/null +++ b/Traffic.Data/ViewModels/AccountUpdatePasswordViewModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class AccountUpdatePasswordViewModel + { + [Required(ErrorMessage = "您必須輸入舊密碼")] + public string OldPassword { get; set; } + + [MinLength(8, ErrorMessage = "請輸入至少8個字元")] + [Required(ErrorMessage = "您必須輸入新密碼")] + public string NewPassword { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/AccountUserSiteViewModel.cs b/Traffic.Data/ViewModels/AccountUserSiteViewModel.cs new file mode 100644 index 0000000..e9318b3 --- /dev/null +++ b/Traffic.Data/ViewModels/AccountUserSiteViewModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class UserSiteViewModel + { + /// + /// 流水號 + /// + [JsonPropertyName("Id")] + public int Id { get; set; } + + /// + /// 違規名稱 + /// + [JsonPropertyName("SiteId")] + public string SiteId { get; set; } + + /// + /// 違規名稱 + /// + [JsonPropertyName("SiteName")] + public string SiteName { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/AccountUserViewModel.cs b/Traffic.Data/ViewModels/AccountUserViewModel.cs new file mode 100644 index 0000000..0c03236 --- /dev/null +++ b/Traffic.Data/ViewModels/AccountUserViewModel.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class AccountUserViewModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + + [JsonPropertyName("Account")] + public string Account { get; set; } + + [JsonPropertyName("Name")] + public string Name { get; set; } + + [JsonPropertyName("Email")] + public string Email { get; set; } + + [JsonPropertyName("Phone")] + public string Phone { get; set; } + + [JsonPropertyName("Role")] + public int Role { get; set; } + [JsonPropertyName("ErrorCount")] + public int ErrorCount { get; set; } + + [JsonPropertyName("PoliceStation")] + public PoliceStationViewModel PoliceStation { get; set; } + + [JsonPropertyName("Site")] + public List Site { get; set; } + + [JsonPropertyName("ChangePwdOn")] + public DateTime ChangePwdOn { get; set; } + + [JsonPropertyName("Status")] + public int Status { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/AnnounceInsertViewModel.cs b/Traffic.Data/ViewModels/AnnounceInsertViewModel.cs new file mode 100644 index 0000000..b5a3294 --- /dev/null +++ b/Traffic.Data/ViewModels/AnnounceInsertViewModel.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class AnnounceInsertViewModel + { + /// + /// 標題 + /// + [JsonPropertyName("Title")] + public string Title { get; set; } + + /// + /// 內文 + /// + [JsonPropertyName("Content")] + public string Content { get; set; } + + /// + /// 起始時間 + /// + [JsonPropertyName("StartOn")] + public string StartOn { get; set; } + + /// + /// 狀態 + /// + [JsonPropertyName("Status")] + public int Status { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/AnnounceViewModel.cs b/Traffic.Data/ViewModels/AnnounceViewModel.cs new file mode 100644 index 0000000..77b3c94 --- /dev/null +++ b/Traffic.Data/ViewModels/AnnounceViewModel.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class AnnounceViewModel + { + /// + /// 流水號 + /// + [JsonPropertyName("Id")] + public int Id { get; set; } + + /// + /// 標題 + /// + [JsonPropertyName("Title")] + public string Title { get; set; } + + /// + /// 內文 + /// + [JsonPropertyName("Content")] + public string Content { get; set; } + + /// + /// 起始時間 + /// + [JsonPropertyName("StartOn")] + public string StartOn { get; set; } + + /// + /// 狀態 + /// + [JsonPropertyName("Status")] + public int Status { get; set; } + + [JsonPropertyName("CreatorId")] + public int CreatorId { get; set; } + + [JsonPropertyName("CreatedOn")] + public DateTime CreatedOn { get; set; } + + [JsonPropertyName("UpdatorId")] + public int UpdatorId { get; set; } + + [JsonPropertyName("UpdatedOn")] + public DateTime UpdatedOn { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/CompanyInformationViewModel.cs b/Traffic.Data/ViewModels/CompanyInformationViewModel.cs new file mode 100644 index 0000000..a27aa13 --- /dev/null +++ b/Traffic.Data/ViewModels/CompanyInformationViewModel.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class CompanyInformationViewModel + { + /// + /// 廠商代碼 + /// + [JsonPropertyName("Id")] + public int Id { get; set; } + + /// + /// 廠商代碼 + /// + [JsonPropertyName("CompanyCode")] + public string CompanyCode { get; set; } + + /// + /// 廠商名稱 + /// + [JsonPropertyName("CompanyName")] + public string CompanyName { get; set; } + + /// + /// 廠商Email + /// + [JsonPropertyName("Email")] + public string Email { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/EachSiteEventTypesViewModel.cs b/Traffic.Data/ViewModels/EachSiteEventTypesViewModel.cs new file mode 100644 index 0000000..a083d14 --- /dev/null +++ b/Traffic.Data/ViewModels/EachSiteEventTypesViewModel.cs @@ -0,0 +1,130 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace Traffic.Service.Interfaces +{ + public class ReportSiteEventTypesViewModel + { + public List EachSiteEventTypesViewModel { get; set; } + public List EachEventTypesSiteViewModel { get; set; } + } + + public class EachSiteEventTypesViewModel + { + ///// + ///// 流水號 + ///// + //[JsonPropertyName("Id")] + //public int Id { get; set; } + /// + /// 站點 + /// + [JsonPropertyName("SiteId")] + public string SiteId { get; set; } + + /// + /// 站點名稱 + /// + [JsonPropertyName("SiteName")] + public string SiteName { get; set; } + + /// + /// 違規總數 + /// + [JsonPropertyName("EventTotalCount")] + public int EventTotalCount { get; set; } + + /// + /// 未舉發數量 + /// + [JsonPropertyName("NoStatusCount")] + public int NoStatusCount { get; set; } + + /// + /// 已舉發數量 + /// + [JsonPropertyName("CheckPunishCount")] + public int CheckPunishCount { get; set; } + + /// + /// 不開單數量 + /// + [JsonPropertyName("NoPunishCount")] + public int NoPunishCount { get; set; } + + ///// + ///// 取消開單數量 + ///// + //[JsonPropertyName("CancelPunishCount")] + //public int CancelPunishCount { get; set; } + + /// + /// 被駁回數量 + /// + [JsonPropertyName("RejectedCount")] + public int RejectedCount { get; set; } + + /// + /// 已開單數量 + /// + [JsonPropertyName("PunishCount")] + public int PunishCount { get; set; } + } + + public class EachEventTypesSiteViewModel + { + ///// + ///// 流水號 + ///// + //[JsonPropertyName("Id")] + //public int Id { get; set; } + + /// + /// EventName + /// + [JsonPropertyName("EventName")] + public string EventName { get; set; } + + /// + /// 違規總數 + /// + [JsonPropertyName("EventTotalCount")] + public int EventTotalCount { get; set; } + + /// + /// 未舉發數量 + /// + [JsonPropertyName("NoStatusCount")] + public int NoStatusCount { get; set; } + + /// + /// 已舉發數量 + /// + [JsonPropertyName("CheckPunishCount")] + public int CheckPunishCount { get; set; } + + /// + /// 不開單數量 + /// + [JsonPropertyName("NoPunishCount")] + public int NoPunishCount { get; set; } + + ///// + ///// 取消開單數量 + ///// + //[JsonPropertyName("CancelPunishCount")] + //public int CancelPunishCount { get; set; } + + /// + /// 被駁回數量 + /// + [JsonPropertyName("RejectedCount")] + public int RejectedCount { get; set; } + + /// + /// 已開單數量 + /// + [JsonPropertyName("PunishCount")] + public int PunishCount { get; set; } + } +} \ No newline at end of file diff --git a/Traffic.Data/ViewModels/EventCountViewModel.cs b/Traffic.Data/ViewModels/EventCountViewModel.cs new file mode 100644 index 0000000..022dccc --- /dev/null +++ b/Traffic.Data/ViewModels/EventCountViewModel.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class EventCountViewModel + { + /// + /// 流水號 + /// + [JsonPropertyName("TotalCount")] + public int TotalCount { get; set; } + + /// + /// 確認開單 + /// + [JsonPropertyName("PunishedCount")] + public int PunishedCount { get; set; } + + /// + /// 待確認開單 + /// + [JsonPropertyName("CheckPunishedCount")] + public int CheckPunishedCount { get; set; } + + /// + /// IsStayCount + /// + [JsonPropertyName("IsStayCount")] + public int IsStayCount { get; set; } + + /// + /// UnsureCount + /// + [JsonPropertyName("UnsureCount")] + public int UnsureCount { get; set; } + + /// + /// 駁回 + /// + [JsonPropertyName("RejectedCount")] + public int RejectedCount { get; set; } + + /// + /// 未開單 + /// + [JsonPropertyName("NoStatusCount")] + public int NoStatusCount { get; set; } + + /// + /// 不開單 + /// + [JsonPropertyName("NoPunishedCount")] + public int NoPunishedCount { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/EventTypeViewModel.cs b/Traffic.Data/ViewModels/EventTypeViewModel.cs new file mode 100644 index 0000000..25e6715 --- /dev/null +++ b/Traffic.Data/ViewModels/EventTypeViewModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class EventTypeViewModel + { + /// + /// 流水號 + /// + [JsonPropertyName("Id")] + public int Id { get; set; } + + /// + /// 違規代碼 + /// + [JsonPropertyName("EventType")] + public string EventType { get; set; } + + /// + /// 違規名稱 + /// + [JsonPropertyName("EventName")] + public string EventName { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/EventViewModel.cs b/Traffic.Data/ViewModels/EventViewModel.cs new file mode 100644 index 0000000..e2bf18c --- /dev/null +++ b/Traffic.Data/ViewModels/EventViewModel.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class EventViewModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("SiteID")] + public string SiteID { get; set; } + [JsonPropertyName("EventID")] + public string EventID { get; set; } + [JsonPropertyName("Channel")] + public string Channel { get; set; } + [JsonPropertyName("Slot")] + public string Slot { get; set; } + [JsonPropertyName("Number")] + public string Number { get; set; } + [JsonPropertyName("PlateNumber")] + public string PlateNumber { get; set; } + [JsonPropertyName("EventType")] + public string EventType { get; set; } + [JsonPropertyName("VehicleType")] + public string VehicleType { get; set; } + [JsonPropertyName("VehicleName")] + public string VehicleName { get; set; } + [JsonPropertyName("Distance")] + public string Distance { get; set; } + [JsonPropertyName("Speed")] + public string Speed { get; set; } + [JsonPropertyName("TotalPassTime")] + public string TotalPassTime { get; set; } + [JsonPropertyName("LimitTon")] + public string LimitTon { get; set; } + [JsonPropertyName("Ton")] + public string Ton { get; set; } + [JsonPropertyName("InTime")] + public string InTime { get; set; } + [JsonPropertyName("AlarmTime")] + public string AlarmTime { get; set; } + [JsonPropertyName("OutTime")] + public string OutTime { get; set; } + [JsonPropertyName("LPRTime")] + public string LPRTime { get; set; } + [JsonPropertyName("IMGPath1")] + public string IMGPath1 { get; set; } + [JsonPropertyName("IMGPath2")] + public string IMGPath2 { get; set; } + [JsonPropertyName("IMGPath3")] + public string IMGPath3 { get; set; } + [JsonPropertyName("IMGPath4")] + public string IMGPath4 { get; set; } + [JsonPropertyName("IMGPath5")] + public string IMGPath5 { get; set; } + [JsonPropertyName("IMGPath6")] + public string IMGPath6 { get; set; } + [JsonPropertyName("VideoPath1")] + public string VideoPath1 { get; set; } + [JsonPropertyName("VideoPath2")] + public string VideoPath2 { get; set; } + [JsonPropertyName("IsStay")] + public string IsStay { get; set; } + [JsonPropertyName("Unsure")] + public string Unsure { get; set; } + [JsonPropertyName("CheckPunish")] + public string CheckPunish { get; set; } + [JsonPropertyName("Punished")] + public string Punished { get; set; } + [JsonPropertyName("CompanyCode")] + public string CompanyCode { get; set; } + [JsonPropertyName("Ps")] + public string Ps { get; set; } + [JsonPropertyName("HandlingTime")] + public string HandlingTime { get; set; } + [JsonPropertyName("UploadTime")] + public string UploadTime { get; set; } + [JsonPropertyName("Rejected")] + public string Rejected { get; set; } + [JsonPropertyName("Account")] + public string Account { get; set; } + } + + public class EventSearchByNumberViewModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("Number")] + public string Number { get; set; } + [JsonPropertyName("SiteName")] + public string SiteName { get; set; } + [JsonPropertyName("EventName")] + public string EventName { get; set; } + [JsonPropertyName("InTime")] + public string InTime { get; set; } + [JsonPropertyName("Status")] + public string Status { get; set; } + } + + public class JoinEventSiteAndUserViewModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("UserID")] + public string UserID { get; set; } + [JsonPropertyName("County")] + public string County { get; set; } + [JsonPropertyName("Area")] + public string Area { get; set; } + [JsonPropertyName("SiteId")] + public string SiteId { get; set; } + [JsonPropertyName("SiteName")] + public string SiteName { get; set; } + [JsonPropertyName("EventName")] + public string EventName { get; set; } + [JsonPropertyName("VehicleName")] + public string VehicleName { get; set; } + [JsonPropertyName("Laws")] + public List Laws { get; set; } + [JsonPropertyName("EventID")] + public string EventID { get; set; } + [JsonPropertyName("Channel")] + public string Channel { get; set; } + [JsonPropertyName("Slot")] + public string Slot { get; set; } + [JsonPropertyName("Number")] + public string Number { get; set; } + //[JsonPropertyName("PlateNumber")] + //public string PlateNumber { get; set; } + [JsonPropertyName("EventType")] + public string EventType { get; set; } + [JsonPropertyName("VehicleType")] + public string VehicleType { get; set; } + [JsonPropertyName("Distance")] + public string Distance { get; set; } + [JsonPropertyName("Speed")] + public string Speed { get; set; } + [JsonPropertyName("TotalPassTime")] + public string TotalPassTime { get; set; } + [JsonPropertyName("LimitTon")] + public string LimitTon { get; set; } + [JsonPropertyName("Ton")] + public string Ton { get; set; } + [JsonPropertyName("InTime")] + public string InTime { get; set; } + [JsonPropertyName("AlarmTime")] + public string AlarmTime { get; set; } + [JsonPropertyName("OutTime")] + public string OutTime { get; set; } + [JsonPropertyName("LPRTime")] + public string LPRTime { get; set; } + [JsonPropertyName("IMGPath1")] + public string IMGPath1 { get; set; } + //[JsonPropertyName("IMGPath2")] + //public string IMGPath2 { get; set; } + //[JsonPropertyName("IMGPath3")] + //public string IMGPath3 { get; set; } + //[JsonPropertyName("IMGPath4")] + //public string IMGPath4 { get; set; } + //[JsonPropertyName("IMGPath5")] + //public string IMGPath5 { get; set; } + //[JsonPropertyName("IMGPath6")] + //public string IMGPath6 { get; set; } + [JsonPropertyName("IMGList")] + public List IMGList { get; set; } + [JsonPropertyName("VideoPath1")] + public string VideoPath1 { get; set; } + //[JsonPropertyName("VideoPath2")] + //public string VideoPath2 { get; set; } + [JsonPropertyName("Video")] + public List VideoList { get; set; } + [JsonPropertyName("IsStay")] + public string IsStay { get; set; } + [JsonPropertyName("Unsure")] + public string Unsure { get; set; } + [JsonPropertyName("CheckPunish")] + public string CheckPunish { get; set; } + [JsonPropertyName("Punished")] + public string Punished { get; set; } + [JsonPropertyName("CompanyCode")] + public string CompanyCode { get; set; } + [JsonPropertyName("Rejected")] + public string Rejected { get; set; } + [JsonPropertyName("Status")] + public string Status { get; set; } + [JsonPropertyName("Ps")] + public string Ps { get; set; } + [JsonPropertyName("HandlingTime")] + public string HandlingTime { get; set; } + [JsonPropertyName("UploadTime")] + public string UploadTime { get; set; } + [JsonPropertyName("Account")] + public string Account { get; set; } + } + + public class LawsCodes + { + public string LawsCode { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/JsonCancelEvent.cs b/Traffic.Data/ViewModels/JsonCancelEvent.cs new file mode 100644 index 0000000..5affa47 --- /dev/null +++ b/Traffic.Data/ViewModels/JsonCancelEvent.cs @@ -0,0 +1,45 @@ +using System.Text.Json.Serialization; + +namespace Traffic.Data.ViewModels +{ + public class JsonCancelEvent + { + // "area":"中壢區", + //"handlingTime":"2021-11-17 09:23:26", + //"eventID":"20211117205715785", + //"policeID":"取消開單測試", + //"vehicleName":"汽車", + //"organization":"中壢分局", + //"county":"桃園市", + //"siteName":"中壢火車站-計程車下客區", + //"eventName":"違規停車", + //"action":"取消開單", + //"plate":"APP-0215", + //"sn":"1309697" + + [JsonPropertyName("area")] + public string area { get; set; } + [JsonPropertyName("handlingTime")] + public string handlingTime { get; set; } + [JsonPropertyName("eventID")] + public string eventID { get; set; } + [JsonPropertyName("policeID")] + public string policeID { get; set; } + [JsonPropertyName("vehicleName")] + public string vehicleName { get; set; } + [JsonPropertyName("organization")] + public string organization { get; set; } + [JsonPropertyName("county")] + public string county { get; set; } + [JsonPropertyName("siteName")] + public string siteName { get; set; } + [JsonPropertyName("eventName")] + public string eventName { get; set; } + [JsonPropertyName("action")] + public string action { get; set; } + [JsonPropertyName("plate")] + public string plate { get; set; } + [JsonPropertyName("sn")] + public string sn { get; set; } + } +} \ No newline at end of file diff --git a/Traffic.Data/ViewModels/JsonCheckPunish.cs b/Traffic.Data/ViewModels/JsonCheckPunish.cs new file mode 100644 index 0000000..e0843f9 --- /dev/null +++ b/Traffic.Data/ViewModels/JsonCheckPunish.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class JsonCheckPunish + { + [JsonPropertyName("area")] + public string area { get; set; } + [JsonPropertyName("handlingTime")] + public string handlingTime { get; set; } + [JsonPropertyName("eventID")] + public string eventID { get; set; } + [JsonPropertyName("policeID")] + public string policeID { get; set; } + [JsonPropertyName("vehicleName")] + public string vehicleName { get; set; } + [JsonPropertyName("images")] + public List images { get; set; } + + + [JsonPropertyName("county")] + public string county { get; set; } + [JsonPropertyName("siteName")] + public string siteName { get; set; } + [JsonPropertyName("plate")] + public string plate { get; set; } + [JsonPropertyName("organization")] + public string organization { get; set; } + [JsonPropertyName("eventName")] + public string eventName { get; set; } + [JsonPropertyName("sn")] + public string sn { get; set; } + [JsonPropertyName("punishID")] + public string punishID { get; set; } + } + public class JsonCheckPunishEventType1 : JsonCheckPunish + { + [JsonPropertyName("alarmTime")] + public string alarmTime { get; set; } + [JsonPropertyName("inTime")] + public string inTime { get; set; } + [JsonPropertyName("outTime")] + public string outTime { get; set; } + } + + public class JsonCheckPunishEventType2 : JsonCheckPunish + { + [JsonPropertyName("distance")] + public string distance { get; set; } + [JsonPropertyName("speed")] + public string speed { get; set; } + [JsonPropertyName("totalPassTime")] + public string totalPassTime { get; set; } + [JsonPropertyName("inTime")] + public string inTime { get; set; } + [JsonPropertyName("outTime")] + public string outTime { get; set; } + } + + public class JsonCheckPunishEventType3 : JsonCheckPunish + { + [JsonPropertyName("alarmTime")] + public string alarmTime { get; set; } + } + + public class JsonCheckPunishEventType4 : JsonCheckPunish + { + [JsonPropertyName("alarmTime")] + public string alarmTime { get; set; } + } + + public class JsonCheckPunishEventType6 : JsonCheckPunish + { + [JsonPropertyName("alarmTime")] + public string alarmTime { get; set; } + [JsonPropertyName("ton")] + public string ton { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/LoginResultModel.cs b/Traffic.Data/ViewModels/LoginResultModel.cs new file mode 100644 index 0000000..8d69e59 --- /dev/null +++ b/Traffic.Data/ViewModels/LoginResultModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class LoginResultModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + + [JsonPropertyName("Name")] + public string Name { get; set; } + + [JsonPropertyName("Role")] + public int Role { get; set; } + + [JsonPropertyName("Token")] + public string Token { get; set; } + + [JsonPropertyName("Message")] + public string Message { get; set; } + + [JsonPropertyName("Success")] + public bool Success { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/LoginViewModel.cs b/Traffic.Data/ViewModels/LoginViewModel.cs new file mode 100644 index 0000000..1f6d2ed --- /dev/null +++ b/Traffic.Data/ViewModels/LoginViewModel.cs @@ -0,0 +1,13 @@ +using System.Text.Json.Serialization; + +namespace Traffic.Data.ViewModels +{ + public class LoginViewModel + { + [JsonPropertyName("Account")] + public string Account { get; set; } + + [JsonPropertyName("Password")] + public string Password { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/MailViewModel.cs b/Traffic.Data/ViewModels/MailViewModel.cs new file mode 100644 index 0000000..b9ffc2f --- /dev/null +++ b/Traffic.Data/ViewModels/MailViewModel.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class MailViewModel + { + /// + /// 寄件者 + /// + public string From { get; set; } + + /// + /// 收件者 + /// + public string[] To { get; set; } + + /// + /// 主旨 + /// + public string Subject { get; set; } + + /// + /// 主旨 Encoding (System.Text.Encoding.UTF8) + /// + public Encoding SubjectEncoding { get; set; } + + /// + /// 內文 + /// + public string Body { get; set; } + + /// + /// 內文是否為Html + /// + public bool IsBodyHtml { get; set; } + + /// + /// 內文 Encoding (System.Text.Encoding.UTF8) + /// + public Encoding BodyEncoding { get; set; } + + /// + /// 郵件的優先度 + /// + public MailPriority Priority { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/MalfunctionViewModel.cs b/Traffic.Data/ViewModels/MalfunctionViewModel.cs new file mode 100644 index 0000000..eba4e09 --- /dev/null +++ b/Traffic.Data/ViewModels/MalfunctionViewModel.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class MalfunctionViewModel + { + [JsonPropertyName("userId")] + public int UserId { get; set; } + [JsonPropertyName("Siteid")] + public string Siteid { get; set; } + [JsonPropertyName("CompanyCode")] + public string CompanyCode { get; set; } + [JsonPropertyName("DeviceType")] + public string DeviceType { get; set; } + [JsonPropertyName("DeviceID")] + public string DeviceID { get; set; } + [JsonPropertyName("Message")] + public string Message { get; set; } + [JsonPropertyName("Time")] + public string Time { get; set; } + [JsonPropertyName("Status")] + public string Status { get; set; } + } + + public class SiteMalfunctionViewModel + { + [JsonPropertyName("userId")] + public int UserId { get; set; } + [JsonPropertyName("County")] + public string County { get; set; } + [JsonPropertyName("Area")] + public string Area { get; set; } + [JsonPropertyName("Siteid")] + public string Siteid { get; set; } + [JsonPropertyName("SiteName")] + public string SiteName { get; set; } + [JsonPropertyName("SiteStatus")] + public string SiteStatus { get; set; } + [JsonPropertyName("EventType")] + public string EventType { get; set; } + [JsonPropertyName("Malfunction")] + public List Malfunctions { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/NotPunishViewModel.cs b/Traffic.Data/ViewModels/NotPunishViewModel.cs new file mode 100644 index 0000000..1c42798 --- /dev/null +++ b/Traffic.Data/ViewModels/NotPunishViewModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class NotPunishViewModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + + [JsonPropertyName("EventTypeId")] + public int EventTypeId { get; set; } + + [JsonPropertyName("EventType")] + public string EventType { get; set; } + + [JsonPropertyName("EventName")] + public string EventName { get; set; } + + [JsonPropertyName("NotPunishType")] + public int NotPunishType { get; set; } + + [JsonPropertyName("NotPunishReason")] + public string NotPunishReason { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/PageData.cs b/Traffic.Data/ViewModels/PageData.cs new file mode 100644 index 0000000..1da2528 --- /dev/null +++ b/Traffic.Data/ViewModels/PageData.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class PageData + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("PageModule")] + public string PageModule { get; set; } + [JsonPropertyName("PageName")] + public string PageName { get; set; } + [JsonPropertyName("PageUrl")] + public string PageUrl { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/PageViewModel.cs b/Traffic.Data/ViewModels/PageViewModel.cs new file mode 100644 index 0000000..df3dbf3 --- /dev/null +++ b/Traffic.Data/ViewModels/PageViewModel.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class PageViewModel + { + + [JsonPropertyName("RowCount")] + public int RowCount { get; set; } + + [JsonPropertyName("PageCount")] + public int PageCount { get; set; } + + [JsonPropertyName("CurrentPage")] + public int CurrentPage { get; set; } + + [JsonPropertyName("Data")] + public T Data { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/PoliceStationViewModel.cs b/Traffic.Data/ViewModels/PoliceStationViewModel.cs new file mode 100644 index 0000000..b6151cf --- /dev/null +++ b/Traffic.Data/ViewModels/PoliceStationViewModel.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class PoliceStationViewModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + + [JsonPropertyName("Area")] + public string Area { get; set; } + + [JsonPropertyName("StationName")] + public string StationName { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/RepairViewModel.cs b/Traffic.Data/ViewModels/RepairViewModel.cs new file mode 100644 index 0000000..2a65a89 --- /dev/null +++ b/Traffic.Data/ViewModels/RepairViewModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class RepairViewModel + { + public int QuestionType { get; set; } + public string SendTo { get; set; } + public string Title { get; set; } + public string Content { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/ReportMalfunctionViewModel.cs b/Traffic.Data/ViewModels/ReportMalfunctionViewModel.cs new file mode 100644 index 0000000..7668681 --- /dev/null +++ b/Traffic.Data/ViewModels/ReportMalfunctionViewModel.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class ReportMalfunctionViewModel + { + [JsonPropertyName("Time")] + public string Time { get; set; } + [JsonPropertyName("SiteId")] + public string SiteId { get; set; } + [JsonPropertyName("SiteName")] + public string SiteName { get; set; } + [JsonPropertyName("CompanyCode")] + public string CompanyCode { get; set; } + [JsonPropertyName("DeviceType")] + public string DeviceType { get; set; } + [JsonPropertyName("DeviceID")] + public string DeviceID { get; set; } + [JsonPropertyName("Message")] + public string Message { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/ReportRequestViewModel.cs b/Traffic.Data/ViewModels/ReportRequestViewModel.cs new file mode 100644 index 0000000..ab544b8 --- /dev/null +++ b/Traffic.Data/ViewModels/ReportRequestViewModel.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class ReportRequestViewModel + { + [JsonPropertyName("StartDate")] + public string StartDate { get; set; } + + [JsonPropertyName("EndDate")] + public string EndDate { get; set; } + + [JsonPropertyName("StartTime")] + public int StartTime { get; set; } + + [JsonPropertyName("EndTime")] + public int EndTime { get; set; } + + [JsonPropertyName("Sites")] + public List Sites { get; set; } + } + + public class ReportEventType1ViewModel + { + /// + /// 違規時間 + /// + [JsonPropertyName("DateTime")] + public string DateTime { get; set; } + + /// + /// 汽車 + /// + [JsonPropertyName("CarCount")] + public int CarCount { get; set; } + + /// + /// 機車 + /// + [JsonPropertyName("MotorcycleCount")] + public int MotorcycleCount { get; set; } + + /// + /// 計程車 + /// + [JsonPropertyName("TaxiCount")] + public int TaxiCount { get; set; } + + /// + /// 公車 + /// + [JsonPropertyName("BusCount")] + public int BusCount { get; set; } + + /// + /// 有車牌 + /// + [JsonPropertyName("HasNumber")] + public int HasNumber { get; set; } + + /// + /// 無車牌 + /// + [JsonPropertyName("HasNoNumber")] + public int HasNoNumber { get; set; } + } + + public class ReportEventType2ViewModel + { + /// + /// 時速 + /// + [JsonPropertyName("Speed")] + public string Speed { get; set; } + + /// + /// 違規數量 + /// + [JsonPropertyName("Count")] + public int Count { get; set; } + } + + + public class ReportEventType34ViewModel + { + /// + /// 汽車 + /// + [JsonPropertyName("CarCount")] + public int CarCount { get; set; } + + /// + /// 貨車 + /// + [JsonPropertyName("TruckCount")] + public int TruckCount { get; set; } + + /// + /// 大客車 + /// + [JsonPropertyName("CoachCount")] + public int CoachCount { get; set; } + } + + public class ReportEventType6ViewModel + { + /// + /// 噸數 + /// + [JsonPropertyName("Ton")] + public string Ton { get; set; } + + /// + /// 違規數量 + /// + [JsonPropertyName("Count")] + public int Count { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/Response.cs b/Traffic.Data/ViewModels/Response.cs new file mode 100644 index 0000000..d0bf81d --- /dev/null +++ b/Traffic.Data/ViewModels/Response.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class Response + { + [JsonPropertyName("Result")] + public object Result { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/RoleData.cs b/Traffic.Data/ViewModels/RoleData.cs new file mode 100644 index 0000000..8996b5a --- /dev/null +++ b/Traffic.Data/ViewModels/RoleData.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class RoleData + { + [JsonPropertyName("Id")] + public int Id { get; set; } + + [JsonPropertyName("RoleName")] + public string RoleName { get; set; } + + [JsonPropertyName("Status")] + public bool Status { get; set; } + + [JsonPropertyName("CreatorId")] + public string CreatorId { get; set; } + + [JsonPropertyName("CreatedOn")] + public DateTime CreatedOn { get; set; } + } + + public class RoleDataQuery + { + [JsonPropertyName("Id")] + public int Id { get; set; } + + [JsonPropertyName("RoleName")] + public string RoleName { get; set; } + + [JsonPropertyName("Status")] + public bool Status { get; set; } + + [JsonPropertyName("CreateID")] + public int CreateID { get; set; } + + [JsonPropertyName("CreateTime")] + public string CreateTime { get; set; } + } + + public class RoleCodeInfo + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("RoleName")] + public string RoleName { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/RolePermissionData.cs b/Traffic.Data/ViewModels/RolePermissionData.cs new file mode 100644 index 0000000..e2e68e4 --- /dev/null +++ b/Traffic.Data/ViewModels/RolePermissionData.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.Models +{ + public class RolePermissionData + { + [JsonPropertyName("Id")] + public int Id { get; set; } + + [JsonPropertyName("RoleCodeId")] + public int RoleCodeId { get; set; } + + [JsonPropertyName("PageId")] + public int PageId { get; set; } + } + + public class RolePermissionDataQuery + { + [JsonPropertyName("Id")] + public int Id { get; set; } + + [JsonPropertyName("RoleId")] + public int RoleId { get; set; } + + [JsonPropertyName("PageId")] + public int PageId { get; set; } + + [JsonPropertyName("RoleName")] + public string RoleName { get; set; } + + [JsonPropertyName("PageName")] + public string PageName { get; set; } + } + + public class PagePermissionData + { + [JsonPropertyName("Enable")] + public bool Enable { get; set; } + + [JsonPropertyName("RoleId")] + public int RoleId { get; set; } + + [JsonPropertyName("PageId")] + public int PageId { get; set; } + + } + + public class PagePermissionDataQuery + { + [JsonPropertyName("Enable")] + public bool Enable { get; set; } + + [JsonPropertyName("RoleId")] + public int RoleId { get; set; } + + [JsonPropertyName("PageId")] + public int PageId { get; set; } + + [JsonPropertyName("PageModule")] + public string PageModule { get; set; } + + [JsonPropertyName("PageName")] + public string PageName { get; set; } + + [JsonPropertyName("PageUrl")] + public string PageUrl { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/SearchModel.cs b/Traffic.Data/ViewModels/SearchModel.cs new file mode 100644 index 0000000..f06b1ea --- /dev/null +++ b/Traffic.Data/ViewModels/SearchModel.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class SearchModel + { + [JsonPropertyName("Term")] + public string Term { get; set; } + [JsonPropertyName("Page")] + public int Page { get; set; } + [JsonPropertyName("PageSize")] + public int PageSize { get; set; } + [JsonPropertyName("Order")] + public string Order { get; set; } + [JsonPropertyName("IsAsc")] + public bool IsAsc { get; set; } + + public SearchModel() + { + Page = 1; + PageSize = 10; + Order = "id"; + IsAsc = true; + } + } +} diff --git a/Traffic.Data/ViewModels/SearchModelViewModel.cs b/Traffic.Data/ViewModels/SearchModelViewModel.cs new file mode 100644 index 0000000..2d5425e --- /dev/null +++ b/Traffic.Data/ViewModels/SearchModelViewModel.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class SearchModelViewModel + { + [JsonPropertyName("Term")] + public string Term { get; set; } + [JsonPropertyName("Page")] + public string Page { get; set; } + [JsonPropertyName("PageSize")] + public string PageSize { get; set; } + [JsonPropertyName("Order")] + public string Order { get; set; } + [JsonPropertyName("IsAsc")] + public string IsAsc { get; set; } + + public SearchModelViewModel() + { + Page = "1"; + PageSize = "10"; + Order = "id"; + IsAsc = "true"; + } + } +} diff --git a/Traffic.Data/ViewModels/SiteAndEventTypeViewModel.cs b/Traffic.Data/ViewModels/SiteAndEventTypeViewModel.cs new file mode 100644 index 0000000..1a181c2 --- /dev/null +++ b/Traffic.Data/ViewModels/SiteAndEventTypeViewModel.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class SiteAndEventTypeViewModel + { + [JsonPropertyName("StartTime")] + public string StartTime { get; set; } + [JsonPropertyName("EndTime")] + public string EndTime { get; set; } + [JsonPropertyName("Sites")] + public List Sites { get; set; } + [JsonPropertyName("EventTypes")] + public List EventTypes { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/SiteInformationViewModel.cs b/Traffic.Data/ViewModels/SiteInformationViewModel.cs new file mode 100644 index 0000000..8be8df2 --- /dev/null +++ b/Traffic.Data/ViewModels/SiteInformationViewModel.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class SiteInformationViewModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("Country")] + public string County { get; set; } + [JsonPropertyName("Area")] + public string Area { get; set; } + [JsonPropertyName("SiteID")] + public string SiteID { get; set; } + [JsonPropertyName("SiteName")] + public string SiteName { get; set; } + [JsonPropertyName("EventType")] + public string EventType { get; set; } + [JsonPropertyName("EventName")] + public string EventName { get; set; } + [JsonPropertyName("Ip")] + public string Ip { get; set; } + [JsonPropertyName("DbName")] + public string DbName { get; set; } + [JsonPropertyName("TableName")] + public string TableName { get; set; } + [JsonPropertyName("User")] + public string User { get; set; } + [JsonPropertyName("Password")] + public string Password { get; set; } + [JsonPropertyName("FinalRecord")] + public int FinalRecord { get; set; } + [JsonPropertyName("Target")] + public string Target { get; set; } + [JsonPropertyName("ClusterHead")] + public string ClusterHead { get; set; } + [JsonPropertyName("ARHFinalRecord")] + public int ARHFinalRecord { get; set; } + [JsonPropertyName("Laws")] + public string Laws { get; set; } + [JsonPropertyName("CompanyCode")] + public string CompanyCode { get; set; } + [JsonPropertyName("CompanyName")] + public string CompanyName { get; set; } + [JsonPropertyName("CompanyEmail")] + public string CompanyEmail { get; set; } + } + + public class UserSiteInformationViewModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("Country")] + public string County { get; set; } + [JsonPropertyName("Area")] + public string Area { get; set; } + [JsonPropertyName("SiteID")] + public string SiteID { get; set; } + [JsonPropertyName("SiteName")] + public string SiteName { get; set; } + [JsonPropertyName("EventType")] + public string EventType { get; set; } + [JsonPropertyName("EventName")] + public string EventName { get; set; } + [JsonPropertyName("CompanyCode")] + public string CompanyCode { get; set; } + [JsonPropertyName("CompanyName")] + public string CompanyName { get; set; } + [JsonPropertyName("CompanyEmail")] + public string CompanyEmail { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/SmtpClientViewModel.cs b/Traffic.Data/ViewModels/SmtpClientViewModel.cs new file mode 100644 index 0000000..7d9f59c --- /dev/null +++ b/Traffic.Data/ViewModels/SmtpClientViewModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Mail.ViewModels +{ + public class SmtpClientViewModel + { + public string Account { get; set; } + public string Password { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/TradeResultModel.cs b/Traffic.Data/ViewModels/TradeResultModel.cs new file mode 100644 index 0000000..7aeea50 --- /dev/null +++ b/Traffic.Data/ViewModels/TradeResultModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class TradeResultModel + { + [JsonPropertyName("Success")] + public bool Success { get; set; } + [JsonPropertyName("Message")] + public string Message { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/TycgViewModel.cs b/Traffic.Data/ViewModels/TycgViewModel.cs new file mode 100644 index 0000000..4f036cf --- /dev/null +++ b/Traffic.Data/ViewModels/TycgViewModel.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class TycgViewModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("Time")] + public string Time { get; set; } + [JsonPropertyName("Timestamp")] + public Int64 Timestamp { get; set; } + [JsonPropertyName("Trendflags")] + public int Trendflags { get; set; } + [JsonPropertyName("Status")] + public int Status { get; set; } + [JsonPropertyName("Value")] + public string Value { get; set; } + [JsonPropertyName("ip")] + public string ip { get; set; } + [JsonPropertyName("api")] + public string api { get; set; } + [JsonPropertyName("Trendflags_Tag")] + public string Trendflags_Tag { get; set; } + [JsonPropertyName("Status_tag")] + public string Status_tag { get; set; } + } + + public class TycgTableNameViewModel + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("LogName")] + public string LogName { get; set; } + [JsonPropertyName("APIName")] + public string APIName { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/UserData.cs b/Traffic.Data/ViewModels/UserData.cs new file mode 100644 index 0000000..2252233 --- /dev/null +++ b/Traffic.Data/ViewModels/UserData.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Data.ViewModels +{ + public class UserData + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("Account")] + public string Account { get; set; } + [JsonPropertyName("UserName")] + public string UserName { get; set; } + [JsonPropertyName("Password")] + public string Password { get; set; } + [JsonPropertyName("newPassword")] + public string NewPassword { get; set; } + [JsonPropertyName("Email")] + public string Email { get; set; } + [JsonPropertyName("PhoneNumber")] + public string PhoneNumber { get; set; } + [JsonPropertyName("Status")] + public int Status { get; set; } + [JsonPropertyName("RoleCode")] + public AccountRole RoleCode { get; set; } + [JsonPropertyName("RoleCode_Id")] + public int RoleCode_Id { get; set; } + [JsonPropertyName("GroupCode")] + public AccountGroup GroupCode { get; set; } + [JsonPropertyName("GroupCode_Id")] + public int GroupCode_Id { get; set; } + + [JsonPropertyName("Site_Id")] + public List Site_Id { get; set; } + } + + public class UserNameList + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("UserName")] + public string UserName { get; set; } + [JsonPropertyName("Email")] + public string Email { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/UserDataQuery.cs b/Traffic.Data/ViewModels/UserDataQuery.cs new file mode 100644 index 0000000..642a76c --- /dev/null +++ b/Traffic.Data/ViewModels/UserDataQuery.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Data.ViewModels +{ + public class UserDataQuery + { + [JsonPropertyName("Id")] + public int Id { get; set; } + [JsonPropertyName("Account")] + public string Account { get; set; } + [JsonPropertyName("UserName")] + public string UserName { get; set; } + [JsonPropertyName("Email")] + public string Email { get; set; } + [JsonPropertyName("PhoneNumber")] + public string PhoneNumber { get; set; } + [JsonPropertyName("Status")] + public int Status { get; set; } + [JsonPropertyName("RoleCode")] + public AccountRole RoleCode { get; set; } + [JsonPropertyName("RoleCode_Id")] + public int RoleCode_Id { get; set; } + [JsonPropertyName("GroupCode")] + public AccountGroup GroupCode { get; set; } + [JsonPropertyName("GroupCode_Id")] + public int GroupCode_Id { get; set; } + [JsonPropertyName("IsLogon")] + public bool? IsLogon { get; set; } + [JsonPropertyName("CreatorId")] + public string CreatorId { get; set; } + [JsonPropertyName("CreatedOn")] + public string CreatedOn { get; set; } + + [JsonPropertyName("PoliceStation")] + public PoliceStationViewModel PoliceStation { get; set; } + + [JsonPropertyName("Site")] + public List Site { get; set; } + } +} diff --git a/Traffic.Data/ViewModels/VehicleTypeViewModel.cs b/Traffic.Data/ViewModels/VehicleTypeViewModel.cs new file mode 100644 index 0000000..4a97f1b --- /dev/null +++ b/Traffic.Data/ViewModels/VehicleTypeViewModel.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Data.ViewModels +{ + public class VehicleTypeViewModel + { + /// + /// 流水號 + /// + public int Id { get; set; } + + /// + /// 違規代碼 + /// + public string VehicleType { get; set; } + + /// + /// 違規名稱 + /// + public string VehicleName { get; set; } + } +} diff --git a/Traffic.Repository/Implements/AccountRepository.cs b/Traffic.Repository/Implements/AccountRepository.cs new file mode 100644 index 0000000..01cc3dd --- /dev/null +++ b/Traffic.Repository/Implements/AccountRepository.cs @@ -0,0 +1,263 @@ +using Dapper; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class AccountRepository : IAccountRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public AccountRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public IEnumerable GetAccountUsers() + { + var sql = $@"SELECT * FROM {nameof(AccountUser)}"; + + return Connection.Query(sql, null, Transaction); + } + + public AccountUser GetAccountUserByAccount(string account) + { + var sql = $@"SELECT * FROM {nameof(AccountUser)} + WHERE {nameof(AccountUser.Account)} = @{nameof(AccountUser.Account)}"; + + return Connection.QueryFirstOrDefault(sql, new { Account = account }, Transaction); + } + + public AccountUser GetAccountUserByAccount(string account, string password) + { + var sql = $@"SELECT * FROM {nameof(AccountUser)} + WHERE {nameof(AccountUser.Account)} = @{nameof(AccountUser.Account)} + AND {nameof(AccountUser.Password)} = @{nameof(AccountUser.Password)}"; + + return Connection.QueryFirstOrDefault(sql, new { Account = account, Password = password }, Transaction); + } + + public AccountUser GetAccountUserById(int id) + { + var sql = $@"SELECT * FROM {nameof(AccountUser)} + WHERE {nameof(AccountUser.Id)} = @{nameof(AccountUser.Id)}"; + + return Connection.QueryFirstOrDefault(sql, new { Id = id }, Transaction); + } + + public IEnumerable GetAccountRoles() + { + var sql = $@"SELECT * FROM {nameof(AccountRole)}"; + + return Connection.Query(sql, null, Transaction); + } + + public IEnumerable GetAccountUserSite(int id) + { + var sql = $@"SELECT * FROM {nameof(AccountUserSite)} + WHERE {nameof(AccountUserSite.UserId)} = @{nameof(AccountUserSite.UserId)}"; + + return Connection.Query(sql, new { UserId = id }, Transaction); + } + + public IEnumerable GetAccountUserSites() + { + var sql = $@"SELECT * FROM {nameof(AccountUserSite)}"; + + return Connection.Query(sql, null, Transaction); + } + + public int InsertAccountUser(AccountUser accountUser) + { + var sql = $@"INSERT INTO {nameof(AccountUser)} ( + {nameof(AccountUser.Account)}, + {nameof(AccountUser.Password)}, + {nameof(AccountUser.UserName)}, + {nameof(AccountUser.PhoneNumber)}, + {nameof(AccountUser.Email)}, + {nameof(AccountUser.RoleCodeId)}, + {nameof(AccountUser.PoliceStationId)}, + {nameof(AccountUser.CreatorId)}, + {nameof(AccountUser.CreatedOn)}, + {nameof(AccountUser.ChangePwdOn)}) + VALUES (@{nameof(AccountUser.Account)}, + @{nameof(AccountUser.Password)}, + @{nameof(AccountUser.UserName)}, + @{nameof(AccountUser.PhoneNumber)}, + @{nameof(AccountUser.Email)}, + @{nameof(AccountUser.RoleCodeId)}, + @{nameof(AccountUser.PoliceStationId)}, + @{nameof(AccountUser.CreatorId)}, + @{nameof(AccountUser.CreatedOn)}, + @{nameof(AccountUser.ChangePwdOn)}); + SELECT LAST_INSERT_ID() AS `User_id`;"; + return Connection.QuerySingle(sql, accountUser, Transaction); + } + + public int InsertAccountRole(AccountRole accountUser) + { + var sql = $@"INSERT INTO {nameof(AccountRole)} ( + {nameof(AccountRole.RoleName)}, + {nameof(AccountRole.CreatorId)}, + {nameof(AccountRole.CreatedOn)}) + VALUES (@{nameof(AccountRole.RoleName)}, + @{nameof(AccountRole.CreatorId)}, + @{nameof(AccountRole.CreatedOn)}); + SELECT LAST_INSERT_ID() AS `User_id`;"; + return Connection.QuerySingle(sql, accountUser, Transaction); + } + + public bool InsertAccountUserSite(List userSite) + { + var sql = $@"INSERT INTO {nameof(AccountUserSite)} ( + {nameof(AccountUserSite.UserId)}, + {nameof(AccountUserSite.SiteId)}) + VALUES (@{nameof(AccountUserSite.UserId)}, + @{nameof(AccountUserSite.SiteId)})"; + + var result = Connection.Execute(sql, userSite, Transaction); + return result >= 1; + } + + public bool UpdateAccountUserbyAdmin(AccountUser accountUser) + { + var sql = $@"UPDATE {nameof(AccountUser)} + SET {nameof(AccountUser.Account)}=@{nameof(AccountUser.Account)}, + {nameof(AccountUser.UserName)}=@{nameof(AccountUser.UserName)}, + {nameof(AccountUser.PhoneNumber)}=@{nameof(AccountUser.PhoneNumber)}, + {nameof(AccountUser.Email)}=@{nameof(AccountUser.Email)}, + {nameof(AccountUser.RoleCodeId)}=@{nameof(AccountUser.RoleCodeId)}, + {nameof(AccountUser.PoliceStationId)}=@{nameof(AccountUser.PoliceStationId)}, + {nameof(AccountUser.UpdatorId)}=@{nameof(AccountUser.UpdatorId)}, + {nameof(AccountUser.UpdatedOn)}=@{nameof(AccountUser.UpdatedOn)} + WHERE {nameof(AccountUser.Id)} = @{nameof(AccountUser.Id)}"; + + var result = Connection.Execute(sql, accountUser, Transaction); + return result == 1; + } + + public bool UpdateAccountUserPasswordByAdmin(int id, string newPassword, int byWho, DateTime updateOn) + { + var sql = $@"UPDATE {nameof(AccountUser)} + SET {nameof(AccountUser.Password)}=@newPassword, + {nameof(AccountUser.UpdatorId)}=@{nameof(AccountUser.UpdatorId)}, + {nameof(AccountUser.UpdatedOn)}=@{nameof(AccountUser.UpdatedOn)}, + {nameof(AccountUser.ChangePwdOn)}=@{nameof(AccountUser.UpdatedOn)}, + {nameof(AccountUser.ErrorCount)}=0 + WHERE {nameof(AccountUser.Id)} = @{nameof(AccountUser.Id)}"; + + var result = Connection.Execute(sql, new { Id = id, newPassword, UpdatorId = byWho, UpdatedOn = updateOn }, Transaction); + return result == 1; + } + + public bool UpdateAccountUserbyUser(AccountUser accountUser) + { + var sql = $@"UPDATE {nameof(AccountUser)} + SET {nameof(AccountUser.UserName)}=@{nameof(AccountUser.UserName)}, + {nameof(AccountUser.PhoneNumber)}=@{nameof(AccountUser.PhoneNumber)}, + {nameof(AccountUser.Email)}=@{nameof(AccountUser.Email)}, + {nameof(AccountUser.UpdatorId)}=@{nameof(AccountUser.UpdatorId)}, + {nameof(AccountUser.UpdatedOn)}=@{nameof(AccountUser.UpdatedOn)} + WHERE {nameof(AccountUser.Id)} = @{nameof(AccountUser.Id)}"; + + var result = Connection.Execute(sql, accountUser, Transaction); + return result == 1; + } + + public bool UpdateAccountUserPasswordByUser(int id, string oldPassword, string newPassword, DateTime updatedOn) + { + var sql = $@"UPDATE {nameof(AccountUser)} + SET {nameof(AccountUser.Password)}=@newPassword, + {nameof(AccountUser.UpdatorId)}=@{nameof(AccountUser.UpdatorId)}, + {nameof(AccountUser.UpdatedOn)}=@{nameof(AccountUser.UpdatedOn)}, + {nameof(AccountUser.ChangePwdOn)}=@{nameof(AccountUser.UpdatedOn)}, + {nameof(AccountUser.ErrorCount)}=0 + WHERE {nameof(AccountUser.Password)} = @oldPassword And {nameof(AccountUser.Id)} = @{nameof(AccountUser.Id)}"; + + var result = Connection.Execute(sql, new { Id = id, oldPassword, newPassword, UpdatorId = id, UpdatedOn = updatedOn }, Transaction); + return result == 1; + } + + public bool InsertUserLoginLog(UserLoginLog userLogin) + { + var sql = $@"INSERT INTO {nameof(UserLoginLog)} ( + {nameof(UserLoginLog.UserId)}, + {nameof(UserLoginLog.LoginIP)}, + {nameof(UserLoginLog.LoginOn)}, + {nameof(UserLoginLog.Status)}) + VALUES (@{nameof(UserLoginLog.UserId)}, + @{nameof(UserLoginLog.LoginIP)}, + @{nameof(UserLoginLog.LoginOn)}, + @{nameof(UserLoginLog.Status)})"; + + var result = Connection.Execute(sql, userLogin, Transaction); + return result == 1; + } + + public bool UpdateUserErrorCount(int id, int errorCount) + { + var sql = $@"UPDATE {nameof(AccountUser)} + SET {nameof(AccountUser.ErrorCount)}=@{nameof(AccountUser.ErrorCount)} + WHERE {nameof(AccountUser.Id)} = @{nameof(AccountUser.Id)}"; + + var result = Connection.Execute(sql, new { id, errorCount }, Transaction); + return result == 1; + } + + public bool DisableUser(int byWho, int id, int status) + { + var sql = $@"UPDATE {nameof(AccountUser)} + SET {nameof(AccountUser.Status)} = @{nameof(status)}, + {nameof(AccountUser.UpdatorId)} = @{nameof(byWho)}, + {nameof(AccountUser.UpdatedOn)} = NOW() + WHERE {nameof(AccountUser.Id)} = @{nameof(id)}"; + + var result = Connection.Execute(sql, new { byWho, id, status }, Transaction); + return result == 1; + } + + public bool DeleteUser(int id) + { + var sql = $@"DELETE FROM {nameof(AccountUser)} WHERE {nameof(AccountUser.Id)} = @{nameof(AccountUser.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + + public bool DeleteUserSite(int userId) + { + var sql = $@"DELETE FROM {nameof(AccountUserSite)} WHERE {nameof(AccountUserSite.UserId)} = @{nameof(AccountUserSite.UserId)}"; + var result = Connection.Execute(sql, new { UserId = userId }, Transaction); + return result >= 1; + } + + public IEnumerable GetAccountPwdTop3(string account) + { + var sql = $@"SELECT * FROM {nameof(AccountPwd)} + WHERE {nameof(AccountPwd.Account)} = {nameof(account)} + ORDER BY {nameof(AccountPwd.CreatedOn)} DESC + LIMIT 3"; + + return Connection.Query(sql, new { account }, Transaction); + } + + public bool InsertAccountPwd(AccountPwd accountUser) + { + var sql = $@"INSERT INTO {nameof(AccountPwd)} ( + {nameof(AccountPwd.Account)}, + {nameof(AccountPwd.Password)}, + {nameof(AccountPwd.CreatedOn)}) + VALUES (@{nameof(AccountPwd.Account)}, + @{nameof(AccountPwd.Password)}, + @{nameof(AccountPwd.CreatedOn)})"; + var result = Connection.Execute(sql, accountUser, Transaction); + return result >= 1; + } + } +} diff --git a/Traffic.Repository/Implements/AnnounceRepository.cs b/Traffic.Repository/Implements/AnnounceRepository.cs new file mode 100644 index 0000000..5145346 --- /dev/null +++ b/Traffic.Repository/Implements/AnnounceRepository.cs @@ -0,0 +1,76 @@ +using Dapper; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class AnnounceRepository : IAnnounceRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public AnnounceRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public IEnumerable GetAnnounces() + { + var sql = $"SELECT * FROM {nameof(Announce)}"; + return Connection.Query(sql, null, Transaction); + } + + public Announce GetAnnounceById(int id) + { + var sql = $"SELECT * FROM {nameof(Announce)} Where {nameof(Announce.Id)} = @{nameof(Announce.Id)}"; + return Connection.QueryFirstOrDefault(sql, new { id }, Transaction); + } + + public bool InsertAnnounce(Announce announce) + { + var sql = $@"INSERT INTO {nameof(Announce)} ( + {nameof(Announce.Title)}, + {nameof(Announce.Content)}, + {nameof(Announce.StartOn)}, + {nameof(Announce.Status)}, + {nameof(Announce.CreatorId)}, + {nameof(Announce.CreatedOn)}) + VALUES(@{nameof(Announce.Title)}, + @{nameof(Announce.Content)}, + @{nameof(Announce.StartOn)}, + @{nameof(Announce.Status)}, + @{nameof(Announce.CreatorId)}, + @{nameof(Announce.CreatedOn)})"; + + var result = Connection.Execute(sql, announce, Transaction); + return result == 1; + } + + public bool UpdateAnnounce(Announce announce) + { + var sql = $@"UPDATE {nameof(Announce)} + SET {nameof(Announce.Title)} = @{nameof(Announce.Title)}, + {nameof(Announce.Content)} = @{nameof(Announce.Content)}, + {nameof(Announce.StartOn)} = @{nameof(Announce.StartOn)}, + {nameof(Announce.Status)} = @{nameof(Announce.Status)}, + {nameof(Announce.UpdatorId)} = @{nameof(Announce.UpdatorId)}, + {nameof(Announce.UpdatedOn)} = @{nameof(Announce.UpdatedOn)} + WHERE {nameof(Announce.Id)} = @{nameof(Announce.Id)}"; + var result = Connection.Execute(sql, announce, Transaction); + return result == 1; + } + + public bool DeleteAnnounce(int id) + { + var sql = $@"DELETE FROM {nameof(Announce)} WHERE {nameof(Announce.Id)} = @{nameof(Announce.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + } +} diff --git a/Traffic.Repository/Implements/CompanyInformationRepository.cs b/Traffic.Repository/Implements/CompanyInformationRepository.cs new file mode 100644 index 0000000..4319241 --- /dev/null +++ b/Traffic.Repository/Implements/CompanyInformationRepository.cs @@ -0,0 +1,75 @@ +using Dapper; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class CompanyInformationRepository : ICompanyInformationRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public CompanyInformationRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + /// + /// 分頁 select * from persons limit A offset B; + /// A就是你需要顯示多少行; + /// B就是查詢的起點位置。 + /// + /// 第幾頁 + /// 一頁幾行 + /// + public IEnumerable GetCompanyInformations() + { + var sql = $"SELECT * FROM {nameof(CompanyInformation)}"; + return Connection.Query(sql, null, Transaction); + } + + public CompanyInformation GetCompanyInformationById(int id) + { + var sql = $"SELECT * FROM {nameof(CompanyInformation)} Where {nameof(CompanyInformation.Id)} = @{nameof(CompanyInformation.Id)}"; + return Connection.QueryFirstOrDefault(sql, new { id }, Transaction); + } + + public bool InsertCompanyInformation(CompanyInformation company) + { + var sql = $@"INSERT INTO {nameof(CompanyInformation)} ( + {nameof(CompanyInformation.CompanyName)}, + {nameof(CompanyInformation.CompanyCode)}, + {nameof(CompanyInformation.Email)}) + VALUES(@{nameof(CompanyInformation.CompanyName)}, + @{nameof(CompanyInformation.CompanyCode)}, + @{nameof(CompanyInformation.Email)})"; + + var result = Connection.Execute(sql, company, Transaction); + return result == 1; + } + + public bool UpdateCompanyInformation(CompanyInformation company) + { + var sql = $@"UPDATE {nameof(CompanyInformation)} + SET {nameof(CompanyInformation.CompanyName)} = @{nameof(CompanyInformation.CompanyName)}, + {nameof(CompanyInformation.CompanyCode)} = @{nameof(CompanyInformation.CompanyCode)}, + {nameof(CompanyInformation.Email)} = @{nameof(CompanyInformation.Email)} + WHERE {nameof(CompanyInformation.Id)} = @{nameof(CompanyInformation.Id)}"; + var result = Connection.Execute(sql, company, Transaction); + return result == 1; + } + + public bool DeleteCompanyInformation(int id) + { + var sql = $@"DELETE FROM {nameof(CompanyInformation)} WHERE {nameof(CompanyInformation.Id)} = @{nameof(CompanyInformation.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + } +} diff --git a/Traffic.Repository/Implements/EventRepository.cs b/Traffic.Repository/Implements/EventRepository.cs new file mode 100644 index 0000000..78b3c0b --- /dev/null +++ b/Traffic.Repository/Implements/EventRepository.cs @@ -0,0 +1,370 @@ +using Dapper; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class EventRepository : IEventRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public EventRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public int GetEventCount(string term) + { + if (string.IsNullOrWhiteSpace(term)) + { + var sql = $"SELECT Count(*) FROM {nameof(Event)}"; + return Connection.QueryFirst(sql, null, Transaction); + } + else + { + var sql = $"SELECT Count(*) FROM {nameof(Event)} WHERE number = @number"; + return Connection.QueryFirst(sql, new { number = term }, Transaction); + } + } + + public int GetEventBySitesCount(string siteId, string term) + { + if (string.IsNullOrWhiteSpace(term)) + { + var sql = $"SELECT Count(*) FROM {nameof(Event)} WHERE siteId = @siteId"; + return Connection.QueryFirst(sql, new { siteId, number = term }, Transaction); + } + else + { + var sql = $"SELECT Count(*) FROM {nameof(Event)} WHERE siteId = @siteId and number = @number"; + return Connection.QueryFirst(sql, new { siteId, number = term }, Transaction); + } + } + + public int GetThisYearEventsCount(string startTime, string endTime, string account) + { + var sql = $"SELECT Count(*) FROM {nameof(Event)} WHERE punished = 1 and uploadTime >= @startTime and uploadTime >= @endTime and account = @account"; + return Connection.QueryFirst(sql, new { startTime, endTime, account }, Transaction); + } + + public int GetThisMonthEventsCount(string startTime, string endTime, string account) + { + var sql = $"SELECT Count(*) FROM {nameof(Event)} WHERE punished = 1 and uploadTime >= @startTime and uploadTime >= @endTime and account = @account"; + return Connection.QueryFirst(sql, new { startTime, endTime, account }, Transaction); + } + + public int GetEventByEventTypeCount(string eventType) + { + var sql = $"SELECT Count(*) FROM {nameof(Event)} WHERE eventType = @eventType"; + return Connection.QueryFirst(sql, new { eventType }, Transaction); + } + + public IEnumerable GetExceptionNumbers() + { + var sql = $"SELECT * FROM {nameof(ExceptionNumber)} "; + return Connection.Query(sql, null, Transaction); + } + public IEnumerable GetEvents() + { + var sql = $"SELECT * FROM {nameof(Event)} "; + return Connection.Query(sql, null, Transaction); + } + + public IEnumerable GetEventsByCar(string term) + { + var sql = $@"SELECT {nameof(Event.Id)}, + {nameof(Event.Number)}, + {nameof(Event.SiteID)}, + {nameof(Event.EventType)}, + {nameof(Event.InTime)}, + {nameof(Event.CheckPunish)}, + {nameof(Event.Punished)}, + {nameof(Event.Rejected)} + FROM {nameof(Event)} WHERE number like @term"; + return Connection.Query(sql, new { term }, Transaction); + } + + public IEnumerable GetEventBySites(string siteId, int pageNumber, int pageSize) + { + var sql = $"SELECT * FROM {nameof(Event)} WHERE siteId = @siteId limit @pageSize offset @offsetIndex"; + return Connection.Query(sql, new { siteId, pageSize, offsetIndex = pageSize * (pageNumber - 1) }, Transaction); + } + + public IEnumerable GetEventBySitesAndEventType(List sitesId, List eventTypes, string startTime, string endTime) + { + var sql = $@"SELECT s.*, e.checkPunish, e.punished, e.rejected, e.ps, e.speed, e.inTime, e.outTime, e.outTime, e.number, e.vehicleType, e.Ton + FROM event as e + LEFT JOIN siteinformation s on s.siteID = e.siteID + WHERE s.siteId in @sitesId and + s.eventType in @eventTypes and + e.alarmTime >= @startTime and e.alarmTime <= @endTime"; + return Connection.Query(sql, new { sitesId, eventTypes, startTime, endTime }, Transaction); + } + + public IEnumerable GetEventByEventType(string eventType, int pageNumber, int pageSize) + { + var sql = $"SELECT * FROM {nameof(Event)} WHERE eventType = @eventType limit @pageSize offset @offsetIndex"; + return Connection.Query(sql, new { eventType, pageSize, offsetIndex = pageSize * (pageNumber - 1) }, Transaction); + } + + public IEnumerable GetEvents(string startDatetime, string endDatetime) + { + var sql = $"SELECT * FROM {nameof(Event)} WHERE alarmTime >= @startDatetime AND alarmTime <= @endDatetime"; + return Connection.Query(sql, new { startDatetime, endDatetime }, Transaction); + } + + public IEnumerable GetEventJoinSiteAndUsers(int userId, string eventType, string startTime, string endTime) + { + var sql = $@"SELECT + e.id, + a.userId, + s.county, + s.area, + s.siteid, + s.siteName, + s.eventType, + s.laws, + e.* + FROM accountusersite as a + LEFT JOIN siteinformation as s on s.Id = a.siteid + LEFT JOIN event as e on s.siteID = e.siteID + WHERE a.userid = @userid and s.eventType = @eventType"; + + return Connection.Query(sql, + new + { + userId, + eventType, + startTime, + endTime + }, Transaction); + } + + public int GetEventByTimeCount(string startTime, string endTime) + { + var sql = $@"SELECT Count(*) + FROM event + WHERE alarmTime >= @startTime and alarmTime <= @endTime "; + + return Connection.QueryFirst(sql, + new + { + startTime, + endTime + }, Transaction); + } + + public IEnumerable GetEventByTime(string startTime, string endTime) + { + var sql = $@"SELECT * + FROM event + WHERE alarmTime >= @startTime and alarmTime <= @endTime "; + + return Connection.Query(sql, + new + { + startTime, + endTime + }, Transaction); + } + + public IEnumerable GetVehicleType() + { + var sql = $"SELECT * FROM vehicletype"; + return Connection.Query(sql, null, Transaction); + } + + public VehicleTypeTable GetVehicleTypebyType(string vehicletype) + { + var sql = $"SELECT * FROM vehicletype WHERE vehicletype = @vehicletype"; + return Connection.QueryFirstOrDefault(sql, new { vehicletype }, Transaction); + } + + public Event GetEventById(int id) + { + var sql = $"SELECT * FROM {nameof(Event)} Where {nameof(Event.Id)} = @{nameof(Event.Id)}"; + return Connection.QueryFirstOrDefault(sql, new { id }, Transaction); + } + + public bool InsertEvent(Event data) + { + var sql = $@"INSERT INTO {nameof(Event)} ( + {nameof(Event.SiteID)}, + {nameof(Event.EventID)}, + {nameof(Event.Channel)}, + {nameof(Event.Slot)}, + {nameof(Event.EventType)}, + {nameof(Event.VehicleType)}, + {nameof(Event.Distance)}, + {nameof(Event.Speed)}, + {nameof(Event.TotalPassTime)}, + {nameof(Event.LimitTon)}, + {nameof(Event.Ton)}, + {nameof(Event.InTime)}, + {nameof(Event.AlarmTime)}, + {nameof(Event.OutTime)}, + {nameof(Event.LPRTime)}, + {nameof(Event.IMGPath1)}, + {nameof(Event.IMGPath2)}, + {nameof(Event.IMGPath3)}, + {nameof(Event.IMGPath4)}, + {nameof(Event.IMGPath5)}, + {nameof(Event.IMGPath6)}, + {nameof(Event.VideoPath1)}, + {nameof(Event.VideoPath2)}, + {nameof(Event.IsStay)}, + {nameof(Event.Unsure)}, + {nameof(Event.CheckPunish)}, + {nameof(Event.Punished)}, + {nameof(Event.CompanyCode)}, + {nameof(Event.Ps)}, + {nameof(Event.HandlingTime)}, + {nameof(Event.UploadTime)}) + VALUES(@{nameof(Event.SiteID)}, + @{nameof(Event.EventID)}, + @{nameof(Event.Channel)}, + @{nameof(Event.Slot)}, + @{nameof(Event.Number)}, + @{nameof(Event.PlateNumber)}, + @{nameof(Event.EventType)}, + @{nameof(Event.VehicleType)}, + @{nameof(Event.Distance)}, + @{nameof(Event.Speed)}, + @{nameof(Event.TotalPassTime)}, + @{nameof(Event.LimitTon)}, + @{nameof(Event.Ton)}, + @{nameof(Event.InTime)}, + @{nameof(Event.AlarmTime)}, + @{nameof(Event.OutTime)}, + @{nameof(Event.LPRTime)}, + @{nameof(Event.IMGPath1)}, + @{nameof(Event.IMGPath2)}, + @{nameof(Event.IMGPath3)}, + @{nameof(Event.IMGPath4)}, + @{nameof(Event.IMGPath5)}, + @{nameof(Event.IMGPath6)}, + @{nameof(Event.VideoPath1)}, + @{nameof(Event.VideoPath2)}, + @{nameof(Event.IsStay)}, + @{nameof(Event.Unsure)}, + @{nameof(Event.CheckPunish)}, + @{nameof(Event.Punished)}, + @{nameof(Event.CompanyCode)}, + @{nameof(Event.Ps)}, + @{nameof(Event.HandlingTime)}, + @{nameof(Event.UploadTime)})"; + + var result = Connection.Execute(sql, data, Transaction); + return result == 1; + } + + public bool UpdateEvent(Event data) + { + var sql = $@"UPDATE {nameof(Event)} + SET {nameof(Event.SiteID)} = @{nameof(Event.SiteID)}, + {nameof(Event.EventID)} = @{nameof(Event.EventID)}, + {nameof(Event.Channel)} = @{nameof(Event.Channel)}, + {nameof(Event.Slot)} = @{nameof(Event.Slot)}, + {nameof(Event.Number)} = @{nameof(Event.Number)}, + {nameof(Event.PlateNumber)} = @{nameof(Event.PlateNumber)}, + {nameof(Event.EventType)} = @{nameof(Event.EventType)}, + {nameof(Event.VehicleType)} = @{nameof(Event.VehicleType)}, + {nameof(Event.Distance)} = @{nameof(Event.Distance)}, + {nameof(Event.Speed)} = @{nameof(Event.Speed)}, + {nameof(Event.TotalPassTime)} = @{nameof(Event.TotalPassTime)}, + {nameof(Event.LimitTon)} = @{nameof(Event.LimitTon)}, + {nameof(Event.Ton)} = @{nameof(Event.Ton)}, + {nameof(Event.InTime)} = @{nameof(Event.InTime)}, + {nameof(Event.AlarmTime)} = @{nameof(Event.AlarmTime)}, + {nameof(Event.OutTime)} = @{nameof(Event.OutTime)}, + {nameof(Event.LPRTime)} = @{nameof(Event.LPRTime)}, + {nameof(Event.IMGPath1)} = @{nameof(Event.IMGPath1)}, + {nameof(Event.IMGPath2)} = @{nameof(Event.IMGPath2)}, + {nameof(Event.IMGPath3)} = @{nameof(Event.IMGPath3)}, + {nameof(Event.IMGPath4)} = @{nameof(Event.IMGPath4)}, + {nameof(Event.IMGPath5)} = @{nameof(Event.IMGPath5)}, + {nameof(Event.IMGPath6)} = @{nameof(Event.IMGPath6)}, + {nameof(Event.VideoPath1)} = @{nameof(Event.VideoPath1)}, + {nameof(Event.VideoPath2)} = @{nameof(Event.VideoPath2)}, + {nameof(Event.IsStay)} = @{nameof(Event.IsStay)}, + {nameof(Event.Unsure)} = @{nameof(Event.Unsure)}, + {nameof(Event.CheckPunish)} = @{nameof(Event.CheckPunish)}, + {nameof(Event.Punished)} = @{nameof(Event.Punished)}, + {nameof(Event.CompanyCode)} = @{nameof(Event.CompanyCode)}, + {nameof(Event.Ps)} = @{nameof(Event.Ps)}, + {nameof(Event.HandlingTime)} = @{nameof(Event.HandlingTime)}, + {nameof(Event.UploadTime)} = @{nameof(Event.UploadTime)} + WHERE {nameof(Event.Id)} = @{nameof(Event.Id)}"; + var result = Connection.Execute(sql, data, Transaction); + return result == 1; + } + + public bool UpdatEventCheckPunish(string account, int eventId, string checkPunish, string law) + { + var sql = $@"UPDATE {nameof(Event)} + SET {nameof(Event.CheckPunish)} = @{nameof(Event.CheckPunish)}, + {nameof(Event.Ps)} = @law, + {nameof(Event.Account)} = @{nameof(Event.Account)} + WHERE {nameof(Event.Id)} = @{nameof(Event.Id)}"; + var result = Connection.Execute(sql, new { Id = eventId, account, checkPunish, law }, Transaction); + return result == 1; + } + + public bool UpdatEventNoPunish(string account, int eventId, string ps) + { + var sql = $@"UPDATE {nameof(Event)} + SET {nameof(Event.Ps)} = @{nameof(Event.Ps)}, {nameof(Event.Account)} = @{nameof(Event.Account)} + WHERE {nameof(Event.Id)} = @{nameof(Event.Id)}"; + var result = Connection.Execute(sql, new { Id = eventId, Ps = ps, account }, Transaction); + return result == 1; + } + + public bool UpdateEventVehicleType(int id, string vehicleType) + { + var sql = $@"UPDATE {nameof(Event)} + SET {nameof(Event.VehicleType)} = @{nameof(Event.VehicleType)} + WHERE {nameof(Event.Id)} = @{nameof(Event.Id)}"; + var result = Connection.Execute(sql, new { id, vehicleType }, Transaction); + return result == 1; + } + + public bool UpdateEventVehicleNumber(int id, string vehicleNumber) + { + var sql = $@"UPDATE {nameof(Event)} + SET {nameof(Event.Number)} = @{nameof(Event.Number)} + WHERE {nameof(Event.Id)} = @{nameof(Event.Id)}"; + var result = Connection.Execute(sql, new { id, Number = vehicleNumber }, Transaction); + return result == 1; + } + + public bool DeleteEvent(int id) + { + var sql = $@"DELETE FROM {nameof(Event)} WHERE {nameof(Event.Id)} = @{nameof(Event.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + + public bool UpdateEventVehicle(int id, string vehicleType, string vehicleNumber) + { + var sql = $@"UPDATE {nameof(Event)} + SET {nameof(Event.Number)} = @{nameof(Event.Number)}, + {nameof(Event.VehicleType)} = @{nameof(Event.VehicleType)} + WHERE {nameof(Event.Id)} = @{nameof(Event.Id)}"; + var result = Connection.Execute(sql, new { id, Number = vehicleNumber, vehicleType }, Transaction); + return result == 1; + } + + public int GetEventJoinSiteAndUsersCount(int userId, string eventType, string startTime, string endTime) + { + throw new NotImplementedException(); + } + } +} diff --git a/Traffic.Repository/Implements/EventTypeRepository.cs b/Traffic.Repository/Implements/EventTypeRepository.cs new file mode 100644 index 0000000..e954a66 --- /dev/null +++ b/Traffic.Repository/Implements/EventTypeRepository.cs @@ -0,0 +1,72 @@ +using Dapper; +using System.Collections.Generic; +using System.Data; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository +{ + public class EventTypeRepository : IEventTypeRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public EventTypeRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public IEnumerable GetEventTypes() + { + var sql = $"SELECT * FROM EventType"; + return Connection.Query(sql, null, Transaction); + } + + public IEnumerable GetEventType1s() + { + var sql = $"SELECT * FROM EventType1"; + return Connection.Query(sql, null, Transaction); + } + + public EventTypeData GetEventTypeById(int id) + { + var sql = $"SELECT * FROM EventType Where {nameof(EventTypeData.Id)} = @{nameof(EventTypeData.Id)}"; + return Connection.QueryFirstOrDefault(sql, new { id }, Transaction); + } + + public EventTypeData GetEventTypeByEventType(string eventType) + { + var sql = $"SELECT * FROM EventType Where {nameof(EventTypeData.EventType)} = @{nameof(EventTypeData.EventType)}"; + return Connection.QueryFirstOrDefault(sql, new { eventType }, Transaction); + } + + public bool InsertEventType(EventTypeData company) + { + var sql = $@"INSERT INTO EventType ( + {nameof(EventTypeData.EventType)}, + {nameof(EventTypeData.EventName)}) + VALUES(@{nameof(EventTypeData.EventType)}, + @{nameof(EventTypeData.EventName)})"; + + var result = Connection.Execute(sql, company, Transaction); + return result == 1; + } + + public bool UpdateEventType(EventTypeData company) + { + var sql = $@"UPDATE Eventtype + SET {nameof(EventTypeData.EventType)} = @{nameof(EventTypeData.EventType)}, + {nameof(EventTypeData.EventName)} = @{nameof(EventTypeData.EventName)} + WHERE {nameof(EventTypeData.Id)} = @{nameof(EventTypeData.Id)}"; + var result = Connection.Execute(sql, company, Transaction); + return result == 1; + } + + public bool DeleteEventType(int id) + { + var sql = $@"DELETE FROM Eventtype WHERE {nameof(EventTypeData.Id)} = @{nameof(EventTypeData.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + } +} diff --git a/Traffic.Repository/Implements/MalfunctionRepository.cs b/Traffic.Repository/Implements/MalfunctionRepository.cs new file mode 100644 index 0000000..5c45d1d --- /dev/null +++ b/Traffic.Repository/Implements/MalfunctionRepository.cs @@ -0,0 +1,44 @@ +using Dapper; +using System.Collections.Generic; +using System.Data; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class MalfunctionRepository : IMalfunctionRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public MalfunctionRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public IEnumerable GetMalfunctions() + { + var sql = $@"SELECT m.siteID, m.companyCode, m.deviceType, m.deviceID, m.message, Max(m.timestamp) as timestamp + FROM malfunction as m group by m.companyCode, m.deviceType, m.deviceID "; + return Connection.Query(sql, null, Transaction); + } + + public IEnumerable GetMalfunctions(int userid) + { + var sql = $@"SELECT us.userId, s.siteid, m.companyCode, m.deviceType, m.deviceID, m.message, Max(m.timestamp) as timestamp + FROM accountusersite as us + left join siteinformation as s on us.siteid = s.id + left join malfunction as m on s.siteid = m.siteID where us.userid = @userid group by us.userId,s.county,s.area, s.siteid, s.siteName, s.eventType, m.companyCode, m.deviceType, m.deviceID "; + return Connection.Query(sql, new { userid }, Transaction); + } + + public IEnumerable GetMalfunctions(List sitesId, string startTime, string endTime) + { + var sql = $@"SELECT s.siteid, s.siteName, m.* + FROM siteinformation as s + LEFT JOIN malfunction as m on s.siteid = m.siteID + WHERE s.siteid in @sitesId and m.timestamp >= @startTime and m.timestamp <= @endTime"; + return Connection.Query(sql, new { sitesId, startTime, endTime }, Transaction); + } + } +} diff --git a/Traffic.Repository/Implements/NotPunishRepository.cs b/Traffic.Repository/Implements/NotPunishRepository.cs new file mode 100644 index 0000000..68b8be4 --- /dev/null +++ b/Traffic.Repository/Implements/NotPunishRepository.cs @@ -0,0 +1,67 @@ +using Dapper; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class NotPunishRepository : INotPunishRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public NotPunishRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public IEnumerable GetNotPunishs() + { + var sql = $"SELECT * FROM {nameof(NotPunish)}"; + return Connection.Query(sql, null, Transaction); + } + + public NotPunish GetNotPunishById(int id) + { + var sql = $"SELECT * FROM {nameof(NotPunish)} Where {nameof(NotPunish.Id)} = @{nameof(NotPunish.Id)}"; + return Connection.QueryFirstOrDefault(sql, new { id }, Transaction); + } + + public bool InsertNotPunish(NotPunish data) + { + var sql = $@"INSERT INTO {nameof(NotPunish)} ( + {nameof(NotPunish.EventTypeId)}, + {nameof(NotPunish.NotPunishType)}, + {nameof(NotPunish.NotPunishReason)}) + VALUES(@{nameof(NotPunish.EventTypeId)}, + @{nameof(NotPunish.NotPunishType)}, + @{nameof(NotPunish.NotPunishReason)})"; + + var result = Connection.Execute(sql, data, Transaction); + return result == 1; + } + + public bool UpdateNotPunish(NotPunish data) + { + var sql = $@"UPDATE {nameof(NotPunish)} + SET {nameof(NotPunish.EventTypeId)} = @{nameof(NotPunish.EventTypeId)}, + {nameof(NotPunish.NotPunishType)} = @{nameof(NotPunish.NotPunishType)}, + {nameof(NotPunish.NotPunishReason)} = @{nameof(NotPunish.NotPunishReason)} + WHERE {nameof(NotPunish.Id)} = @{nameof(NotPunish.Id)}"; + var result = Connection.Execute(sql, data, Transaction); + return result == 1; + } + + public bool DeleteNotPunish(int id) + { + var sql = $@"DELETE FROM {nameof(NotPunish)} WHERE {nameof(NotPunish.Id)} = @{nameof(NotPunish.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + } +} diff --git a/Traffic.Repository/Implements/PoliceStationRepository.cs b/Traffic.Repository/Implements/PoliceStationRepository.cs new file mode 100644 index 0000000..950de84 --- /dev/null +++ b/Traffic.Repository/Implements/PoliceStationRepository.cs @@ -0,0 +1,64 @@ +using Dapper; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class PoliceStationRepository : IPoliceStationRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public PoliceStationRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public IEnumerable GetPoliceStations() + { + var sql = $"SELECT * FROM {nameof(PoliceStation)}"; + return Connection.Query(sql, null, Transaction); + } + + public PoliceStation GetPoliceStationById(int id) + { + var sql = $"SELECT * FROM {nameof(PoliceStation)} Where {nameof(PoliceStation.Id)} = @{nameof(PoliceStation.Id)}"; + return Connection.QueryFirstOrDefault(sql, new { id }, Transaction); + } + + public bool InsertPoliceStation(PoliceStation station) + { + var sql = $@"INSERT INTO {nameof(PoliceStation)} ( + {nameof(PoliceStation.Area)}, + {nameof(PoliceStation.StationName)}) + VALUES(@{nameof(PoliceStation.Area)}, + @{nameof(PoliceStation.StationName)})"; + + var result = Connection.Execute(sql, station, Transaction); + return result == 1; + } + + public bool UpdatePoliceStation(PoliceStation station) + { + var sql = $@"UPDATE {nameof(PoliceStation)} + SET {nameof(PoliceStation.Area)} = @{nameof(PoliceStation.Area)}, + {nameof(PoliceStation.StationName)} = @{nameof(PoliceStation.StationName)} + WHERE {nameof(PoliceStation.Id)} = @{nameof(PoliceStation.Id)}"; + var result = Connection.Execute(sql, station, Transaction); + return result == 1; + } + + public bool DeletePoliceStation(int id) + { + var sql = $@"DELETE FROM {nameof(PoliceStation)} WHERE {nameof(PoliceStation.Id)} = @{nameof(PoliceStation.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + } +} diff --git a/Traffic.Repository/Implements/RepairRepository.cs b/Traffic.Repository/Implements/RepairRepository.cs new file mode 100644 index 0000000..b65f96e --- /dev/null +++ b/Traffic.Repository/Implements/RepairRepository.cs @@ -0,0 +1,70 @@ +using Dapper; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class RepairRepository : IRepairRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public RepairRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public IEnumerable GetRepairs() + { + var sql = $"SELECT * FROM {nameof(Repair)}"; + return Connection.Query(sql, null, Transaction); + } + + public Repair GetRepairById(int id) + { + var sql = $"SELECT * FROM {nameof(Repair)} Where {nameof(Repair.Id)} = @{nameof(Repair.Id)}"; + return Connection.QueryFirstOrDefault(sql, new { id }, Transaction); + } + + public bool InsertRepair(Repair data) + { + var sql = $@"INSERT INTO {nameof(Repair)} ( + {nameof(Repair.QuestionType)}, + {nameof(Repair.SendTo)}, + {nameof(Repair.Title)}, + {nameof(Repair.Content)}) + VALUES(@{nameof(Repair.QuestionType)}, + @{nameof(Repair.SendTo)}, + @{nameof(Repair.Title)}, + @{nameof(Repair.Content)})"; + + var result = Connection.Execute(sql, data, Transaction); + return result == 1; + } + + public bool UpdateRepair(Repair data) + { + var sql = $@"UPDATE {nameof(Repair)} + SET {nameof(Repair.QuestionType)} = @{nameof(Repair.QuestionType)}, + {nameof(Repair.SendTo)} = @{nameof(Repair.SendTo)}, + {nameof(Repair.Title)} = @{nameof(Repair.Title)}, + {nameof(Repair.Content)} = @{nameof(Repair.Content)} + WHERE {nameof(Repair.Id)} = @{nameof(Repair.Id)}"; + var result = Connection.Execute(sql, data, Transaction); + return result == 1; + } + + public bool DeleteRepair(int id) + { + var sql = $@"DELETE FROM {nameof(Repair)} WHERE {nameof(Repair.Id)} = @{nameof(Repair.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + } +} diff --git a/Traffic.Repository/Implements/RolePageRepository.cs b/Traffic.Repository/Implements/RolePageRepository.cs new file mode 100644 index 0000000..a1d1122 --- /dev/null +++ b/Traffic.Repository/Implements/RolePageRepository.cs @@ -0,0 +1,144 @@ +using Dapper; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class RolePageRepository : IRolePageRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public RolePageRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public IEnumerable GetRolePages() + { + var sql = $"SELECT * FROM {nameof(RolePage)}"; + return Connection.Query(sql, null, Transaction); + } + + public IEnumerable GetRolePageByRoleId(int RoleId) + { + var sql = $"SELECT * FROM {nameof(RolePage)} Where {nameof(RolePage.RoleId)} = @{nameof(RolePage.RoleId)}"; + return Connection.Query(sql, new { RoleId }, Transaction); + } + + public bool InsertRolePage(List RoleId) + { + var sql = $@"INSERT INTO {nameof(RolePage)} ( + {nameof(RolePage.RoleId)}, + {nameof(RolePage.PageId)}) + VALUES(@{nameof(RolePage.RoleId)}, + @{nameof(RolePage.PageId)})"; + + var result = Connection.Execute(sql, RoleId, Transaction); + return result == 1; + } + + public bool InsertRolePage(RolePage RoleId) + { + var sql = $@"INSERT INTO {nameof(RolePage)} ( + {nameof(RolePage.RoleId)}, + {nameof(RolePage.PageId)}) + VALUES(@{nameof(RolePage.RoleId)}, + @{nameof(RolePage.PageId)})"; + + var result = Connection.Execute(sql, RoleId, Transaction); + return result == 1; + } + + public bool UpdateRolePage(RolePage RoleId) + { + var sql = $@"UPDATE {nameof(RolePage)} + SET {nameof(RolePage.RoleId)} = @{nameof(RolePage.RoleId)}, + {nameof(RolePage.PageId)} = @{nameof(RolePage.PageId)} + WHERE {nameof(RolePage.Id)} = @{nameof(RolePage.Id)}"; + var result = Connection.Execute(sql, RoleId, Transaction); + return result == 1; + } + + public bool DeleteRolePage(int id) + { + var sql = $@"DELETE FROM {nameof(RolePage)} WHERE {nameof(RolePage.Id)} = @{nameof(RolePage.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + + + public IEnumerable GetRolePermissionInfo(int? roleid) + { + var sql = $@"SELECT r.roleid as roleId, ar.RoleName , p.id as pageid, p.pagename + FROM traffic.pagelist as p + LEFT JOIN traffic.rolepage as r on r.pageid = p.id + LEFT JOIN traffic.accountrole as ar on ar.id = r.roleId "; + return Connection.Query(sql, new { roleid }, Transaction); + } + + public IEnumerable GetRolePageLists(int roleid) + { + var sql = $@"SELECT r.roleid as roleId, p.id as pageid, p.pagemodule, p.pagename, p.pageurl + FROM traffic.pagelist as p + LEFT JOIN traffic.rolepage as r on r.pageid = p.id + WHERE roleid = @roleid"; + return Connection.Query(sql, new { roleid }, Transaction); + } + + + + + + + public IEnumerable GetPageLists() + { + var sql = $"SELECT * FROM {nameof(PageList)}"; + return Connection.Query(sql, null, Transaction); + } + + public PageList GetPageListById(int id) + { + var sql = $"SELECT * FROM {nameof(PageList)} Where {nameof(PageList.Id)} = @{nameof(PageList.Id)}"; + return Connection.QueryFirstOrDefault(sql, new { id }, Transaction); + } + + public bool InsertPageList(PageList company) + { + var sql = $@"INSERT INTO {nameof(PageList)} ( + {nameof(PageList.PageName)}, + {nameof(PageList.PageModule)}, + {nameof(PageList.PageURL)}) + VALUES(@{nameof(PageList.PageName)}, + @{nameof(PageList.PageModule)}, + @{nameof(PageList.PageURL)})"; + + var result = Connection.Execute(sql, company, Transaction); + return result == 1; + } + + public bool UpdatePageList(PageList company) + { + var sql = $@"UPDATE {nameof(PageList)} + SET {nameof(PageList.PageName)} = @{nameof(PageList.PageName)}, + {nameof(PageList.PageModule)} = @{nameof(PageList.PageModule)}, + {nameof(PageList.PageURL)} = @{nameof(PageList.PageURL)} + WHERE {nameof(PageList.Id)} = @{nameof(PageList.Id)}"; + var result = Connection.Execute(sql, company, Transaction); + return result == 1; + } + + public bool DeletePageList(int id) + { + var sql = $@"DELETE FROM {nameof(PageList)} WHERE {nameof(PageList.Id)} = @{nameof(PageList.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + } +} diff --git a/Traffic.Repository/Implements/SiteInformationRepository.cs b/Traffic.Repository/Implements/SiteInformationRepository.cs new file mode 100644 index 0000000..c28f6b1 --- /dev/null +++ b/Traffic.Repository/Implements/SiteInformationRepository.cs @@ -0,0 +1,114 @@ +using Dapper; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class SiteInformationRepository : ISiteInformationRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public SiteInformationRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public IEnumerable GetSiteInformations() + { + var sql = $"SELECT * FROM {nameof(SiteInformation)}"; + return Connection.Query(sql, null, Transaction); + } + + public IEnumerable GetSiteInformations(List eventTypes) + { + var sql = $"SELECT * FROM {nameof(SiteInformation)} where eventType in @eventTypes"; + return Connection.Query(sql, new { eventTypes }, Transaction); + } + + public SiteInformation GetSiteInformationById(int id) + { + var sql = $"SELECT * FROM {nameof(SiteInformation)} Where {nameof(SiteInformation.Id)} = @{nameof(SiteInformation.Id)}"; + return Connection.QueryFirstOrDefault(sql, new { id }, Transaction); + } + + public SiteInformation GetSiteInformationBySiteId(string siteId) + { + var sql = $"SELECT * FROM {nameof(SiteInformation)} Where {nameof(SiteInformation.SiteID)} = @{nameof(SiteInformation.SiteID)}"; + return Connection.QueryFirstOrDefault(sql, new { siteId }, Transaction); + } + + public bool InsertSiteInformation(SiteInformation data) + { + var sql = $@"INSERT INTO {nameof(SiteInformation)} ( + {nameof(SiteInformation.County)}, + {nameof(SiteInformation.Area)}, + {nameof(SiteInformation.SiteID)}, + {nameof(SiteInformation.SiteName)}, + {nameof(SiteInformation.EventType)}, + {nameof(SiteInformation.Ip)}, + {nameof(SiteInformation.DbName)}, + {nameof(SiteInformation.TableName)}, + {nameof(SiteInformation.User)}, + {nameof(SiteInformation.Password)}, + {nameof(SiteInformation.FinalRecord)}, + {nameof(SiteInformation.ARHFinalRecord)}, + {nameof(SiteInformation.CompanyCode)}, + {nameof(SiteInformation.Laws)}) + VALUES(@{nameof(SiteInformation.County)}, + @{nameof(SiteInformation.Area)}, + @{nameof(SiteInformation.SiteID)}, + @{nameof(SiteInformation.SiteName)}, + @{nameof(SiteInformation.EventType)}, + @{nameof(SiteInformation.Ip)}, + @{nameof(SiteInformation.DbName)}, + @{nameof(SiteInformation.TableName)}, + @{nameof(SiteInformation.User)}, + @{nameof(SiteInformation.Password)}, + @{nameof(SiteInformation.FinalRecord)}, + @{nameof(SiteInformation.ARHFinalRecord)}, + @{nameof(SiteInformation.CompanyCode)}, + @{nameof(SiteInformation.Laws)})"; + + var result = Connection.Execute(sql, data, Transaction); + return result == 1; + } + + public bool UpdateSiteInformation(SiteInformation data) + { + var sql = $@"UPDATE {nameof(SiteInformation)} + SET {nameof(SiteInformation.County)} = @{nameof(SiteInformation.County)}, + {nameof(SiteInformation.Area)} = @{nameof(SiteInformation.Area)}, + {nameof(SiteInformation.SiteID)} = @{nameof(SiteInformation.SiteID)}, + {nameof(SiteInformation.SiteName)} = @{nameof(SiteInformation.SiteName)}, + {nameof(SiteInformation.EventType)} = @{nameof(SiteInformation.EventType)}, + {nameof(SiteInformation.Ip)} = @{nameof(SiteInformation.Ip)}, + {nameof(SiteInformation.DbName)} = @{nameof(SiteInformation.DbName)}, + {nameof(SiteInformation.TableName)} = @{nameof(SiteInformation.TableName)}, + {nameof(SiteInformation.User)} = @{nameof(SiteInformation.User)}, + {nameof(SiteInformation.Password)} = @{nameof(SiteInformation.Password)}, + {nameof(SiteInformation.FinalRecord)} = @{nameof(SiteInformation.FinalRecord)}, + {nameof(SiteInformation.Target)} = @{nameof(SiteInformation.Target)}, + {nameof(SiteInformation.ClusterHead)} = @{nameof(SiteInformation.ClusterHead)}, + {nameof(SiteInformation.ARHFinalRecord)} = @{nameof(SiteInformation.ARHFinalRecord)}, + {nameof(SiteInformation.CompanyCode)} = @{nameof(SiteInformation.CompanyCode)}, + {nameof(SiteInformation.Laws)} = @{nameof(SiteInformation.Laws)} + WHERE {nameof(SiteInformation.Id)} = @{nameof(SiteInformation.Id)}"; + var result = Connection.Execute(sql, data, Transaction); + return result == 1; + } + + public bool DeleteSiteInformation(int id) + { + var sql = $@"DELETE FROM {nameof(SiteInformation)} WHERE {nameof(SiteInformation.Id)} = @{nameof(SiteInformation.Id)}"; + var result = Connection.Execute(sql, new { id }, Transaction); + return result == 1; + } + } +} diff --git a/Traffic.Repository/Implements/TycgRepository.cs b/Traffic.Repository/Implements/TycgRepository.cs new file mode 100644 index 0000000..477873c --- /dev/null +++ b/Traffic.Repository/Implements/TycgRepository.cs @@ -0,0 +1,64 @@ +using Dapper; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Implements +{ + public class TycgRepository : ITycgRepository + { + public IDbTransaction Transaction { get; } + public IDbConnection Connection => Transaction.Connection; + + public TycgRepository(IDbTransaction transaction) + { + Transaction = transaction; + } + + public IEnumerable GetTycgs(string tableName) + { + var sql = string.Empty; + switch (tableName.ToLower().Trim()) + { + case "tycg_logases": + sql = $"SELECT * FROM tycg_logases order by timestamp desc"; + break; + case "tycg_logbigcarviolation": + sql = $"SELECT * FROM tycg_logbigcarviolation order by timestamp desc"; + break; + case "tycg_logchecked": + sql = $"SELECT * FROM tycg_logchecked order by timestamp desc"; + break; + case "tycg_logcrossroad": + sql = $"SELECT * FROM tycg_logcrossroad order by timestamp desc"; + break; + case "tycg_logmalfunctionhttp": + sql = $"SELECT * FROM tycg_logmalfunctionhttp order by timestamp desc"; + break; + case "tycg_logrejected": + sql = $"SELECT * FROM tycg_logrejected order by timestamp desc"; + break; + case "tycg_logtraffichttp": + sql = $"SELECT * FROM tycg_logtraffichttp order by timestamp desc"; + break; + case "tycg_loguploaded": + sql = $"SELECT * FROM tycg_loguploaded order by timestamp desc"; + break; + default: + break; + } + return Connection.Query(sql, null, Transaction); + } + + public IEnumerable GetTycgsTableName() + { + var sql = $"SELECT * FROM {nameof(Log_Mapping)}"; + return Connection.Query(sql, null, Transaction); + } + } +} diff --git a/Traffic.Repository/Infrastructures/ConnectionFactory.cs b/Traffic.Repository/Infrastructures/ConnectionFactory.cs new file mode 100644 index 0000000..b558fc2 --- /dev/null +++ b/Traffic.Repository/Infrastructures/ConnectionFactory.cs @@ -0,0 +1,29 @@ +using Microsoft.Extensions.Configuration; +using MySql.Data.MySqlClient; +using System.Data.Common; +using System.Data.SqlClient; + +namespace Traffic.Repository.Infrastructures +{ + public class ConnectionFactory + { + private readonly IConfiguration _configuration; + public ConnectionFactory(IConfiguration configuration) + { + _configuration = configuration; + } + + public DbConnection CreateDbConn() + { + return new MySqlConnection(GetConnectionString()); + } + + private string GetConnectionString() + { + //return _configuration.GetConnectionString("DefaultConnection"); + + return _configuration["ConnectionStrings:DefaultConnection"]; + + } + } +} diff --git a/Traffic.Repository/Infrastructures/IUnitOfWork.cs b/Traffic.Repository/Infrastructures/IUnitOfWork.cs new file mode 100644 index 0000000..62f1d7e --- /dev/null +++ b/Traffic.Repository/Infrastructures/IUnitOfWork.cs @@ -0,0 +1,23 @@ +using System; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Infrastructures +{ + public interface IUnitOfWork : IDisposable + { + IAccountRepository AccountRepository { get; } + ICompanyInformationRepository CompanyInformationRepository { get; } + IEventTypeRepository EventTypeRepository { get; } + IPoliceStationRepository PoliceStationRepository { get; } + IAnnounceRepository AnnounceRepository { get; } + IRolePageRepository RolePageRepository { get; } + INotPunishRepository NotPunishRepository { get; } + ISiteInformationRepository SiteInformationRepository { get; } + IEventRepository EventRepository { get; } + IMalfunctionRepository MalfunctionRepository { get; } + ITycgRepository TycgRepository { get; } + IRepairRepository RepairRepository { get; } + void Complete(); + void Rollback(); + } +} diff --git a/Traffic.Repository/Infrastructures/UnitOfWork.cs b/Traffic.Repository/Infrastructures/UnitOfWork.cs new file mode 100644 index 0000000..9ac43b1 --- /dev/null +++ b/Traffic.Repository/Infrastructures/UnitOfWork.cs @@ -0,0 +1,121 @@ +using System; +using System.Data; +using Traffic.Repository.Implements; +using Traffic.Repository.Interfaces; + +namespace Traffic.Repository.Infrastructures +{ + public class UnitOfWork : IUnitOfWork + { + private IDbConnection _connection; + private IDbTransaction _transaction; + + private IAccountRepository _accountRepository; + private ICompanyInformationRepository _companyInformationRepository; + private IEventTypeRepository _eventTypeRepository; + private IPoliceStationRepository _policeStationRepository; + private IAnnounceRepository _announceRepository; + private IRolePageRepository _roleRepository; + private INotPunishRepository _notPunishRepository; + private ISiteInformationRepository _siteInformationRepository; + private IEventRepository _eventRepository; + private IMalfunctionRepository _malfunctionRepository; + private ITycgRepository _tycgRepository; + private IRepairRepository _repairRepository; + private bool _disposed; + + public UnitOfWork(ConnectionFactory connectionFactory) + { + var factory = connectionFactory; + + _connection = factory.CreateDbConn(); + _connection.Open(); + _transaction = _connection.BeginTransaction(); + } + + public IAccountRepository AccountRepository => _accountRepository ??= new AccountRepository(_transaction); + public ICompanyInformationRepository CompanyInformationRepository => _companyInformationRepository ??= new CompanyInformationRepository(_transaction); + public IEventTypeRepository EventTypeRepository => _eventTypeRepository ??= new EventTypeRepository(_transaction); + public IPoliceStationRepository PoliceStationRepository => _policeStationRepository ??= new PoliceStationRepository(_transaction); + public IAnnounceRepository AnnounceRepository => _announceRepository ??= new AnnounceRepository(_transaction); + public IRolePageRepository RolePageRepository => _roleRepository ??= new RolePageRepository(_transaction); + public INotPunishRepository NotPunishRepository => _notPunishRepository ??= new NotPunishRepository(_transaction); + public ISiteInformationRepository SiteInformationRepository => _siteInformationRepository ??= new SiteInformationRepository(_transaction); + public IEventRepository EventRepository => _eventRepository ??= new EventRepository(_transaction); + public IMalfunctionRepository MalfunctionRepository => _malfunctionRepository ??= new MalfunctionRepository(_transaction); + public ITycgRepository TycgRepository => _tycgRepository ??= new TycgRepository(_transaction); + public IRepairRepository RepairRepository => _repairRepository ??= new RepairRepository(_transaction); + + public void Rollback() + { + _transaction.Rollback(); + } + + public void Complete() + { + try + { + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + finally + { + _transaction.Dispose(); + _transaction = _connection.BeginTransaction(); + ResetRepositories(); + } + } + + private void ResetRepositories() + { + _accountRepository = null; + _companyInformationRepository = null; + _eventTypeRepository = null; + _policeStationRepository = null; + _announceRepository = null; + _roleRepository = null; + _notPunishRepository = null; + _siteInformationRepository = null; + _eventRepository = null; + _malfunctionRepository = null; + _tycgRepository = null; + _repairRepository = null; + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + if (_transaction != null) + { + _transaction.Dispose(); + _transaction = null; + } + if (_connection != null) + { + _connection.Dispose(); + _connection = null; + } + } + _disposed = true; + } + } + + ~UnitOfWork() + { + Dispose(false); + } + } +} diff --git a/Traffic.Repository/Interfaces/IAccountRepository.cs b/Traffic.Repository/Interfaces/IAccountRepository.cs new file mode 100644 index 0000000..f823f16 --- /dev/null +++ b/Traffic.Repository/Interfaces/IAccountRepository.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; + +namespace Traffic.Repository.Interfaces +{ + public interface IAccountRepository + { + public IEnumerable GetAccountUsers(); + public AccountUser GetAccountUserById(int id); + public AccountUser GetAccountUserByAccount(string account); + public IEnumerable GetAccountRoles(); + public IEnumerable GetAccountUserSite(int id); + public IEnumerable GetAccountUserSites(); + public AccountUser GetAccountUserByAccount(string account, string password); + public int InsertAccountUser(AccountUser accountUser); + public int InsertAccountRole(AccountRole accountRole); + public bool InsertAccountUserSite(List userSite); + public bool UpdateAccountUserbyAdmin(AccountUser accountUser); + public bool UpdateAccountUserPasswordByAdmin(int id, string newPassword, int byWho, DateTime updateOn); + public bool UpdateAccountUserbyUser(AccountUser accountUser); + public bool UpdateAccountUserPasswordByUser(int id, string oldPassword, string newPassword, DateTime updatedOn); + public bool InsertUserLoginLog(UserLoginLog userLogin); + public bool UpdateUserErrorCount(int id, int errorCount); + public bool DeleteUser(int id); + public bool DeleteUserSite(int userId); + public bool DisableUser(int byWho, int id, int status); + public IEnumerable GetAccountPwdTop3(string account); + public bool InsertAccountPwd(AccountPwd accountUser); + } +} diff --git a/Traffic.Repository/Interfaces/IAnnounceRepository.cs b/Traffic.Repository/Interfaces/IAnnounceRepository.cs new file mode 100644 index 0000000..dee3bf6 --- /dev/null +++ b/Traffic.Repository/Interfaces/IAnnounceRepository.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Repository.Interfaces +{ + public interface IAnnounceRepository + { + public IEnumerable GetAnnounces(); + public Announce GetAnnounceById(int id); + public bool InsertAnnounce(Announce company); + public bool UpdateAnnounce(Announce company); + public bool DeleteAnnounce(int id); + } +} diff --git a/Traffic.Repository/Interfaces/ICompanyInformationRepository.cs b/Traffic.Repository/Interfaces/ICompanyInformationRepository.cs new file mode 100644 index 0000000..2b98db8 --- /dev/null +++ b/Traffic.Repository/Interfaces/ICompanyInformationRepository.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Repository.Interfaces +{ + public interface ICompanyInformationRepository + { + public IEnumerable GetCompanyInformations(); + public CompanyInformation GetCompanyInformationById(int id); + public bool InsertCompanyInformation(CompanyInformation company); + public bool UpdateCompanyInformation(CompanyInformation company); + public bool DeleteCompanyInformation(int id); + } +} diff --git a/Traffic.Repository/Interfaces/IEventRepository.cs b/Traffic.Repository/Interfaces/IEventRepository.cs new file mode 100644 index 0000000..898e794 --- /dev/null +++ b/Traffic.Repository/Interfaces/IEventRepository.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; + +namespace Traffic.Repository.Interfaces +{ + public interface IEventRepository + { + public int GetEventCount(string term); + public int GetEventBySitesCount(string siteId, string term); + public int GetEventJoinSiteAndUsersCount(int userId, string eventType, string startTime, string endTime); + public IEnumerable GetEvents(); + public IEnumerable GetEventsByCar(string term); + public IEnumerable GetEventBySites(string siteId, int page, int pageSize); + public IEnumerable GetEventBySitesAndEventType(List sitesId, List eventTypes, string startTime, string endTime); + public IEnumerable GetEventByEventType(string eventType, int page, int pageSize); + public int GetEventByTimeCount(string startTime, string endTime); + public IEnumerable GetEventByTime(string startTime, string endTime); + public IEnumerable GetVehicleType(); + //public IEnumerable GetEventJoinSiteAndUsers(int userid, string eventType, string startTime, string endTime); + public IEnumerable GetEventJoinSiteAndUsers(int userId, string eventType, string startTime, string endTime); + public IEnumerable GetEvents(string startDatetime, string endDatetime); + public Event GetEventById(int id); + public VehicleTypeTable GetVehicleTypebyType(string vehicletype); + public int GetThisYearEventsCount(string startTime, string endTime, string account); + public int GetThisMonthEventsCount(string startTime, string endTime, string account); + public int GetEventByEventTypeCount(string eventType); + public bool InsertEvent(Event data); + public bool UpdateEvent(Event data); + public bool UpdatEventCheckPunish(string account, int eventId, string checkPunish, string law); + public bool UpdatEventNoPunish(string account, int eventId, string ps); + public bool UpdateEventVehicleType(int id, string vehicleType); + public bool UpdateEventVehicleNumber(int id, string vehicleNumber); + public bool UpdateEventVehicle(int id, string vehicleType, string vehicleNumber); + public bool DeleteEvent(int id); + public IEnumerable GetExceptionNumbers(); + } +} diff --git a/Traffic.Repository/Interfaces/IEventTypeRepository.cs b/Traffic.Repository/Interfaces/IEventTypeRepository.cs new file mode 100644 index 0000000..b8b37a4 --- /dev/null +++ b/Traffic.Repository/Interfaces/IEventTypeRepository.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; +using Traffic.Data.Models; + +namespace Traffic.Repository.Interfaces +{ + public interface IEventTypeRepository + { + public IEnumerable GetEventTypes(); + public IEnumerable GetEventType1s(); + public EventTypeData GetEventTypeById(int id); + public EventTypeData GetEventTypeByEventType(string eventType); + public bool InsertEventType(EventTypeData eventType); + public bool UpdateEventType(EventTypeData eventType); + public bool DeleteEventType(int id); + } +} diff --git a/Traffic.Repository/Interfaces/IMalfunctionRepository.cs b/Traffic.Repository/Interfaces/IMalfunctionRepository.cs new file mode 100644 index 0000000..50bb319 --- /dev/null +++ b/Traffic.Repository/Interfaces/IMalfunctionRepository.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Repository.Interfaces +{ + public interface IMalfunctionRepository + { + public IEnumerable GetMalfunctions(); + public IEnumerable GetMalfunctions(int userid); + public IEnumerable GetMalfunctions(List sitesId, string startTime, string endTime); + } +} diff --git a/Traffic.Repository/Interfaces/INotPunishRepository.cs b/Traffic.Repository/Interfaces/INotPunishRepository.cs new file mode 100644 index 0000000..75a6171 --- /dev/null +++ b/Traffic.Repository/Interfaces/INotPunishRepository.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Repository.Interfaces +{ + public interface INotPunishRepository + { + public IEnumerable GetNotPunishs(); + public NotPunish GetNotPunishById(int id); + public bool InsertNotPunish(NotPunish data); + public bool UpdateNotPunish(NotPunish data); + public bool DeleteNotPunish(int id); + } +} diff --git a/Traffic.Repository/Interfaces/IPoliceStationRepository.cs b/Traffic.Repository/Interfaces/IPoliceStationRepository.cs new file mode 100644 index 0000000..a01a940 --- /dev/null +++ b/Traffic.Repository/Interfaces/IPoliceStationRepository.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Repository.Interfaces +{ + public interface IPoliceStationRepository + { + public IEnumerable GetPoliceStations(); + public PoliceStation GetPoliceStationById(int id); + public bool InsertPoliceStation(PoliceStation station); + public bool UpdatePoliceStation(PoliceStation station); + public bool DeletePoliceStation(int id); + } +} diff --git a/Traffic.Repository/Interfaces/IRepairRepository.cs b/Traffic.Repository/Interfaces/IRepairRepository.cs new file mode 100644 index 0000000..b0a17c4 --- /dev/null +++ b/Traffic.Repository/Interfaces/IRepairRepository.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Repository.Interfaces +{ + public interface IRepairRepository + { + public IEnumerable GetRepairs(); + public Repair GetRepairById(int id); + public bool InsertRepair(Repair data); + public bool UpdateRepair(Repair data); + public bool DeleteRepair(int id); + } +} diff --git a/Traffic.Repository/Interfaces/IRolePageRepository.cs b/Traffic.Repository/Interfaces/IRolePageRepository.cs new file mode 100644 index 0000000..8662457 --- /dev/null +++ b/Traffic.Repository/Interfaces/IRolePageRepository.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Repository.Interfaces +{ + public interface IRolePageRepository + { + public IEnumerable GetRolePages(); + public IEnumerable GetRolePageByRoleId(int id); + public bool InsertRolePage(List RoleId); + public bool InsertRolePage(RolePage rolePage); + public bool UpdateRolePage(RolePage rolePage); + public bool DeleteRolePage(int id); + + public IEnumerable GetRolePermissionInfo(int? roleid); + public IEnumerable GetRolePageLists(int roleid); + + public IEnumerable GetPageLists(); + public PageList GetPageListById(int id); + public bool InsertPageList(PageList company); + public bool UpdatePageList(PageList company); + public bool DeletePageList(int id); + } +} diff --git a/Traffic.Repository/Interfaces/ISiteInformationRepository.cs b/Traffic.Repository/Interfaces/ISiteInformationRepository.cs new file mode 100644 index 0000000..7fc713b --- /dev/null +++ b/Traffic.Repository/Interfaces/ISiteInformationRepository.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Repository.Interfaces +{ + public interface ISiteInformationRepository + { + public IEnumerable GetSiteInformations(); + public IEnumerable GetSiteInformations(List eventTypes); + public SiteInformation GetSiteInformationById(int id); + public SiteInformation GetSiteInformationBySiteId(string Siteid); + public bool InsertSiteInformation(SiteInformation data); + public bool UpdateSiteInformation(SiteInformation data); + public bool DeleteSiteInformation(int id); + } +} diff --git a/Traffic.Repository/Interfaces/ITycgRepository.cs b/Traffic.Repository/Interfaces/ITycgRepository.cs new file mode 100644 index 0000000..9c562eb --- /dev/null +++ b/Traffic.Repository/Interfaces/ITycgRepository.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; + +namespace Traffic.Repository.Interfaces +{ + public interface ITycgRepository + { + public IEnumerable GetTycgs(string tableName); + public IEnumerable GetTycgsTableName(); + } +} diff --git a/Traffic.Repository/Traffic.Repository.csproj b/Traffic.Repository/Traffic.Repository.csproj new file mode 100644 index 0000000..eb3f353 --- /dev/null +++ b/Traffic.Repository/Traffic.Repository.csproj @@ -0,0 +1,17 @@ + + + + net5.0 + + + + + + + + + + + + + diff --git a/Traffic.Service/Filter/LogFilter.cs b/Traffic.Service/Filter/LogFilter.cs new file mode 100644 index 0000000..b6455f7 --- /dev/null +++ b/Traffic.Service/Filter/LogFilter.cs @@ -0,0 +1,32 @@ +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace Traffic.Service.Filter +{ + public class LogFilter : IActionFilter + { + private readonly ILogger _logger; + public LogFilter(ILogger logger) + { + _logger = logger; + } + + public void OnActionExecuting(ActionExecutingContext context) + { + // Do something before the action executes. + _logger.LogDebug($"{MethodBase.GetCurrentMethod()}{context.HttpContext.Request.Path}"); + } + + public void OnActionExecuted(ActionExecutedContext context) + { + // Do something before the action executes. + _logger.LogDebug($"{MethodBase.GetCurrentMethod()}{context.HttpContext.Request.Path}"); + } + } +} diff --git a/Traffic.Service/Helpers/JwtHelpers.cs b/Traffic.Service/Helpers/JwtHelpers.cs new file mode 100644 index 0000000..3fcb382 --- /dev/null +++ b/Traffic.Service/Helpers/JwtHelpers.cs @@ -0,0 +1,89 @@ +using Microsoft.IdentityModel.Tokens; +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Text; +using System.IdentityModel.Tokens.Jwt; +using Traffic.Data.ViewModels; +using Microsoft.Extensions.Configuration; +using Traffic.Data.Enums; + +namespace Traffic.Service.Helpers +{ + public class JwtHelpers + { + private readonly IConfiguration _configuration; + + public JwtHelpers(IConfiguration configuration) + { + _configuration = configuration; + } + + public string GenerateToken(AccountUserViewModel admin, int expireDays = 30) + { + var issuer = _configuration.GetValue("JwtSettings:Issuer"); + var signKey = _configuration.GetValue("JwtSettings:SignKey"); + + // 設定要加入到 JWT Token 中的聲明資訊(Claims) + var claims = new List(); + + // 在 RFC 7519 規格中(Section#4),總共定義了 7 個預設的 Claims,我們應該只用的到兩種! + //claims.Add(new Claim(JwtRegisteredClaimNames.Iss, issuer)); + claims.Add(new Claim(JwtRegisteredClaimNames.NameId, admin.Id.ToString())); // member.Identity.Name + claims.Add(new Claim(JwtRegisteredClaimNames.Name, admin.Account.ToString())); // member.Identity.Name + claims.Add(new Claim(JwtRegisteredClaimNames.GivenName, admin.Name.ToString())); // member.Identity.Name + //claims.Add(new Claim(JwtRegisteredClaimNames.Aud, "The Audience")); + //claims.Add(new Claim(JwtRegisteredClaimNames.Exp, DateTimeOffset.UtcNow.AddMinutes(30).ToUnixTimeSeconds().ToString())); + //claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString())); // 必須為數字 + //claims.Add(new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString())); // 必須為數字 + claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); // JWT ID + + // 網路上常看到的這個 NameId 設定是多餘的 + //claims.Add(new Claim(JwtRegisteredClaimNames.NameId, memberName)); + + // 這個 Claim 也以直接被 JwtRegisteredClaimNames.Sub 取代,所以也是多餘的 + //claims.Add(new Claim(ClaimTypes.Name, memberName)); + + // 你可以自行擴充 "roles" 加入登入者該有的角色 + switch (admin.Role) + { + case (int)Auth.Admin: + claims.Add(new Claim("roles", "Admin")); + break; + case (int)Auth.User: + claims.Add(new Claim("roles", "User")); + break; + default: + break; + } + + var memberClaimsIdentity = new ClaimsIdentity(claims); + + // 建立一組對稱式加密的金鑰,主要用於 JWT 簽章之用 + var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signKey)); + + // HmacSha256 有要求必須要大於 128 bits,所以 key 不能太短,至少要 16 字元以上 + // https://stackoverflow.com/questions/47279947/idx10603-the-algorithm-hs256-requires-the-securitykey-keysize-to-be-greater + var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); + + // 建立 SecurityTokenDescriptor + var tokenDescriptor = new SecurityTokenDescriptor + { + Issuer = issuer, + //Audience = issuer, // 由於你的 API 受眾通常沒有區分特別對象,因此通常不太需要設定,也不太需要驗證 + //NotBefore = DateTime.Now, // 預設值就是 DateTime.Now + //IssuedAt = DateTime.Now, // 預設值就是 DateTime.Now + Subject = memberClaimsIdentity, + Expires = DateTime.Now.AddDays(expireDays), + SigningCredentials = signingCredentials + }; + + // 產出所需要的 JWT securityToken 物件,並取得序列化後的 Token 結果(字串格式) + var tokenHandler = new JwtSecurityTokenHandler(); + var securityToken = tokenHandler.CreateToken(tokenDescriptor); + var serializeToken = tokenHandler.WriteToken(securityToken); + + return serializeToken; + } + } +} diff --git a/Traffic.Service/Helpers/ParserForUserFromClaim.cs b/Traffic.Service/Helpers/ParserForUserFromClaim.cs new file mode 100644 index 0000000..bef7425 --- /dev/null +++ b/Traffic.Service/Helpers/ParserForUserFromClaim.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; + +namespace LiangLiSystem.Services.Helpers +{ + public class ParserForUserFromClaim + { + public ClaimsIdentity userIdentity { get; set; } + public ParserForUserFromClaim(ClaimsIdentity c) + { + userIdentity = c; + } + + public int GetUserId() + { + if (userIdentity == null) { return 0; } + + var result = userIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier); + + return Convert.ToInt16(result.FirstOrDefault().Value); + } + + public string GetUserName() + { + if (userIdentity == null) { return string.Empty; } + + var result = userIdentity.Claims.Where(c => c.Type == ClaimTypes.GivenName); + + return result.FirstOrDefault().Value.ToString(); + } + + public string GetAccount() + { + if (userIdentity == null) { return string.Empty; } + + var result = userIdentity.Claims.Where(c => c.Type == "name"); + + return result.FirstOrDefault().Value.ToString(); + } + } +} diff --git a/Traffic.Service/Helpers/Util.cs b/Traffic.Service/Helpers/Util.cs new file mode 100644 index 0000000..775386f --- /dev/null +++ b/Traffic.Service/Helpers/Util.cs @@ -0,0 +1,70 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; + +namespace LiangLiSystem.Services.Helpers +{ + public static class Util + { + public static string GetEnumDesc(Enum value) + { + FieldInfo fi = value.GetType().GetField(value.ToString()); + + DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; + + if (attributes != null && attributes.Any()) + { + return attributes.First().Description; + } + + return value.ToString(); + } + + public static DateTime GetDateTimeNow() + { + return Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); + } + public static string GetDateTimeNow(string date) + { + return Convert.ToDateTime(date).ToString("yyyy-MM-dd HH:mm:ss"); + } + + public static SearchModel GetSearchModel(SearchModelViewModel searchModel) + { + return new SearchModel + { + Term = searchModel.Term, + Page = Convert.ToInt32(string.IsNullOrWhiteSpace(searchModel.Page) ? "1" : searchModel.Page), + PageSize = Convert.ToInt32(string.IsNullOrWhiteSpace(searchModel.PageSize) ? "1" : searchModel.PageSize), + IsAsc = (searchModel.IsAsc == "true" || searchModel.IsAsc == "") ? true : false, + Order = string.IsNullOrWhiteSpace(searchModel.Order) ? "id" : searchModel.Order, + }; + } + + /// + /// #必須包含數字, #必須包含小寫字母, #必須包含大寫字母, #必須包含特殊符號, #至少8個字符,最多30個字符 + /// + /// + /// + public static bool IsValidPassword(string password) + { + var regex = new Regex(@" + (?=.*[0-9]) #必須包含數字 + (?=.*[a-z]) #必須包含小寫字母 + (?=.*[A-Z]) #必須包含大寫字母 + (?=([\x21-\x7e]+)[^a-zA-Z0-9]) #必須包含特殊符號 + .{12,30} #至少12個字符,最多30個字符 + ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace); + + return regex.Match(password).Success; + } + } +} diff --git a/Traffic.Service/Implements/AccountService.cs b/Traffic.Service/Implements/AccountService.cs new file mode 100644 index 0000000..f224e21 --- /dev/null +++ b/Traffic.Service/Implements/AccountService.cs @@ -0,0 +1,573 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.Extensions.Logging; +using Omu.ValueInjecter; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Enums; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class AccountService : IAccountService + { + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + public AccountService(IUnitOfWork unitOfWork, ILogger logger) + { + _unitOfWork = unitOfWork; + _logger = logger; + } + + public AccountUserViewModel GetAccountUser(int id) + { + try + { + //user + var user = _unitOfWork.AccountRepository.GetAccountUserById(id); + _logger.LogError($"GetAccountUser user id = {id}"); + if (user == null) + { + _logger.LogError($"GetAccountUser user id = {id} is null"); + return null; + } + + //station + var station = _unitOfWork.PoliceStationRepository.GetPoliceStationById(user.PoliceStationId); + if (station == null) + { + _logger.LogError($"GetAccountUser station = {user.PoliceStationId} is null"); + return null; + } + + var policeStationViewModel = new PoliceStationViewModel + { + Id = station.Id, + StationName = station.StationName, + Area = station.Area + }; + + //site + var sites = _unitOfWork.AccountRepository.GetAccountUserSite(id); + if (sites == null) + { + _logger.LogError($"GetAccountUser sites is null"); + return null; + } + var sitesViewModel = new List(); + var siteInfo = _unitOfWork.SiteInformationRepository.GetSiteInformations(); + foreach (var item in sites) + { + var siteVM = new UserSiteViewModel + { + Id = item.Id, + SiteId = siteInfo.FirstOrDefault(i => i.Id == item.SiteId).SiteID, + SiteName = siteInfo.FirstOrDefault(i => i.Id == item.SiteId).SiteName + }; + sitesViewModel.Add(siteVM); + } + + return new AccountUserViewModel + { + Id = id, + Account = user.Account, + Name = user.UserName, + Email = user.Email, + Phone = user.PhoneNumber, + Role = user.RoleCodeId, + PoliceStation = policeStationViewModel, + Site = sitesViewModel, + Status = user.Status + }; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new AccountUserViewModel(); + } + } + + public bool GetExistUser(string account) + { + try + { + var user = _unitOfWork.AccountRepository.GetAccountUserByAccount(account); + return user != null; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return false; + } + } + + public TradeResultModel InserAccountUser(int byWho, UserData account) + { + var result = new TradeResultModel { Success = false }; + try + { + SHA256 sha256 = new SHA256CryptoServiceProvider();//建立一個SHA256 + byte[] source = Encoding.Default.GetBytes("000000");//將字串轉為Byte[] + byte[] crypto = sha256.ComputeHash(source);//進行SHA256加密 + var accountUser = new AccountUser + { + Password = Convert.ToBase64String(crypto),//把加密後的字串從Byte[]轉為字串 + Account = account.Account, + UserName = account.UserName, + Email = account.Email, + PhoneNumber = account.PhoneNumber, + CreatorId = byWho, + CreatedOn = Util.GetDateTimeNow(), + RoleCodeId = account.RoleCode_Id, + PoliceStationId = account.GroupCode_Id, + ChangePwdOn = Util.GetDateTimeNow(), + }; + + var id = _unitOfWork.AccountRepository.InsertAccountUser(accountUser); + + var sites = new List(); + foreach (var item in account.Site_Id) + { + var site = new AccountUserSite + { + UserId = id, + SiteId = item + }; + sites.Add(site); + } + + bool isSuccess = _unitOfWork.AccountRepository.InsertAccountUserSite(sites); + _unitOfWork.Complete(); + result.Success = isSuccess; + return result; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + result.Message = ex.Message; + _logger.LogError(ex.Message); + return result; + } + } + + public PageViewModel> GetUserDataList(SearchModel searchModel, int? userId) + { + try + { + var sql = _unitOfWork.AccountRepository.GetAccountUsers(); + if (!string.IsNullOrEmpty(searchModel.Term)) + { + sql = sql.Where(x => x.Account.Contains(searchModel.Term) || x.UserName.Contains(searchModel.Term)); + } + + if (userId != null) + { + sql = sql.Where(x => userId == x.Id); + } + + int count = -1; + int pageCount = -1; + if (searchModel.Page == 1) + { + count = sql.Count(); + if (count % 10 != 0) + { + pageCount = (count / searchModel.PageSize) + 1; + } + else + { + pageCount = count / searchModel.PageSize; + } + } + switch (searchModel.Order) + { + case "Id": + sql = searchModel.IsAsc ? sql.OrderBy(x => x.Id) : sql.OrderByDescending(x => x.Id); + break; + case "Account": + sql = searchModel.IsAsc ? sql.OrderBy(x => x.Account).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.Account).ThenByDescending(x => x.Id); + break; + case "UserName": + sql = searchModel.IsAsc ? sql.OrderBy(x => x.UserName).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.Account).ThenByDescending(x => x.Id); + break; + case "GroupCodeId": + sql = searchModel.IsAsc ? sql.OrderBy(x => x.PoliceStationId).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.PoliceStationId).ThenByDescending(x => x.Id); + break; + case "RoleCodeId": + sql = searchModel.IsAsc ? sql.OrderBy(x => x.RoleCodeId).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.RoleCodeId).ThenByDescending(x => x.Id); + break; + default: + goto case "Id"; + } + + //station + var stations = _unitOfWork.PoliceStationRepository.GetPoliceStations(); + var stationsViewModel = new List(); + foreach (var item in stations) + { + var policeStationViewModel = new PoliceStationViewModel + { + Id = item.Id, + Area = item.Area, + StationName = item.StationName, + }; + stationsViewModel.Add(policeStationViewModel); + } + + //site + var sites = _unitOfWork.AccountRepository.GetAccountUserSites(); + if (sites == null) + { + _logger.LogError($"GetAccountUser sites is null"); + return null; + } + var sitesViewModel = new List(); + var siteInfo = _unitOfWork.SiteInformationRepository.GetSiteInformations(); + foreach (var item in sites) + { + var siteVM = new UserSiteViewModel + { + Id = item.SiteId, + SiteId = siteInfo.FirstOrDefault(i => i.Id == item.SiteId).SiteID, + SiteName = siteInfo.FirstOrDefault(i => i.Id == item.SiteId).SiteName + }; + sitesViewModel.Add(siteVM); + } + + sql = sql.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var data = sql.ToList().Select(x => new UserDataQuery + { + Id = x.Id, + Account = x.Account, + UserName = x.UserName, + Email = x.Email, + PhoneNumber = x.PhoneNumber, + GroupCode_Id = x.PoliceStationId, + RoleCode_Id = x.RoleCodeId, + CreatorId = x.CreatorId.ToString(), + CreatedOn = x.CreatedOn.ToString(), + PoliceStation = stationsViewModel.FirstOrDefault(i => i.Id == x.PoliceStationId), + Status = x.Status, + Site = sites.Where(i => i.UserId == x.Id).Select(y => new UserSiteViewModel + { + Id = y.SiteId, + SiteId = siteInfo.FirstOrDefault(i => i.Id == y.SiteId).SiteID, + SiteName = siteInfo.FirstOrDefault(i => i.Id == y.SiteId).SiteName + }).ToList() + }); + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = data, + }; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + + public TradeResultModel UpdateAccountbyAdmin(int byWho, UserData account) + { + var result = new TradeResultModel { Success = false }; + try + { + var accountUser = new AccountUser + { + Id = account.Id, + Account = account.Account, + UserName = account.UserName, + Email = account.Email, + PhoneNumber = account.PhoneNumber, + PoliceStationId = account.GroupCode_Id, + RoleCodeId = account.RoleCode_Id, + UpdatorId = byWho, + UpdatedOn = Util.GetDateTimeNow(), + }; + + var sites = new List(); + foreach (var item in account.Site_Id) + { + var site = new AccountUserSite + { + UserId = account.Id, + SiteId = item + }; + sites.Add(site); + } + _unitOfWork.AccountRepository.DeleteUserSite(account.Id); + _unitOfWork.AccountRepository.InsertAccountUserSite(sites); + + var IsSuccess = _unitOfWork.AccountRepository.UpdateAccountUserbyAdmin(accountUser); + if (IsSuccess) + { + _unitOfWork.Complete(); + } + else + { + _unitOfWork.Rollback(); + } + result.Success = IsSuccess; + return result; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + result.Message = ex.Message; + _logger.LogError(ex.Message); + return result; + } + } + + public TradeResultModel UpdateAccountbyUser(int byWho, UserData account) + { + var result = new TradeResultModel { Success = false }; + try + { + var accountUser = new AccountUser + { + Id = byWho, + UserName = account.UserName, + Email = account.Email, + PhoneNumber = account.PhoneNumber, + UpdatorId = byWho, + UpdatedOn = Util.GetDateTimeNow(), + }; + + var IsSuccess = _unitOfWork.AccountRepository.UpdateAccountUserbyUser(accountUser); + if (IsSuccess) + { + _unitOfWork.Complete(); + } + else + { + _unitOfWork.Rollback(); + } + result.Success = IsSuccess; + return result; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + result.Message = ex.Message; + _logger.LogError(ex.Message); + return result; + } + } + + public TradeResultModel UpdateAccountPasswordbyAdmin(int id, int byWho) + { + var result = new TradeResultModel { Success = false }; + SHA256 sha256 = new SHA256CryptoServiceProvider(); + byte[] source = Encoding.Default.GetBytes("000000"); + byte[] crypto = sha256.ComputeHash(source); + var newPassword = Convert.ToBase64String(crypto); + + try + { + var account = _unitOfWork.AccountRepository.GetAccountUserById(id); + if (account != null) + { + _unitOfWork.AccountRepository.UpdateAccountUserPasswordByAdmin(id, newPassword, byWho, Util.GetDateTimeNow()); + _unitOfWork.Complete(); + result.Success = true; + } + else + { + result.Success = false; + result.Message = "No This User"; + } + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + result.Message = ex.Message; + _logger.LogError(ex.Message); + return result; + } + return result; + } + + public TradeResultModel UpdateAccountPasswordByUser(int ByWho, UserData accountViewModel) + { + var result = new TradeResultModel { Success = false }; + var pwdTimes = _unitOfWork.AccountRepository.GetAccountPwdTop3(accountViewModel.Account); + if (!Util.IsValidPassword(accountViewModel.NewPassword)) + { + result.Success = false; + result.Message = "Please enter a valid password"; + } + else + { + SHA256 sha256 = new SHA256CryptoServiceProvider(); + byte[] source = Encoding.Default.GetBytes(accountViewModel.Password); + byte[] crypto = sha256.ComputeHash(source); + var oldPassword = Convert.ToBase64String(crypto); + + SHA256 newSha256 = new SHA256CryptoServiceProvider(); + byte[] newSource = Encoding.Default.GetBytes(accountViewModel.NewPassword); + byte[] newCrypto = newSha256.ComputeHash(newSource); + var newPassword = Convert.ToBase64String(newCrypto); + + try + { + var account = _unitOfWork.AccountRepository.GetAccountUserById(accountViewModel.Id); + + if (account == null || account.Password != oldPassword) + { + result.Success = false; + result.Message = "wrong password"; + } + else if (pwdTimes.Any(i => i.Password == newPassword)) + { + result.Success = false; + result.Message = "修改密碼不可以與前三次相同"; + } + else + { + var createOn = Util.GetDateTimeNow(); + _unitOfWork.AccountRepository.UpdateAccountUserPasswordByUser(ByWho, oldPassword, newPassword, createOn); + _unitOfWork.AccountRepository.InsertAccountPwd(new AccountPwd() { Account = account.Account, Password = newPassword, CreatedOn = createOn }); + _unitOfWork.Complete(); + result.Success = true; + } + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + result.Message = ex.Message; + _logger.LogError(ex.Message); + return result; + } + } + return result; + } + + public IEnumerable GetUserNameList() + { + try + { + var data = _unitOfWork.AccountRepository.GetAccountUsers().Select(x => new UserNameList + { + Id = x.Id, + UserName = x.UserName, + Email = x.Email + }); + + return data; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new List(); + } + } + + public TradeResultModel DeleteUserData(int id) + { + var result = new TradeResultModel { Success = false }; + try + { + var data = _unitOfWork.AccountRepository.GetAccountUserById(id); + if (data != null) + { + _unitOfWork.AccountRepository.DeleteUser(id); + _unitOfWork.Complete(); + } + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + result.Message = ex.Message; + _logger.LogError(ex.Message); + return result; + } + result.Success = true; + return result; + } + + public TradeResultModel PutUserbyAdmin(int byWho, int id, int status) + { + var result = new TradeResultModel { Success = false }; + try + { + var isSuccess = _unitOfWork.AccountRepository.DisableUser(byWho, id, status); + if (!isSuccess) + { + result.Success = false; + result.Message = "修改失敗"; + return result; + } + + _unitOfWork.Complete(); + result.Success = true; + return result; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + result.Message = ex.Message; + _logger.LogError(ex.Message); + return result; + } + } + + public IEnumerable GetUserSite(int id) + { + try + { + var siteInfo = _unitOfWork.SiteInformationRepository.GetSiteInformations(); + var datas = _unitOfWork.AccountRepository.GetAccountUserSite(id); + + var result = new List(); + foreach (var site in datas) + { + result.Add(siteInfo.FirstOrDefault(s => s.Id == site.SiteId).SiteName); + } + return result; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new List(); + } + } + + public IEnumerable GetUserSiteInfo(int id) + { + try + { + var siteInfo = _unitOfWork.SiteInformationRepository.GetSiteInformations(); + var datas = _unitOfWork.AccountRepository.GetAccountUserSite(id); + + var result = new List(); + foreach (var site in datas) + { + var s = siteInfo.FirstOrDefault(s => s.Id == site.SiteId); + var siteViewModel = new UserSiteInformationViewModel(); + siteViewModel.InjectFrom(s); + siteViewModel.Id = site.Id; + + result.Add(siteViewModel); + } + return result; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new List(); + } + } + } +} diff --git a/Traffic.Service/Implements/AnnounceService.cs b/Traffic.Service/Implements/AnnounceService.cs new file mode 100644 index 0000000..7819b21 --- /dev/null +++ b/Traffic.Service/Implements/AnnounceService.cs @@ -0,0 +1,186 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class AnnounceService : IAnnounceService + { + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + public AnnounceService(IUnitOfWork unitOfWork, ILogger logger) + { + _unitOfWork = unitOfWork; + _logger = logger; + } + + public PageViewModel> GetAnnounces(SearchModel searchModel) + { + try + { + var announce = _unitOfWork.AnnounceRepository.GetAnnounces(); + + if (!string.IsNullOrEmpty(searchModel.Term)) + { + announce = announce.Where(x => x.Title.Contains(searchModel.Term)); + } + + int count = announce.Count(); + int pageCount = count % searchModel.PageSize != 0 ? (count / searchModel.PageSize) + 1 : count / searchModel.PageSize; + + switch (searchModel.Order.ToLower()) + { + case "id": + default: + announce = searchModel.IsAsc ? announce.OrderBy(x => x.Id) : announce.OrderByDescending(x => x.Id); + break; + case "starton": + announce = searchModel.IsAsc ? announce.OrderBy(x => x.StartOn).ThenBy(x => x.Id) : announce.OrderByDescending(x => x.StartOn).ThenByDescending(x => x.Id); + break; + case "status": + announce = searchModel.IsAsc ? announce.OrderBy(x => x.Status).ThenBy(x => x.Id) : announce.OrderByDescending(x => x.Status).ThenByDescending(x => x.Id); + break; + } + + announce = announce.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var data = announce.ToList().Select(x => new AnnounceViewModel + { + Id = x.Id, + Title = x.Title, + Content = x.Content, + StartOn = x.StartOn.ToString("yyyy-MM-dd HH:mm:ss"), + Status = x.Status, + CreatorId = x.CreatorId, + CreatedOn = x.CreatedOn, + UpdatorId = x.UpdatorId, + UpdatedOn = x.UpdatedOn, + }); + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = data, + }; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new PageViewModel>(); + } + } + + public AnnounceViewModel GetAnnounceById(int id) + { + try + { + var data = _unitOfWork.AnnounceRepository.GetAnnounceById(id); + if (data != null) + { + return new AnnounceViewModel + { + Id = data.Id, + Title = data.Title, + Content = data.Content, + StartOn = data.StartOn.ToString("yyyy-MM-dd HH:mm:ss"), + Status = data.Status, + CreatorId = data.CreatorId, + CreatedOn = data.CreatedOn, + UpdatorId = data.UpdatorId, + UpdatedOn = data.UpdatedOn, + }; + } + else + { + return null; + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new AnnounceViewModel(); + } + } + + public TradeResultModel InsertAnnounce(int byWho, AnnounceInsertViewModel viewModel) + { + try + { + var data = new Announce + { + Title = viewModel.Title, + Content = viewModel.Content, + StartOn = Convert.ToDateTime(viewModel.StartOn), + Status = viewModel.Status, + CreatorId = byWho, + CreatedOn = DateTime.Now + }; + + var result = _unitOfWork.AnnounceRepository.InsertAnnounce(data); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "新增成功" : "新增失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatAnnounce(int id, AnnounceInsertViewModel viewModel, int byWho) + { + try + { + var data = new Announce + { + Id = id, + Title = viewModel.Title, + Content = viewModel.Content, + StartOn = Convert.ToDateTime(viewModel.StartOn), + Status = viewModel.Status, + UpdatorId = byWho, + UpdatedOn = DateTime.Now, + }; + + var result = _unitOfWork.AnnounceRepository.UpdateAnnounce(data); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel DeleteAnnounce(int id) + { + try + { + var result = _unitOfWork.AnnounceRepository.DeleteAnnounce(id); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "刪除成功" : "刪除失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + } +} diff --git a/Traffic.Service/Implements/CompanyInformationService.cs b/Traffic.Service/Implements/CompanyInformationService.cs new file mode 100644 index 0000000..00a3509 --- /dev/null +++ b/Traffic.Service/Implements/CompanyInformationService.cs @@ -0,0 +1,203 @@ +using Microsoft.Extensions.Logging; +using Omu.ValueInjecter; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class CompanyInformationService : ICompanyInformationService + { + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + public CompanyInformationService(IUnitOfWork unitOfWork, ILogger logger) + { + _unitOfWork = unitOfWork; + _logger = logger; + } + + public IEnumerable GetCompanyInformations() + { + var datas = _unitOfWork.CompanyInformationRepository.GetCompanyInformations(); + var result = new List(); + foreach (var data in datas) + { + var vm = new CompanyInformationViewModel(); + vm.InjectFrom(data); + vm.Id = data.Id; + result.Add(vm); + } + + return result; + } + + + public IEnumerable GetCompanyInformationsEmailNotNull() + { + var datas = _unitOfWork.CompanyInformationRepository.GetCompanyInformations(); + var result = new List(); + foreach (var data in datas) + { + var vm = new CompanyInformationViewModel(); + vm.InjectFrom(data); + vm.Id = data.Id; + result.Add(vm); + } + + return result.Where(i => !string.IsNullOrWhiteSpace(i.Email)); + } + + public PageViewModel> GetCompanyInformations(SearchModel searchModel) + { + try + { + + var company = _unitOfWork.CompanyInformationRepository.GetCompanyInformations(); + + if (!string.IsNullOrEmpty(searchModel.Term)) + { + company = company.Where(x => x.CompanyCode.Contains(searchModel.Term) || x.CompanyName.Contains(searchModel.Term)); + } + + int count = company.Count(); + int pageCount = count % searchModel.PageSize != 0 ? (count / searchModel.PageSize) + 1 : count / searchModel.PageSize; + + switch (searchModel.Order.ToLower()) + { + case "id": + default: + company = searchModel.IsAsc ? company.OrderBy(x => x.Id) : company.OrderByDescending(x => x.Id); + break; + case "companycode": + company = searchModel.IsAsc ? company.OrderBy(x => x.CompanyCode).ThenBy(x => x.Id) : company.OrderByDescending(x => x.CompanyCode).ThenByDescending(x => x.Id); + break; + case "companyname": + company = searchModel.IsAsc ? company.OrderBy(x => x.CompanyName).ThenBy(x => x.Id) : company.OrderByDescending(x => x.CompanyName).ThenByDescending(x => x.Id); + break; + } + + company = company.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var data = company.ToList().Select(x => new CompanyInformation + { + Id = x.Id, + CompanyCode = x.CompanyCode, + CompanyName = x.CompanyName, + Email = x.Email + }); + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = data, + }; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new PageViewModel>(); + } + } + + public CompanyInformationViewModel GetCompanyInformationById(int id) + { + try + { + var company = _unitOfWork.CompanyInformationRepository.GetCompanyInformationById(id); + if (company != null) + { + return new CompanyInformationViewModel + { + Id = company.Id, + CompanyCode = company.CompanyCode, + CompanyName = company.CompanyName, + Email = company.Email, + }; + } + else + { + return null; + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + + public TradeResultModel InsertCompanyInformation(CompanyInformationViewModel CompanyInformation) + { + try + { + var company = new CompanyInformation + { + CompanyName = CompanyInformation.CompanyName, + CompanyCode = CompanyInformation.CompanyCode, + Email = CompanyInformation.Email, + }; + + var result = _unitOfWork.CompanyInformationRepository.InsertCompanyInformation(company); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "新增成功" : "新增失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatCompanyInformation(int id, CompanyInformationViewModel CompanyInformation) + { + try + { + var company = new CompanyInformation + { + Id = id, + CompanyName = CompanyInformation.CompanyName, + CompanyCode = CompanyInformation.CompanyCode, + Email = CompanyInformation.Email, + }; + + var result = _unitOfWork.CompanyInformationRepository.UpdateCompanyInformation(company); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel DeleteCompanyInformation(int id) + { + try + { + var result = _unitOfWork.CompanyInformationRepository.DeleteCompanyInformation(id); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "刪除成功" : "刪除失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + } +} diff --git a/Traffic.Service/Implements/EventService.cs b/Traffic.Service/Implements/EventService.cs new file mode 100644 index 0000000..baaec6f --- /dev/null +++ b/Traffic.Service/Implements/EventService.cs @@ -0,0 +1,951 @@ +using LiangLiSystem.Services.Helpers; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Omu.ValueInjecter; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class EventService : IEventService + { + private readonly IConfiguration _configuration; + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + public EventService(IConfiguration configuration, IUnitOfWork unitOfWork, ILogger logger) + { + _configuration = configuration; + _unitOfWork = unitOfWork; + _logger = logger; + } + + public PageViewModel> GetEventsByCar(SearchModel searchModel) + { + try + { + var number = $"%{searchModel.Term}%"; + var datas = _unitOfWork.EventRepository.GetEventsByCar(number); + var sites = _unitOfWork.SiteInformationRepository.GetSiteInformations(); + var eventTypes = _unitOfWork.EventTypeRepository.GetEventTypes(); + + var count = datas.Count(); + int pageCount = count % searchModel.PageSize != 0 ? (count / searchModel.PageSize) + 1 : count / searchModel.PageSize; + switch (searchModel.Order.ToLower()) + { + case "id": + default: + datas = searchModel.IsAsc ? datas.OrderBy(x => x.Id) : datas.OrderByDescending(x => x.Id); + break; + case "number": + datas = searchModel.IsAsc ? datas.OrderBy(x => x.Number).ThenBy(x => x.Id) : datas.OrderByDescending(x => x.Number).ThenByDescending(x => x.Id); + break; + case "siteid": + datas = searchModel.IsAsc ? datas.OrderBy(x => x.SiteID).ThenBy(x => x.Id) : datas.OrderByDescending(x => x.SiteID).ThenByDescending(x => x.Id); + break; + case "eventtype": + datas = searchModel.IsAsc ? datas.OrderBy(x => x.EventType).ThenBy(x => x.Id) : datas.OrderByDescending(x => x.EventType).ThenByDescending(x => x.Id); + break; + case "intime": + datas = searchModel.IsAsc ? datas.OrderBy(x => Convert.ToDateTime(x.InTime)).ThenBy(x => x.Id) : datas.OrderByDescending(x => Convert.ToDateTime(x.InTime)).ThenByDescending(x => x.Id); + break; + } + datas = datas.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var result = new List(); + foreach (var data in datas) + { + var vm = new EventSearchByNumberViewModel(); + vm.Id = data.Id; + vm.Number = data.Number; + vm.InTime = Convert.ToDateTime(data.InTime).ToString("yyyy-MM-dd HH:mm:ss"); + vm.SiteName = sites.FirstOrDefault(i => i.SiteID == data.SiteID).SiteName; + vm.EventName = eventTypes.FirstOrDefault(i => i.EventType == sites.FirstOrDefault(i => i.SiteID == data.SiteID).EventType).EventName; + if (data.Punished == "1") + { + vm.Status = "已開單"; + } + else if (data.Rejected == "1") + { + vm.Status = "不開單"; + } + else if (data.CheckPunish == "1") + { + vm.Status = "開單處理中"; + } + else + { + vm.Status = "未處理"; + } + result.Add(vm); + } + + if (searchModel.Order.ToLower() == "status") + { + result = searchModel.IsAsc ? result.OrderBy(x => x.Status).ThenBy(x => x.Id).ToList() : result.OrderByDescending(x => x.Status).ThenByDescending(x => x.Id).ToList(); + } + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = result, + }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new PageViewModel>(); + } + } + + public IEnumerable GetEventsByEventType(int userId, string eventType, string startTime, string endTime, string site, string status, string time, string speed) + { + try + { + _logger.LogInformation("GetEventsByEventType Init"); + _logger.LogInformation($"GetEventsByEventType userId ={userId}"); + _logger.LogInformation($"GetEventsByEventType eventType ={eventType}"); + _logger.LogInformation($"GetEventsByEventType startTime ={startTime}"); + _logger.LogInformation($"GetEventsByEventType endTime ={endTime}"); + _logger.LogInformation($"GetEventsByEventType site ={site}"); + + var punishCount = Convert.ToInt16(_configuration["EventStatus:Count"]); + var dataCount = _unitOfWork.EventRepository.GetEventByTimeCount(startTime, endTime); + if (dataCount >= punishCount) + { + return null; + } + + //異常車牌 + var data = _unitOfWork.EventRepository.GetEventByTime(startTime, endTime); + var userSite = _unitOfWork.AccountRepository.GetAccountUserSite(userId); + var sites = new List(); + foreach (var item in userSite) + { + var sitedata = _unitOfWork.SiteInformationRepository.GetSiteInformationById(item.SiteId); + sites.Add(sitedata); + } + sites = sites.Where(i => i.EventType == eventType).ToList(); + + data = data.Where(i => sites.Any(j => j.SiteID == i.SiteID)); + + _logger.LogInformation($"GetEventJoinSiteAndUsers Data.count = {data.Count()}"); + + if (eventType == "1") + { + data = data.Where(i => Convert.ToDateTime(i.InTime).Hour >= 6); + } + + _logger.LogInformation($"GetEventJoinSiteAndUsers Convert.ToDateTime(i.InTime).Hour >= 6 Data.count = {data.Count()}"); + + var exceptionNumbers = _unitOfWork.EventRepository.GetExceptionNumbers(); + + data = data.Where(i => ShowThisEvent(exceptionNumbers, i) == true); + + if (site != "ALL") + { + data = data.Where(i => i.SiteID == site); + } + + if (time != "ALL") + { + if (time == "1") + { + data = data.Where(i => (Convert.ToDateTime(i.OutTime) - Convert.ToDateTime(i.InTime)).TotalSeconds >= 70 && (Convert.ToDateTime(i.OutTime) - Convert.ToDateTime(i.InTime)).TotalSeconds < 190); + } + else if (time == "3") + { + data = data.Where(i => (Convert.ToDateTime(i.OutTime) - Convert.ToDateTime(i.InTime)).TotalSeconds >= 190); + } + } + + if (speed != "ALL") + { + data = data.Where(i => Convert.ToDouble(i.Speed) >= Convert.ToDouble(speed)); + } + + if (status == "未開單") + { + data = data.Where(i => i.Punished == "0" && i.Rejected == "0" && i.CheckPunish == "0" && string.IsNullOrWhiteSpace(i.Ps)); + } + else if (status == "已退回") + { + data = data.Where(i => i.Rejected == "1"); + } + else if (status == "裁決中") + { + data = data.Where(i => i.CheckPunish == "1"); + } + else if (status == "已開罰") + { + data = data.Where(i => i.Punished == "1"); + } + else if (status == "不開單") + { + data = data.Where(i => i.Punished == "0" && i.Rejected == "0" && i.CheckPunish == "0" && !string.IsNullOrWhiteSpace(i.Ps)); + } + + _logger.LogInformation($"GetEventJoinSiteAndUsers All condition Data.count = {data.Count()}"); + var cars = _unitOfWork.EventRepository.GetVehicleType(); + var eventTypes = _unitOfWork.EventTypeRepository.GetEventTypes(); + var result = new List(); + foreach (var x in data.ToList()) + { + var sitedata = sites.FirstOrDefault(i => i.SiteID == x.SiteID); + var vm = new JoinEventSiteAndUserViewModel + { + Id = x.Id, + UserID = userId.ToString(), + SiteId = x.SiteID, + SiteName = sitedata.SiteName, + Account = x.Account, + Area = sitedata.Area, + County = sitedata.County, + EventName = eventTypes.Any(i => i.EventType == x.EventType) ? eventTypes.FirstOrDefault(i => i.EventType == x.EventType).EventName : "", + CheckPunish = x.CheckPunish, + HandlingTime = x.HandlingTime, + Laws = GetLawsCodes(sitedata.Laws), + UploadTime = x.UploadTime, + VehicleName = cars.Any(i => i.VehicleType == x.VehicleType) ? cars.FirstOrDefault(i => i.VehicleType == x.VehicleType).VehicleName : "", + Ps = x.Ps, + InTime = x.InTime, + OutTime = x.OutTime, + Punished = x.Punished, + Rejected = x.Rejected, + IMGPath1 = x.IMGPath1.Replace("carviolation.tycg.gov.tw:8443", "172.16.1.49:8443"), + //IMGPath2 = x.IMGPath2, + //IMGPath3 = x.IMGPath3, + //IMGPath4 = x.IMGPath4, + //IMGPath5 = x.IMGPath5, + //IMGPath6 = x.IMGPath6, + VideoPath1 = x.VideoPath1.Replace("carviolation.tycg.gov.tw:8443", "172.16.1.49:8443"), + //VideoPath2 = x.VideoPath2, + IMGList = GetFiles(x.IMGPath1.Replace("carviolation.tycg.gov.tw:8443", "172.16.1.49:8443"), _configuration["EventStatus:ImagePath"], x.SiteID, x.EventID), + VideoList = GetFiles(x.VideoPath1.Replace("carviolation.tycg.gov.tw:8443", "172.16.1.49:8443"), _configuration["EventStatus:VideoPath"], x.SiteID, x.EventID), + Number = x.Number, + AlarmTime = x.AlarmTime, + Channel = x.Channel, + CompanyCode = x.CompanyCode, + Distance = x.Distance, + EventID = x.EventID, + EventType = x.EventType, + IsStay = x.IsStay, + LimitTon = x.LimitTon, + LPRTime = x.LPRTime, + //PlateNumber = x.PlateNumber, + Slot = x.Slot, + Speed = x.Speed, + Ton = x.Ton, + TotalPassTime = x.TotalPassTime, + Unsure = x.Unsure, + VehicleType = x.VehicleType, + Status = GetStatus(x) + }; + result.Add(vm); + } + + return result; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new List(); + } + } + + private List GetLawsCodes(string law) + { + try + { + if (string.IsNullOrWhiteSpace(law)) + { + return null; + } + var codes = new List(); + foreach (var item in law.Split(',')) + { + var key = new LawsCodes(); + key.LawsCode = item; + codes.Add(key); + } + return codes; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + + private static bool ShowThisEvent(IEnumerable exceptionNumber, Event joinEventSiteAndUser) + { + var date = Convert.ToDateTime(joinEventSiteAndUser.InTime).ToString("yyyy-MM-dd"); + var result = exceptionNumber.Where(i => i.Number == joinEventSiteAndUser.Number && date == i.Date); + if (result.Any()) + { + return false; + } + else + { + return true; + } + } + + public List GetFiles(string url, string path, string siteID, string eventID) + { + try + { + if (_configuration["Mode:IsTest"] == "True") + { + var result = new List + { + url + "/event1.jpg", + url + "/event2.jpg", + url + "/event3.jpg", + url + "/event4.jpg", + url + "/event5.jpg", + url + "/event6.jpg" + }; + return result; + } + else + { + //取得圖片的路徑 + var folder = new DirectoryInfo($"{path}/{siteID}/{eventID}"); + //取得圖片路徑底下有多少 Image + var files = folder.GetFiles(); + var result = new List(); + foreach (var item in files) + { + result.Add(url + "/" + item.Name); + } + return result; + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + + public PageViewModel> GetEventByEventType(int userId, string eventType, SearchModel searchModel) + { + throw new NotImplementedException(); + } + + private static string GetStatus(Event data) + { + if (data.Punished == "1") + { + return "已開罰"; + } + else if (data.Rejected == "1") + { + return "已退回"; + } + else if (data.CheckPunish == "1") + { + return "裁決中"; + } + else if (data.Punished == "0" && data.Rejected == "0" && data.CheckPunish == "0" && !string.IsNullOrWhiteSpace(data.Ps)) + { + return "不開單"; + } + else + { + return "未開單"; + } + } + + public PageViewModel> GetEventBySites(string siteId, SearchModel searchModel) + { + try + { + var count = _unitOfWork.EventRepository.GetEventBySitesCount(siteId, searchModel.Term); + var datas = _unitOfWork.EventRepository.GetEventBySites(siteId, searchModel.Page, searchModel.PageSize); + var cars = _unitOfWork.EventRepository.GetVehicleType(); + + int pageCount = count % searchModel.PageSize != 0 ? (count / searchModel.PageSize) + 1 : count / searchModel.PageSize; + + switch (searchModel.Order.ToLower()) + { + case "id": + default: + datas = searchModel.IsAsc ? datas.OrderBy(x => x.Id) : datas.OrderByDescending(x => x.Id); + break; + case "siteid": + datas = searchModel.IsAsc ? datas.OrderBy(x => x.SiteID).ThenBy(x => x.Id) : datas.OrderByDescending(x => x.SiteID).ThenByDescending(x => x.Id); + break; + } + + datas = datas.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var result = new List(); + foreach (var data in datas) + { + var vm = new EventViewModel(); + vm.InjectFrom(data); + vm.Id = data.Id; + vm.VehicleName = cars.FirstOrDefault(x => x.VehicleType == vm.VehicleType).VehicleName; + result.Add(vm); + } + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = result, + }; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new PageViewModel>(); + } + } + + public EventViewModel GetEventById(int id) + { + try + { + var data = _unitOfWork.EventRepository.GetEventById(id); + var cars = _unitOfWork.EventRepository.GetVehicleTypebyType(data.VehicleType); + if (data != null) + { + var result = new EventViewModel(); + result.InjectFrom(data); + result.Id = data.Id; + result.VehicleName = cars.VehicleName; + return result; + } + else + { + return null; + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + + public int GetThisYearEventsCount(string account) + { + try + { + var thisYearStart = $"{DateTime.Now.Year}-01-01 00:00:00"; + var thisYearEnd = $"{DateTime.Now.Year}-12-31 23:59:59"; + var count = _unitOfWork.EventRepository.GetThisYearEventsCount(thisYearStart, thisYearEnd, account); + return count; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return 0; + } + } + + public int GetThisMonthEventsCount(string account) + { + try + { + var thisMonthStart = $"{DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd")} 00:00:00"; + var thisMonthEnd = $"{DateTime.Now.AddMonths(1).AddDays(-DateTime.Now.AddMonths(1).Day).ToString("yyyy-MM-dd")} 23:59:59"; + var count = _unitOfWork.EventRepository.GetThisMonthEventsCount(thisMonthStart, thisMonthEnd, account); + return count; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return 0; + } + } + + public EventCountViewModel GetEventsCount(string startDatetime, string endDatetime) + { + try + { + var datas = _unitOfWork.EventRepository.GetEvents(startDatetime, endDatetime); + var TotalCount = datas.Count(); + var PunishedCount = datas.Where(i => i.Punished == "1").Count(); + var CheckPunishedCount = datas.Where(i => i.CheckPunish == "1").Count(); + var IsStayCount = datas.Where(i => i.IsStay == "1").Count(); + var UnsureCount = datas.Where(i => i.Unsure == "1").Count(); + var RejectedCount = datas.Where(i => i.Rejected == "1").Count(); + var NoStatusCount = datas. + Where(i => i.Rejected == "0" && i.Unsure == "0" && i.IsStay == "0" && i.CheckPunish == "0" && i.Punished == "0").Count(); + + var NoPunishedCount = datas.Where(i => i.Rejected == "0" && i.Unsure == "0" && i.IsStay == "0" && i.CheckPunish == "0" && i.Punished == "0" && !string.IsNullOrWhiteSpace(i.Ps)).Count(); + var result = new EventCountViewModel() + { + TotalCount = TotalCount, + CheckPunishedCount = CheckPunishedCount, + IsStayCount = IsStayCount, + PunishedCount = PunishedCount, + UnsureCount = UnsureCount, + RejectedCount = RejectedCount, + NoStatusCount = NoStatusCount, + NoPunishedCount = NoPunishedCount + }; + + return result; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new EventCountViewModel(); + } + } + + public TradeResultModel InsertEvent(EventViewModel viewModel) + { + try + { + var data = new Event(); + data.InjectFrom(viewModel); + + var result = _unitOfWork.EventRepository.InsertEvent(data); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "新增成功" : "新增失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatEvent(int id, EventViewModel viewModel) + { + try + { + var data = new Event(); + data.InjectFrom(viewModel); + data.Id = id; + var result = _unitOfWork.EventRepository.UpdateEvent(data); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatEventCheckPunish(string account, int eventId, string checkPunish, string law) + { + try + { + var data = _unitOfWork.EventRepository.GetEventById(eventId); + if (data == null) + { + return new TradeResultModel { Success = false, Message = "查無此案件" }; + } + + if (data.Rejected == "1") + { + return new TradeResultModel { Success = false, Message = "此案件的狀態為不開罰" }; + } + + if (data.Punished == "1") + { + return new TradeResultModel { Success = false, Message = "此案件的狀態為已開罰" }; + } + + if (data.CheckPunish == "1") + { + if (checkPunish == "1") + { + return new TradeResultModel { Success = false, Message = "此案件的狀態為等待開罰中" }; + } + } + + if (checkPunish == "0") + { + account = string.Empty; + } + + var site = _unitOfWork.SiteInformationRepository.GetSiteInformationBySiteId(data.SiteID); + var eventName = _unitOfWork.EventTypeRepository.GetEventTypeByEventType(site.EventType).EventName; + var vehicleName = _unitOfWork.EventRepository.GetVehicleTypebyType(data.VehicleType).VehicleName; + var user = _unitOfWork.AccountRepository.GetAccountUserByAccount(account); + var organization = _unitOfWork.PoliceStationRepository.GetPoliceStationById(user.PoliceStationId).StationName; + + //取得圖片的路徑 + var imageFolder = new DirectoryInfo($"{_configuration["EventStatus:ImagePath"]}/{site.SiteID}/{data.EventID}"); + //取得圖片路徑底下有多少 Image + var imageFiles = imageFolder.GetFiles(); + + //建立一個此事件的資料夾在Upload的資料夾裡 + var folder = $"{site.SiteID}_{data.EventID}_{data.Number}"; + DirectoryInfo uploadFolder = Directory.CreateDirectory(_configuration["EventStatus:Upload"] + folder); + + //將Image路徑的資料複製到Upload的資料夾 + var images = new List(); + foreach (var file in imageFiles) + { + images.Add(file.Name); + File.Copy(imageFolder.FullName + "\\" + file.Name, uploadFolder.FullName + "\\" + file.Name, true); + } + + //各個EventType分別產生不同資料夾 + switch (site.EventType) + { + case "1": + var json = new JsonCheckPunishEventType1 + { + area = site.Area, + county = site.County, + eventID = data.EventID, + siteName = site.SiteName, + alarmTime = Util.GetDateTimeNow(data.AlarmTime), + eventName = eventName, + inTime = Util.GetDateTimeNow(data.InTime), + handlingTime = Util.GetDateTimeNow(data.HandlingTime), + sn = data.Id.ToString(), + plate = data.Number, + outTime = Util.GetDateTimeNow(data.OutTime), + vehicleName = vehicleName, + organization = organization, + policeID = user.UserName, + punishID = law, + images = images, + }; + CreateCheckPunishEventTypeJson(_configuration["EventStatus:Upload"], folder, data.SiteID, data.EventID, json); + break; + case "2": + var json2 = new JsonCheckPunishEventType2 + { + area = site.Area, + county = site.County, + eventID = data.EventID, + siteName = site.SiteName, + eventName = eventName, + inTime = Util.GetDateTimeNow(data.InTime), + handlingTime = Util.GetDateTimeNow(data.HandlingTime), + sn = data.Id.ToString(), + plate = data.Number, + outTime = Util.GetDateTimeNow(data.OutTime), + vehicleName = vehicleName, + organization = organization, + policeID = user.UserName, + punishID = law, + images = images, + distance = data.Distance, + speed = data.Speed, + totalPassTime = data.TotalPassTime + }; + CreateCheckPunishEventTypeJson(_configuration["EventStatus:Upload"], folder, data.SiteID, data.EventID, json2); + break; + case "3": + var json3 = new JsonCheckPunishEventType3 + { + area = site.Area, + county = site.County, + eventID = data.EventID, + siteName = site.SiteName, + alarmTime = Util.GetDateTimeNow(data.AlarmTime), + eventName = eventName, + handlingTime = Util.GetDateTimeNow(data.HandlingTime), + sn = data.Id.ToString(), + plate = data.Number, + vehicleName = vehicleName, + organization = organization, + policeID = user.UserName, + punishID = law, + images = images, + }; + CreateCheckPunishEventTypeJson(_configuration["EventStatus:Upload"], folder, data.SiteID, data.EventID, json3); + break; + case "4": + var json4 = new JsonCheckPunishEventType4 + { + area = site.Area, + county = site.County, + eventID = data.EventID, + siteName = site.SiteName, + alarmTime = Util.GetDateTimeNow(data.AlarmTime), + eventName = eventName, + handlingTime = Util.GetDateTimeNow(data.HandlingTime), + sn = data.Id.ToString(), + plate = data.Number, + vehicleName = vehicleName, + organization = organization, + policeID = user.UserName, + punishID = law, + images = images, + }; + CreateCheckPunishEventTypeJson(_configuration["EventStatus:Upload"], folder, data.SiteID, data.EventID, json4); + break; + case "6": + var json6 = new JsonCheckPunishEventType6 + { + area = site.Area, + county = site.County, + eventID = data.EventID, + siteName = site.SiteName, + alarmTime = Util.GetDateTimeNow(data.AlarmTime), + eventName = eventName, + handlingTime = Util.GetDateTimeNow(data.HandlingTime), + sn = data.Id.ToString(), + plate = data.Number, + vehicleName = vehicleName, + organization = organization, + policeID = user.UserName, + punishID = law, + images = images, + ton = data.Ton, + }; + CreateCheckPunishEventTypeJson(_configuration["EventStatus:Upload"], folder, data.SiteID, data.EventID, json6); + break; + } + + var result = _unitOfWork.EventRepository.UpdatEventCheckPunish(account, eventId, checkPunish, law); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatEventCheckPunishList(string account, List eventIds, string checkPunish, string law) + { + try + { + bool IsSuccess = true; + foreach (var eventId in eventIds) + { + var result = UpdatEventCheckPunish(account, eventId, checkPunish, law).Success; + if (result == false) + { + IsSuccess = false; + } + } + + return new TradeResultModel { Success = IsSuccess, Message = IsSuccess ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatEventNoPunish(string account, int eventId, string reason) + { + try + { + var data = _unitOfWork.EventRepository.GetEventById(eventId); + if (data == null) + { + return new TradeResultModel { Success = false, Message = "查無此案件" }; + } + + if (data.CheckPunish != "0") + { + return new TradeResultModel { Success = false, Message = "此案件的狀態為等待開罰中" }; + } + + if (data.Rejected != "0") + { + return new TradeResultModel { Success = false, Message = "此案件的狀態已經為不開罰" }; + } + + if (data.Punished != "0") + { + return new TradeResultModel { Success = false, Message = "此案件的狀態為已開罰" }; + } + + var result = _unitOfWork.EventRepository.UpdatEventNoPunish(account, eventId, reason); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatEventCancel(string account, int id) + { + try + { + var data = _unitOfWork.EventRepository.GetEventById(id); + var site = _unitOfWork.SiteInformationRepository.GetSiteInformationBySiteId(data.SiteID); + var eventType = _unitOfWork.EventTypeRepository.GetEventTypeByEventType(site.EventType); + var vichle = _unitOfWork.EventRepository.GetVehicleTypebyType(data.VehicleType); + if (data == null) + { + return new TradeResultModel { Success = false, Message = "查無此案件" }; + } + + string siteId = data.SiteID; + JsonCancelEvent jsonCancelEvent = new JsonCancelEvent + { + plate = data.Number, + county = site.County, + action = "取消開單", + area = site.Area, + siteName = site.SiteName, + eventID = data.EventID, + policeID = "取消開單測試", + eventName = eventType.EventName, + handlingTime = Convert.ToDateTime(data.HandlingTime).ToString("yyyy-MM-dd HH:mm:ss"), + organization = site.Area, + vehicleName = vichle.VehicleName, + sn = data.Id.ToString(), + }; + CreateCancelJson(_configuration["EventStatus:Cancel"], siteId, jsonCancelEvent); + return new TradeResultModel { Success = true, Message = "成功取消開單" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + private static void CreateCheckPunishEventTypeJson(string path, string folder, string siteId, string eventID, object jsonCheckPunishEvent) + { + string fileName = $"{siteId}_{eventID}.json"; + path = path + folder + "\\" + fileName; + string Text = JsonConvert.SerializeObject(jsonCheckPunishEvent); + using (FileStream fs = File.Create(path)) + { + byte[] info = new UTF8Encoding(true).GetBytes(Text); + fs.Write(info, 0, info.Length); + } + } + + private static void CreateCancelJson(string path, string siteId, JsonCancelEvent jsonCancelEvent) + { + string fileName = $"{siteId}_{jsonCancelEvent.eventID}_{jsonCancelEvent.plate}.json"; + path = path + fileName; + string Text = JsonConvert.SerializeObject(jsonCancelEvent); + using (FileStream fs = File.Create(path)) + { + byte[] info = new UTF8Encoding(true).GetBytes(Text); + fs.Write(info, 0, info.Length); + } + } + + public TradeResultModel UpdatEventVehicleType(int id, string vehicleType) + { + try + { + var result = _unitOfWork.EventRepository.UpdateEventVehicleType(id, vehicleType); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatEventVehicleNumber(int id, string vehicleNumber) + { + try + { + var result = _unitOfWork.EventRepository.UpdateEventVehicleNumber(id, vehicleNumber); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatEventVehicle(int id, string vehicleType, string vehicleNumber) + { + try + { + var result = _unitOfWork.EventRepository.UpdateEventVehicle(id, vehicleType, vehicleNumber); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel DeleteEvent(int id) + { + try + { + var result = _unitOfWork.EventRepository.DeleteEvent(id); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "刪除成功" : "刪除失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public IEnumerable GetVehicleTypes() + { + try + { + var datas = _unitOfWork.EventRepository.GetVehicleType(); + var vms = new List(); + foreach (var data in datas) + { + var vm = new VehicleTypeViewModel(); + vm.InjectFrom(data); + vms.Add(vm); + } + return vms; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + } +} diff --git a/Traffic.Service/Implements/EventTypeService.cs b/Traffic.Service/Implements/EventTypeService.cs new file mode 100644 index 0000000..404e6ad --- /dev/null +++ b/Traffic.Service/Implements/EventTypeService.cs @@ -0,0 +1,233 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class EventTypeService : IEventTypeService + { + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + public EventTypeService(IUnitOfWork unitOfWork, ILogger logger) + { + _unitOfWork = unitOfWork; + _logger = logger; + } + + public IEnumerable GetEventTypes() + { + try + { + var eventType = _unitOfWork.EventTypeRepository.GetEventTypes(); + var data = eventType.ToList().Select(x => new EventTypeViewModel + { + Id = x.Id, + EventName = x.EventName, + EventType = x.EventType + }); + + return data; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new List(); + } + } + + public IEnumerable GetEventType1s() + { + try + { + var eventType = _unitOfWork.EventTypeRepository.GetEventType1s(); + var data = eventType.ToList().Select(x => new EventTypeViewModel + { + Id = x.Id, + EventName = x.EventName, + EventType = x.EventType + }); + + return data; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new List(); + } + } + + public PageViewModel> GetEventTypes(SearchModel searchModel) + { + try + { + var eventType = _unitOfWork.EventTypeRepository.GetEventTypes(); + + if (!string.IsNullOrEmpty(searchModel.Term)) + { + eventType = eventType.Where(x => x.EventName.Contains(searchModel.Term) || x.EventType.Contains(searchModel.Term)); + } + + int count = eventType.Count(); + int pageCount = count % searchModel.PageSize != 0 ? (count / searchModel.PageSize) + 1 : count / searchModel.PageSize; + + switch (searchModel.Order.ToLower()) + { + case "id": + default: + eventType = searchModel.IsAsc ? eventType.OrderBy(x => x.Id) : eventType.OrderByDescending(x => x.Id); + break; + case "eventname": + eventType = searchModel.IsAsc ? eventType.OrderBy(x => x.EventName).ThenBy(x => x.Id) : eventType.OrderByDescending(x => x.EventName).ThenByDescending(x => x.Id); + break; + case "eventtype": + eventType = searchModel.IsAsc ? eventType.OrderBy(x => x.EventType).ThenBy(x => x.Id) : eventType.OrderByDescending(x => x.EventType).ThenByDescending(x => x.Id); + break; + } + + eventType = eventType.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var data = eventType.ToList().Select(x => new EventTypeViewModel + { + Id = x.Id, + EventName = x.EventName, + EventType = x.EventType + }); + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = data, + }; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return new PageViewModel>(); + } + } + + public EventTypeViewModel GetEventTypeById(int id) + { + try + { + var eventType = _unitOfWork.EventTypeRepository.GetEventTypeById(id); + if (eventType != null) + { + return new EventTypeViewModel + { + Id = id, + EventName = eventType.EventName, + EventType = eventType.EventType, + }; + } + else + { + return null; + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + + public EventTypeViewModel GetEventTypeByEventType(string eventType) + { + try + { + var data = _unitOfWork.EventTypeRepository.GetEventTypeByEventType(eventType); + if (data != null) + { + return new EventTypeViewModel + { + EventName = data.EventName, + EventType = data.EventType, + }; + } + else + { + return null; + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + + public TradeResultModel InsertEventType(EventTypeViewModel EventType) + { + try + { + var eventType = new EventTypeData + { + EventName = EventType.EventName, + EventType = EventType.EventType, + }; + + var result = _unitOfWork.EventTypeRepository.InsertEventType(eventType); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "新增成功" : "新增失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatEventType(int id, EventTypeViewModel EventType) + { + try + { + var eventType = new EventTypeData + { + Id = id, + EventName = EventType.EventName, + EventType = EventType.EventType, + }; + + var result = _unitOfWork.EventTypeRepository.UpdateEventType(eventType); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel DeleteEventType(int id) + { + try + { + var result = _unitOfWork.EventTypeRepository.DeleteEventType(id); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "刪除成功" : "刪除失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + } +} diff --git a/Traffic.Service/Implements/FileService.cs b/Traffic.Service/Implements/FileService.cs new file mode 100644 index 0000000..7832270 --- /dev/null +++ b/Traffic.Service/Implements/FileService.cs @@ -0,0 +1,447 @@ +using ClosedXML.Excel; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class FileService : IFileService + { + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + public FileService(IConfiguration configuration, ILogger logger) + { + _configuration = configuration; + _logger = logger; + } + + public string ExportGetTycgLog(string tableName, IEnumerable data) + { + try + { + string fileName = $"{tableName}.xlsx"; + using (var workbook = new XLWorkbook()) + { + IXLWorksheet worksheet = + workbook.Worksheets.Add(tableName); + worksheet.Cell(1, 1).Value = "Id"; + worksheet.Cell(1, 2).Value = "Time"; + worksheet.Cell(1, 3).Value = "ip"; + worksheet.Cell(1, 4).Value = "api"; + var arryList = data.ToArray(); + for (int index = 1; index <= data.Count(); index++) + { + worksheet.Cell(index + 1, 1).Value = arryList[index - 1].Id; + worksheet.Cell(index + 1, 2).Value = arryList[index - 1].Time; + worksheet.Cell(index + 1, 3).Value = arryList[index - 1].ip; + worksheet.Cell(index + 1, 4).Value = arryList[index - 1].api; + } + using (var stream = new MemoryStream()) + { + workbook.SaveAs(stream); + var content = stream.ToArray(); + + using (FileStream fs = File.Create(_configuration["EventStatus:ExportExcel"] + fileName)) + { + fs.Write(content, 0, content.Length); + return _configuration["EventStatus:ExportExcelUrl"] + fileName; + } + } + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return "匯出失敗"; + } + } + + public string ExportEvent(string startTime, string endTime, string eventName, IEnumerable events) + { + try + { + + string fileName = $"違規事件-{startTime}到{endTime}的{eventName}.xlsx"; + using (var workbook = new XLWorkbook()) + { + IXLWorksheet worksheet = + workbook.Worksheets.Add("events"); + worksheet.Cell(1, 1).Value = "County"; + worksheet.Cell(1, 2).Value = "Area"; + worksheet.Cell(1, 3).Value = "SiteId"; + worksheet.Cell(1, 4).Value = "SiteName"; + worksheet.Cell(1, 5).Value = "EventName"; + worksheet.Cell(1, 6).Value = "VehicleName"; + worksheet.Cell(1, 7).Value = "Laws"; + worksheet.Cell(1, 8).Value = "EventID"; + worksheet.Cell(1, 9).Value = "Channel"; + worksheet.Cell(1, 10).Value = "Slot"; + worksheet.Cell(1, 11).Value = "Number"; + //worksheet.Cell(1, 12).Value = "PlateNumber"; + worksheet.Cell(1, 12).Value = "EventType"; + worksheet.Cell(1, 13).Value = "VehicleType"; + worksheet.Cell(1, 14).Value = "Distance"; + worksheet.Cell(1, 15).Value = "Speed"; + worksheet.Cell(1, 16).Value = "TotalPassTime"; + worksheet.Cell(1, 17).Value = "LimitTon"; + worksheet.Cell(1, 18).Value = "Ton"; + worksheet.Cell(1, 19).Value = "InTime"; + worksheet.Cell(1, 20).Value = "AlarmTime"; + worksheet.Cell(1, 21).Value = "OutTime"; + worksheet.Cell(1, 22).Value = "LPRTime"; + worksheet.Cell(1, 23).Value = "IMGPath1"; + worksheet.Cell(1, 24).Value = "VideoPath1"; + worksheet.Cell(1, 25).Value = "IsStay"; + worksheet.Cell(1, 26).Value = "Unsure"; + worksheet.Cell(1, 27).Value = "CheckPunish"; + worksheet.Cell(1, 28).Value = "Punished"; + worksheet.Cell(1, 29).Value = "CompanyCode"; + worksheet.Cell(1, 30).Value = "Rejected"; + worksheet.Cell(1, 31).Value = "Status"; + worksheet.Cell(1, 32).Value = "Ps"; + worksheet.Cell(1, 33).Value = "HandlingTime"; + worksheet.Cell(1, 34).Value = "UploadTime"; + worksheet.Cell(1, 35).Value = "Account"; + var arryList = events.ToArray(); + for (int index = 1; index <= events.Count(); index++) + { + worksheet.Cell(index + 1, 1).Value = arryList[index - 1].County; + worksheet.Cell(index + 1, 2).Value = arryList[index - 1].Area; + worksheet.Cell(index + 1, 3).Value = arryList[index - 1].SiteId; + worksheet.Cell(index + 1, 4).Value = arryList[index - 1].SiteName; + worksheet.Cell(index + 1, 5).Value = arryList[index - 1].EventName; + worksheet.Cell(index + 1, 6).Value = arryList[index - 1].VehicleName; + worksheet.Cell(index + 1, 7).Value = arryList[index - 1].Laws; + worksheet.Cell(index + 1, 8).Value = arryList[index - 1].EventID; + worksheet.Cell(index + 1, 9).Value = arryList[index - 1].Channel; + worksheet.Cell(index + 1, 10).Value = arryList[index - 1].Slot; + worksheet.Cell(index + 1, 11).Value = arryList[index - 1].Number; + //worksheet.Cell(index + 1, 12).Value = arryList[index - 1].PlateNumber; + worksheet.Cell(index + 1, 12).Value = arryList[index - 1].EventType; + worksheet.Cell(index + 1, 13).Value = arryList[index - 1].VehicleType; + worksheet.Cell(index + 1, 14).Value = arryList[index - 1].Distance; + worksheet.Cell(index + 1, 15).Value = arryList[index - 1].Speed; + worksheet.Cell(index + 1, 16).Value = arryList[index - 1].TotalPassTime; + worksheet.Cell(index + 1, 17).Value = arryList[index - 1].LimitTon; + worksheet.Cell(index + 1, 18).Value = arryList[index - 1].Ton; + worksheet.Cell(index + 1, 19).Value = arryList[index - 1].InTime; + worksheet.Cell(index + 1, 20).Value = arryList[index - 1].AlarmTime; + worksheet.Cell(index + 1, 21).Value = arryList[index - 1].OutTime; + worksheet.Cell(index + 1, 22).Value = arryList[index - 1].LPRTime; + worksheet.Cell(index + 1, 23).Value = arryList[index - 1].IMGPath1; + worksheet.Cell(index + 1, 24).Value = arryList[index - 1].VideoPath1; + worksheet.Cell(index + 1, 25).Value = arryList[index - 1].IsStay; + worksheet.Cell(index + 1, 26).Value = arryList[index - 1].Unsure; + worksheet.Cell(index + 1, 27).Value = arryList[index - 1].CheckPunish; + worksheet.Cell(index + 1, 28).Value = arryList[index - 1].Punished; + worksheet.Cell(index + 1, 29).Value = arryList[index - 1].CompanyCode; + worksheet.Cell(index + 1, 30).Value = arryList[index - 1].Rejected; + worksheet.Cell(index + 1, 31).Value = arryList[index - 1].Status; + worksheet.Cell(index + 1, 32).Value = arryList[index - 1].Ps; + worksheet.Cell(index + 1, 33).Value = arryList[index - 1].HandlingTime; + worksheet.Cell(index + 1, 34).Value = arryList[index - 1].UploadTime; + worksheet.Cell(index + 1, 35).Value = arryList[index - 1].Account; + } + using (var stream = new MemoryStream()) + { + workbook.SaveAs(stream); + var content = stream.ToArray(); + + using (FileStream fs = File.Create(_configuration["EventStatus:ExportExcel"] + fileName)) + { + fs.Write(content, 0, content.Length); + return _configuration["EventStatus:ExportExcelUrl"] + fileName; + } + } + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return "匯出失敗"; + } + } + + public string ExportGetEventType1(string startTime, string endTime, List data) + { + try + { + string fileName = $"違規事件報表-違規停車-{startTime}到{endTime}.xlsx"; + using (var workbook = new XLWorkbook()) + { + IXLWorksheet worksheet = + workbook.Worksheets.Add("events"); + worksheet.Cell(1, 1).Value = "DateTime"; + worksheet.Cell(1, 2).Value = "BusCount"; + worksheet.Cell(1, 3).Value = "CarCount"; + worksheet.Cell(1, 4).Value = "MotorcycleCount"; + worksheet.Cell(1, 5).Value = "TaxiCount"; + worksheet.Cell(1, 6).Value = "HasNumber"; + worksheet.Cell(1, 7).Value = "HasNoNumber"; + var arryList = data.ToArray(); + for (int index = 1; index <= data.Count; index++) + { + worksheet.Cell(index + 1, 1).Value = arryList[index - 1].DateTime; + worksheet.Cell(index + 1, 2).Value = arryList[index - 1].BusCount; + worksheet.Cell(index + 1, 3).Value = arryList[index - 1].CarCount; + worksheet.Cell(index + 1, 4).Value = arryList[index - 1].MotorcycleCount; + worksheet.Cell(index + 1, 5).Value = arryList[index - 1].TaxiCount; + worksheet.Cell(index + 1, 6).Value = arryList[index - 1].HasNumber; + worksheet.Cell(index + 1, 7).Value = arryList[index - 1].HasNoNumber; + } + using (var stream = new MemoryStream()) + { + workbook.SaveAs(stream); + var content = stream.ToArray(); + + using (FileStream fs = File.Create(_configuration["EventStatus:ExportExcel"] + fileName)) + { + fs.Write(content, 0, content.Length); + return _configuration["EventStatus:ExportExcelUrl"] + fileName; + } + } + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return "匯出失敗"; + } + } + + public string ExportGetEventType2(string startTime, string endTime, List data) + { + try + { + string fileName = $"違規事件報表-區間測速-{startTime}到{endTime}.xlsx"; + using (var workbook = new XLWorkbook()) + { + IXLWorksheet worksheet = + workbook.Worksheets.Add("events"); + worksheet.Cell(1, 1).Value = "Speed"; + worksheet.Cell(1, 2).Value = "Count"; + var arryList = data.ToArray(); + for (int index = 1; index <= data.Count; index++) + { + worksheet.Cell(index + 1, 1).Value = arryList[index - 1].Speed; + worksheet.Cell(index + 1, 2).Value = arryList[index - 1].Count; + } + using (var stream = new MemoryStream()) + { + workbook.SaveAs(stream); + var content = stream.ToArray(); + + using (FileStream fs = File.Create(_configuration["EventStatus:ExportExcel"] + fileName)) + { + fs.Write(content, 0, content.Length); + return _configuration["EventStatus:ExportExcelUrl"] + fileName; + } + } + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return "匯出失敗"; + } + } + + public string ExportGetEventType34(string startTime, string endTime, List data) + { + try + { + string fileName = $"違規事件報表-未依標線行駛_路口淨空_闖紅燈-{startTime}到{endTime}.xlsx"; + using (var workbook = new XLWorkbook()) + { + IXLWorksheet worksheet = + workbook.Worksheets.Add("events"); + worksheet.Cell(1, 1).Value = "CarCount"; + worksheet.Cell(1, 2).Value = "CoachCount"; + worksheet.Cell(1, 3).Value = "TruckCount"; + var arryList = data.ToArray(); + for (int index = 1; index <= data.Count; index++) + { + worksheet.Cell(index + 1, 1).Value = arryList[index - 1].CarCount; + worksheet.Cell(index + 1, 2).Value = arryList[index - 1].CoachCount; + worksheet.Cell(index + 1, 3).Value = arryList[index - 1].TruckCount; + } + using (var stream = new MemoryStream()) + { + workbook.SaveAs(stream); + var content = stream.ToArray(); + + using (FileStream fs = File.Create(_configuration["EventStatus:ExportExcel"] + fileName)) + { + fs.Write(content, 0, content.Length); + return _configuration["EventStatus:ExportExcelUrl"] + fileName; + } + } + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return "匯出失敗"; + } + } + + public string ExportGetEventType6(string startTime, string endTime, List data) + { + try + { + string fileName = $"違規事件報表-大貨車禁行-{startTime}到{endTime}.xlsx"; + using (var workbook = new XLWorkbook()) + { + IXLWorksheet worksheet = + workbook.Worksheets.Add("events"); + worksheet.Cell(1, 1).Value = "Ton"; + worksheet.Cell(1, 2).Value = "Count"; + var arryList = data.ToArray(); + for (int index = 1; index <= data.Count; index++) + { + worksheet.Cell(index + 1, 1).Value = arryList[index - 1].Ton; + worksheet.Cell(index + 1, 2).Value = arryList[index - 1].Count; + } + using (var stream = new MemoryStream()) + { + workbook.SaveAs(stream); + var content = stream.ToArray(); + + using (FileStream fs = File.Create(_configuration["EventStatus:ExportExcel"] + fileName)) + { + fs.Write(content, 0, content.Length); + return _configuration["EventStatus:ExportExcelUrl"] + fileName; + } + } + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return "匯出失敗"; + } + } + + public string ExportGetMalfunction(string startTime, string endTime, List data) + { + try + { + string fileName = $"設備異常-{startTime}到{endTime}.xlsx"; + using (var workbook = new XLWorkbook()) + { + IXLWorksheet worksheet = + workbook.Worksheets.Add("Malfunction"); + worksheet.Cell(1, 1).Value = "時間"; + worksheet.Cell(1, 2).Value = "場域"; + worksheet.Cell(1, 3).Value = "公司"; + worksheet.Cell(1, 4).Value = "設備"; + worksheet.Cell(1, 5).Value = "設備編號"; + worksheet.Cell(1, 6).Value = "訊息"; + var arryList = data.ToArray(); + for (int index = 1; index <= data.Count; index++) + { + worksheet.Cell(index + 1, 1).Value = arryList[index - 1].Time; + worksheet.Cell(index + 1, 2).Value = arryList[index - 1].SiteName; + worksheet.Cell(index + 1, 3).Value = arryList[index - 1].CompanyCode; + worksheet.Cell(index + 1, 4).Value = arryList[index - 1].DeviceType; + worksheet.Cell(index + 1, 5).Value = arryList[index - 1].DeviceID; + worksheet.Cell(index + 1, 6).Value = arryList[index - 1].Message; + } + using (var stream = new MemoryStream()) + { + workbook.SaveAs(stream); + var content = stream.ToArray(); + + using (FileStream fs = File.Create(_configuration["EventStatus:ExportExcel"] + fileName)) + { + fs.Write(content, 0, content.Length); + return _configuration["EventStatus:ExportExcelUrl"] + fileName; + } + } + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return "匯出失敗"; + } + } + + public string ExportGetSiteEvent(string startTime, string endTime, ReportSiteEventTypesViewModel data) + { + try + { + string fileName = $"違規事件統計站店違規數統計表-{startTime}到{endTime}.xlsx"; + using (var workbook = new XLWorkbook()) + { + IXLWorksheet worksheet = + workbook.Worksheets.Add("違規事件統計"); + worksheet.Cell(1, 1).Value = "違規項目"; + worksheet.Cell(1, 2).Value = "違規總數"; + worksheet.Cell(1, 3).Value = "未開單"; + worksheet.Cell(1, 4).Value = "裁決中"; + worksheet.Cell(1, 5).Value = "不開單"; + worksheet.Cell(1, 6).Value = "已拒絕"; + worksheet.Cell(1, 7).Value = "已開單"; + var arryList = data.EachEventTypesSiteViewModel.ToArray(); + for (int index = 1; index <= data.EachEventTypesSiteViewModel.Count; index++) + { + worksheet.Cell(index + 1, 1).Value = arryList[index - 1].EventName; + worksheet.Cell(index + 1, 2).Value = arryList[index - 1].EventTotalCount; + worksheet.Cell(index + 1, 3).Value = arryList[index - 1].NoStatusCount; + worksheet.Cell(index + 1, 4).Value = arryList[index - 1].CheckPunishCount; + worksheet.Cell(index + 1, 5).Value = arryList[index - 1].NoPunishCount; + worksheet.Cell(index + 1, 6).Value = arryList[index - 1].RejectedCount; + worksheet.Cell(index + 1, 7).Value = arryList[index - 1].PunishCount; + } + + IXLWorksheet worksheet2 = workbook.Worksheets.Add("站點違規數統計"); + worksheet2.Cell(1, 1).Value = "站點ID"; + worksheet2.Cell(1, 2).Value = "站點名稱"; + worksheet2.Cell(1, 3).Value = "事件總數"; + worksheet2.Cell(1, 4).Value = "未開單"; + worksheet2.Cell(1, 5).Value = "裁決中"; + worksheet2.Cell(1, 6).Value = "不開單"; + worksheet2.Cell(1, 7).Value = "已拒絕"; + worksheet2.Cell(1, 8).Value = "已開單"; + var arryList2 = data.EachSiteEventTypesViewModel.ToArray(); + for (int index = 1; index <= data.EachSiteEventTypesViewModel.Count; index++) + { + worksheet2.Cell(index + 1, 1).Value = arryList2[index - 1].SiteId; + worksheet2.Cell(index + 1, 2).Value = arryList2[index - 1].SiteName; + worksheet2.Cell(index + 1, 3).Value = arryList2[index - 1].EventTotalCount; + worksheet2.Cell(index + 1, 4).Value = arryList2[index - 1].NoStatusCount; + worksheet2.Cell(index + 1, 5).Value = arryList2[index - 1].CheckPunishCount; + worksheet2.Cell(index + 1, 6).Value = arryList2[index - 1].NoPunishCount; + worksheet2.Cell(index + 1, 7).Value = arryList2[index - 1].RejectedCount; + worksheet2.Cell(index + 1, 8).Value = arryList2[index - 1].PunishCount; + } + + using (var stream = new MemoryStream()) + { + workbook.SaveAs(stream); + var content = stream.ToArray(); + + using (FileStream fs = File.Create(_configuration["EventStatus:ExportExcel"] + fileName)) + { + fs.Write(content, 0, content.Length); + return _configuration["EventStatus:ExportExcelUrl"] + fileName; + } + } + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return "匯出失敗"; + } + } + } +} diff --git a/Traffic.Service/Implements/LoginService.cs b/Traffic.Service/Implements/LoginService.cs new file mode 100644 index 0000000..169f531 --- /dev/null +++ b/Traffic.Service/Implements/LoginService.cs @@ -0,0 +1,85 @@ +using LiangLiSystem.Services.Helpers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class LoginService : ILoginService + { + private readonly IUnitOfWork _unitOfWork; + + public LoginService(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + public AccountUserViewModel Login(string account, string password, string ip = "") + { + SHA256 sha256 = new SHA256CryptoServiceProvider();//建立一個SHA256 + byte[] source = Encoding.Default.GetBytes(password);//將字串轉為Byte[] + byte[] crypto = sha256.ComputeHash(source);//進行SHA256加密 + var pwdHash = Convert.ToBase64String(crypto);//把加密後的字串從Byte[]轉為字串 + + var data = _unitOfWork.AccountRepository.GetAccountUserByAccount(account); + if (data == null) + { + return null; + } + + var log = new UserLoginLog + { + UserId = data.Id, + LoginIP = ip, + LoginOn = Util.GetDateTimeNow(), + Status = data.Password != pwdHash ? 0 : 1 + }; + + _unitOfWork.AccountRepository.InsertUserLoginLog(log); + + if (data.Password != pwdHash) + { + var count = data.ErrorCount + 1; + _unitOfWork.AccountRepository.UpdateUserErrorCount(data.Id, count); + _unitOfWork.Complete(); + var viewModel = new AccountUserViewModel + { + Id = data.Id, + Account = data.Account, + Name = data.UserName, + Email = data.Email, + Role = data.RoleCodeId, + ErrorCount = data.ErrorCount + 1, + ChangePwdOn = data.ChangePwdOn, + Status = data.Status + }; + return viewModel; + } + else + { + _unitOfWork.AccountRepository.UpdateUserErrorCount(data.Id, 0); + _unitOfWork.Complete(); + var viewModel = new AccountUserViewModel + { + Id = data.Id, + Account = data.Account, + Name = data.UserName, + Email = data.Email, + Role = data.RoleCodeId, + ErrorCount = 0, + ChangePwdOn = data.ChangePwdOn, + Status = data.Status + }; + + return viewModel; + } + } + } +} diff --git a/Traffic.Service/Implements/MailService.cs b/Traffic.Service/Implements/MailService.cs new file mode 100644 index 0000000..6f5141c --- /dev/null +++ b/Traffic.Service/Implements/MailService.cs @@ -0,0 +1,49 @@ +using Microsoft.Extensions.Configuration; +using System; +using System.Net.Mail; +using Traffic.Data.ViewModels; +using Traffic.Repository.Interfaces; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class MailService : IMailService + { + private readonly IConfiguration _configuration; + + public MailService(IConfiguration configuration) + { + _configuration = configuration; + } + + /// + /// 傳送 Mail + /// + public void SendMail(MailViewModel mailViewModel) + { + using (MailMessage mail = new MailMessage()) + { + mail.From = new MailAddress(mailViewModel.From);//寄件人 + foreach (var toAddress in mailViewModel.To) + { + mail.To.Add(toAddress);//收件人 + } + mail.Subject = mailViewModel.Subject; + mail.SubjectEncoding = mailViewModel.SubjectEncoding; + mail.Body = mailViewModel.Body; + mail.IsBodyHtml = mailViewModel.IsBodyHtml; + mail.BodyEncoding = mailViewModel.BodyEncoding; + mail.Priority = mailViewModel.Priority; + + using (var smtp = new SmtpClient(_configuration["MailServer:Host"], Convert.ToInt16(_configuration["MailServer:Port"]))) + { + var account = _configuration["MailServer:Account"];//mail account + var password = _configuration["MailServer:Password"];//mail password + smtp.Credentials = new System.Net.NetworkCredential(account, password); + smtp.EnableSsl = true; + smtp.Send(mail); + } + } + } + } +} diff --git a/Traffic.Service/Implements/MalfunctionService.cs b/Traffic.Service/Implements/MalfunctionService.cs new file mode 100644 index 0000000..cc12064 --- /dev/null +++ b/Traffic.Service/Implements/MalfunctionService.cs @@ -0,0 +1,154 @@ +using Omu.ValueInjecter; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class MalfunctionService : IMalfunctionService + { + private readonly IUnitOfWork _unitOfWork; + + public MalfunctionService(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + public IEnumerable GetMalfunctionsOld(int userid) + { + var userSites = _unitOfWork.AccountRepository.GetAccountUserSite(userid); + var sites = _unitOfWork.SiteInformationRepository.GetSiteInformations(); + var result = new List(); + + var datas = _unitOfWork.MalfunctionRepository.GetMalfunctions(userid); + DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 當地時區 + var mList = new List(); + foreach (var data in datas) + { + var vm = new MalfunctionViewModel(); + vm.InjectFrom(data); + + DateTime dt = startTime.AddSeconds(Convert.ToInt32(data.Timestamp)); + vm.Time = dt.ToString("yyyy-MM-dd HH:mm:ss"); + if (string.IsNullOrWhiteSpace(vm.Message)) + { + vm.Status = "未連線"; + } + else if (vm.Message.ToLower() == "error") + { + vm.Status = "異常"; + } + else if (vm.Message.ToLower() == "normal") + { + vm.Status = "正常"; + } + else + { + vm.Status = "未連線"; + } + mList.Add(vm); + } + foreach (var item in userSites) + { + var site = sites.Where(i => i.Id == item.SiteId).FirstOrDefault(); + var li = mList.Where(i => i.Siteid == site.SiteID); + var vm = new SiteMalfunctionViewModel + { + SiteName = site.SiteName, + EventType = site.EventType, + Area = site.Area, + County = site.County, + Siteid = site.SiteID, + SiteStatus = li.Any(i => i.Status == "異常") ? "1" : "0", + UserId = userid, + Malfunctions = li.ToList() + }; + + if (li.All(i => i.Status == "未連線")) + { + continue; + } + + result.Add(vm); + } + + return result; + } + + public IEnumerable GetMalfunctions(int userid) + { + var datas = _unitOfWork.MalfunctionRepository.GetMalfunctions(); + var userSites = _unitOfWork.AccountRepository.GetAccountUserSite(userid); + var sites = _unitOfWork.SiteInformationRepository.GetSiteInformations(); + + var result = new List(); + DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 當地時區 + + var mList = new List(); + foreach (var data in datas) + { + DateTime dt = startTime.AddSeconds(Convert.ToInt32(data.Timestamp)); + var vm = new MalfunctionViewModel + { + CompanyCode = data.CompanyCode, + Siteid = data.Siteid, + Message = data.Message, + DeviceID = data.DeviceID, + DeviceType = data.DeviceType, + Time = dt.ToString("yyyy-MM-dd HH:mm:ss"), + UserId = userid, + }; + + if (string.IsNullOrWhiteSpace(vm.Message)) + { + vm.Status = "未連線"; + } + else if (vm.Message.ToLower() == "error") + { + vm.Status = "異常"; + } + else if (vm.Message.ToLower() == "normal") + { + vm.Status = "正常"; + } + else + { + vm.Status = "未連線"; + } + mList.Add(vm); + } + + foreach (var item in userSites) + { + var site = sites.Where(i => i.Id == item.SiteId).FirstOrDefault(); + var li = mList.Where(i => i.Siteid == site.SiteID); + var vm = new SiteMalfunctionViewModel + { + SiteName = site.SiteName, + EventType = site.EventType, + Area = site.Area, + County = site.County, + Siteid = site.SiteID, + SiteStatus = li.Any(i => i.Status == "異常") ? "1" : "0", + UserId = userid, + Malfunctions = li.ToList() + }; + + if (li.All(i => i.Status == "未連線")) + { + continue; + } + + result.Add(vm); + } + + return result; + } + } +} diff --git a/Traffic.Service/Implements/NotPunishService.cs b/Traffic.Service/Implements/NotPunishService.cs new file mode 100644 index 0000000..2196b16 --- /dev/null +++ b/Traffic.Service/Implements/NotPunishService.cs @@ -0,0 +1,253 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class NotPunishService : INotPunishService + { + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + public NotPunishService(IUnitOfWork unitOfWork, ILogger logger) + { + _unitOfWork = unitOfWork; + _logger = logger; + } + + public IEnumerable GetNotPunishs() + { + try + { + _logger.LogInformation($"GetNotPunishs Init"); + var data = _unitOfWork.NotPunishRepository.GetNotPunishs(); + + var eventTypes = _unitOfWork.EventTypeRepository.GetEventTypes(); + var result = data.ToList().Select(x => new NotPunishViewModel + { + Id = x.Id, + EventTypeId = x.EventTypeId, + EventType = eventTypes.Any(i => i.Id == x.EventTypeId) ? eventTypes.FirstOrDefault(i => i.Id == x.EventTypeId).EventType : string.Empty, + EventName = eventTypes.Any(i => i.Id == x.EventTypeId) ? eventTypes.FirstOrDefault(i => i.Id == x.EventTypeId).EventName : string.Empty, + NotPunishType = x.NotPunishType, + NotPunishReason = x.NotPunishReason, + }); + + _logger.LogInformation($"GetNotPunishs Finish"); + return result; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + + public PageViewModel> GetNotPunishs(SearchModel searchModel) + { + try + { + _logger.LogInformation($"GetNotPunishs Init"); + var data = _unitOfWork.NotPunishRepository.GetNotPunishs(); + + if (!string.IsNullOrEmpty(searchModel.Term)) + { + _logger.LogInformation($"GetNotPunishs searchModel.Term ={searchModel.Term}"); + data = data.Where(x => x.NotPunishReason.Contains(searchModel.Term)); + } + + int count = data.Count(); + int pageCount = count % searchModel.PageSize != 0 ? (count / searchModel.PageSize) + 1 : count / searchModel.PageSize; + + switch (searchModel.Order.ToLower()) + { + case "id": + default: + data = searchModel.IsAsc ? data.OrderBy(x => x.Id) : data.OrderByDescending(x => x.Id); + break; + case "eventtypeid": + data = searchModel.IsAsc ? data.OrderBy(x => x.EventTypeId).ThenBy(x => x.Id) : data.OrderByDescending(x => x.EventTypeId).ThenByDescending(x => x.Id); + break; + case "notpunishtype": + data = searchModel.IsAsc ? data.OrderBy(x => x.NotPunishType).ThenBy(x => x.Id) : data.OrderByDescending(x => x.NotPunishType).ThenByDescending(x => x.Id); + break; + case "notpunishreason": + data = searchModel.IsAsc ? data.OrderBy(x => x.NotPunishReason).ThenBy(x => x.Id) : data.OrderByDescending(x => x.NotPunishReason).ThenByDescending(x => x.Id); + break; + } + + var eventTypes = _unitOfWork.EventTypeRepository.GetEventTypes(); + data = data.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var result = data.ToList().Select(x => new NotPunishViewModel + { + Id = x.Id, + EventTypeId = x.EventTypeId, + EventType = eventTypes.Any(i => i.Id == x.EventTypeId) ? eventTypes.FirstOrDefault(i => i.Id == x.EventTypeId).EventType : string.Empty, + EventName = eventTypes.Any(i => i.Id == x.EventTypeId) ? eventTypes.FirstOrDefault(i => i.Id == x.EventTypeId).EventName : string.Empty, + NotPunishType = x.NotPunishType, + NotPunishReason = x.NotPunishReason, + }); + + _logger.LogInformation($"GetNotPunishs Finish"); + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = result, + }; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + + public NotPunishViewModel GetNotPunishById(int id) + { + try + { + _logger.LogDebug($"GetNotPunishById Init"); + _logger.LogDebug($"GetNotPunishById id = {id}"); + + var data = _unitOfWork.NotPunishRepository.GetNotPunishById(id); + if (data == null) + { + _logger.LogWarning($"GetNotPunishById id = {id} is Null"); + return null; + } + + _logger.LogDebug($"GetNotPunishById data.NotPunishType = {data.NotPunishType} and data.NotPunishReason = {data.NotPunishReason}"); + var eventType = _unitOfWork.EventTypeRepository.GetEventTypeById(data.EventTypeId); + + _logger.LogDebug($"GetNotPunishById Finish"); + return new NotPunishViewModel + { + Id = data.Id, + EventTypeId = data.EventTypeId, + EventType = eventType.EventType, + EventName = eventType.EventName, + NotPunishType = data.NotPunishType, + NotPunishReason = data.NotPunishReason, + }; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + } + + public TradeResultModel InsertNotPunish(NotPunishViewModel viewModel) + { + try + { + _logger.LogDebug($"InsertNotPunish Init"); + var eventType = _unitOfWork.EventTypeRepository.GetEventTypeById(viewModel.EventTypeId); + if (eventType == null) + { + _logger.LogWarning($"InsertNotPunish EventTypeId = {viewModel.EventTypeId} 無此事件類型"); + return new TradeResultModel { Success = false, Message = "查無此事件類型" }; + } + + var data = new NotPunish + { + EventTypeId = viewModel.EventTypeId, + NotPunishType = viewModel.NotPunishType, + NotPunishReason = viewModel.NotPunishReason, + }; + + _logger.LogDebug($"InsertNotPunish Insert EventTypeId = { viewModel.EventTypeId}"); + _logger.LogDebug($"InsertNotPunish Insert NotPunishType = {viewModel.NotPunishType}"); + _logger.LogDebug($"InsertNotPunish Insert EventTypeId= {viewModel.EventTypeId}"); + + var result = _unitOfWork.NotPunishRepository.InsertNotPunish(data); + _unitOfWork.Complete(); + + _logger.LogDebug($"InsertNotPunish result is {result}"); + _logger.LogDebug($"InsertNotPunish Finish"); + return new TradeResultModel { Success = result, Message = result ? "新增成功" : "新增失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatNotPunish(int id, NotPunishViewModel viewModel) + { + try + { + _logger.LogDebug($"UpdatNotPunish Init"); + var eventType = _unitOfWork.EventTypeRepository.GetEventTypeById(viewModel.EventTypeId); + if (eventType == null) + { + _logger.LogWarning($"UpdatNotPunish EventTypeId = {viewModel.EventTypeId} 無此事件類型"); + return new TradeResultModel { Success = false, Message = "查無此事件類型" }; + } + + var data = new NotPunish + { + Id = id, + EventTypeId = viewModel.EventTypeId, + NotPunishType = viewModel.NotPunishType, + NotPunishReason = viewModel.NotPunishReason, + }; + + _logger.LogDebug($"InsertNotPunish Insert EventTypeId = { viewModel.EventTypeId}"); + _logger.LogDebug($"InsertNotPunish Insert NotPunishType = {viewModel.NotPunishType}"); + _logger.LogDebug($"InsertNotPunish Insert EventTypeId= {viewModel.EventTypeId}"); + + var result = _unitOfWork.NotPunishRepository.UpdateNotPunish(data); + _unitOfWork.Complete(); + + _logger.LogDebug($"UpdatNotPunish result is {result}"); + _logger.LogDebug($"UpdatNotPunish Finish"); + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel DeleteNotPunish(int id) + { + try + { + _logger.LogDebug($"DeleteNotPunish Init"); + var data = _unitOfWork.NotPunishRepository.GetNotPunishById(id); + if (data == null) + { + _logger.LogWarning($"UpdatNotPunish id = {id} 無此不開單原因"); + return new TradeResultModel { Success = false, Message = "查無此不開單原因" }; + } + + var result = _unitOfWork.NotPunishRepository.DeleteNotPunish(id); + _unitOfWork.Complete(); + + _logger.LogDebug($"DeleteNotPunish result is {result}"); + _logger.LogDebug($"DeleteNotPunish Finish"); + return new TradeResultModel { Success = result, Message = result ? "刪除成功" : "刪除失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + } +} diff --git a/Traffic.Service/Implements/PageListService.cs b/Traffic.Service/Implements/PageListService.cs new file mode 100644 index 0000000..0919e15 --- /dev/null +++ b/Traffic.Service/Implements/PageListService.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class PageListService : IPageListService + { + private readonly IUnitOfWork _unitOfWork; + + public PageListService(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + public TradeResultModel PostPageDataList(PageData pageData) + { + var result = new TradeResultModel { Success = false }; + try + { + pageData.PageModule = pageData.PageModule; + pageData.PageName = pageData.PageName; + pageData.PageUrl = pageData.PageUrl; + + _unitOfWork.RolePageRepository.InsertPageList( + new PageList + { + PageModule = pageData.PageModule, + PageName = pageData.PageName, + PageURL = pageData.PageUrl + }); + _unitOfWork.Complete(); + } + catch (Exception ex) + { + result.Message = ex.Message; + return result; + } + result.Success = true; + return result; + } + + public TradeResultModel PutPageData(PageData pageData) + { + var result = new TradeResultModel { Success = false }; + try + { + _unitOfWork.RolePageRepository.UpdatePageList( + new PageList + { + Id = pageData.Id, + PageModule = pageData.PageModule, + PageName = pageData.PageName, + PageURL = pageData.PageUrl + }); + _unitOfWork.Complete(); + } + catch (Exception ex) + { + result.Message = ex.Message; + return result; + } + result.Success = true; + return result; + } + + public TradeResultModel DeletePageData(int id) + { + var result = new TradeResultModel { Success = false }; + try + { + _unitOfWork.RolePageRepository.DeletePageList(id); + _unitOfWork.Complete(); + } + catch (Exception ex) + { + result.Message = ex.Message; + return result; + } + result.Success = true; + return result; + } + + public PageViewModel> GetPageDataList(SearchModel searchModel) + { + var sql = _unitOfWork.RolePageRepository.GetPageLists(); + if (!string.IsNullOrEmpty(searchModel.Term)) + { + sql = sql.Where(x => x.PageModule.Contains(searchModel.Term) || x.PageName.Contains(searchModel.Term)); + } + int count = -1; + int pageCount = -1; + if (searchModel.Page == 1) + { + count = sql.Count(); + if (count % 10 != 0) + { + pageCount = (count / searchModel.PageSize) + 1; + } + else + { + pageCount = count / searchModel.PageSize; + } + } + switch (searchModel.Order) + { + case "Id": + sql = searchModel.IsAsc ? sql.OrderBy(x => x.Id) : sql.OrderByDescending(x => x.Id); + break; + case "PageModule": + sql = searchModel.IsAsc ? sql.OrderBy(x => x.PageModule).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.PageModule).ThenByDescending(x => x.Id); + break; + case "PageName": + sql = searchModel.IsAsc ? sql.OrderBy(x => x.PageName).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.PageName).ThenByDescending(x => x.Id); + break; + case "PageURL": + sql = searchModel.IsAsc ? sql.OrderBy(x => x.PageURL).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.PageURL).ThenByDescending(x => x.Id); + break; + default: + goto case "Id"; + } + + sql = sql.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var data = sql.ToList().Select(x => new PageData + { + Id = x.Id, + PageModule = x.PageModule, + PageName = x.PageName, + PageUrl = x.PageURL + }); + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = data, + }; + } + } +} diff --git a/Traffic.Service/Implements/PoliceStationService.cs b/Traffic.Service/Implements/PoliceStationService.cs new file mode 100644 index 0000000..10aaab6 --- /dev/null +++ b/Traffic.Service/Implements/PoliceStationService.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class PoliceStationService : IPoliceStationService + { + private readonly IUnitOfWork _unitOfWork; + + public PoliceStationService(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + public PageViewModel> GetPoliceStations(SearchModel searchModel) + { + var company = _unitOfWork.PoliceStationRepository.GetPoliceStations(); + + if (!string.IsNullOrEmpty(searchModel.Term)) + { + company = company.Where(x => x.Area.Contains(searchModel.Term) || x.StationName.Contains(searchModel.Term)); + } + + int count = company.Count(); + int pageCount = count % searchModel.PageSize != 0 ? (count / searchModel.PageSize) + 1 : count / searchModel.PageSize; + + switch (searchModel.Order.ToLower()) + { + case "id": + default: + company = searchModel.IsAsc? company.OrderBy(x => x.Id) : company.OrderByDescending(x => x.Id); + break; + case "area": + company = searchModel.IsAsc ? company.OrderBy(x => x.Area).ThenBy(x => x.Id) : company.OrderByDescending(x => x.Area).ThenByDescending(x => x.Id); + break; + case "stationname": + company = searchModel.IsAsc? company.OrderBy(x => x.StationName).ThenBy(x => x.Id) : company.OrderByDescending(x => x.StationName).ThenByDescending(x => x.Id); + break; + } + + company = company.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var data = company.ToList().Select(x => new PoliceStationViewModel + { + Id = x.Id, + Area = x.Area, + StationName = x.StationName + }); + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = data, + }; + } + + public PoliceStationViewModel GetPoliceStationById(int id) + { + try + { + var station = _unitOfWork.PoliceStationRepository.GetPoliceStationById(id); + if (station != null) + { + return new PoliceStationViewModel + { + Id = station.Id, + Area = station.Area, + StationName = station.StationName, + }; + } + else + { + return null; + } + } + catch (Exception ex) + { + return null; + } + } + + public IEnumerable GetGroupNameList() + { + var data = _unitOfWork.PoliceStationRepository.GetPoliceStations().Select(x => new PoliceStationViewModel + { + Id = x.Id, + Area = x.Area, + StationName = x.StationName + }); + return data; + } + + public TradeResultModel InsertPoliceStation(PoliceStationViewModel PoliceStation) + { + try + { + var station = new PoliceStation + { + Area = PoliceStation.Area, + StationName = PoliceStation.StationName, + }; + + var result = _unitOfWork.PoliceStationRepository.InsertPoliceStation(station); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "新增成功" : "新增失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatPoliceStation(PoliceStationViewModel PoliceStation) + { + try + { + var station = new PoliceStation + { + Id = PoliceStation.Id, + Area = PoliceStation.Area, + StationName = PoliceStation.StationName, + }; + + var result = _unitOfWork.PoliceStationRepository.UpdatePoliceStation(station); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel DeletePoliceStation(int id) + { + try + { + var result = _unitOfWork.PoliceStationRepository.DeletePoliceStation(id); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "刪除成功" : "刪除失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + } +} diff --git a/Traffic.Service/Implements/RepairService.cs b/Traffic.Service/Implements/RepairService.cs new file mode 100644 index 0000000..c977965 --- /dev/null +++ b/Traffic.Service/Implements/RepairService.cs @@ -0,0 +1,236 @@ +using Mail.ViewModels; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Omu.ValueInjecter; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class RepairService : IRepairService + { + private readonly IConfiguration _configuration; + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + private readonly IMailService _mailService; + + public RepairService(IConfiguration configuration, IUnitOfWork unitOfWork, ILogger logger, IMailService mailService) + { + _configuration = configuration; + _unitOfWork = unitOfWork; + _logger = logger; + _mailService = mailService; + } + + public IEnumerable GetRepairs() + { + try + { + _logger.LogInformation($"GetRepairs Init"); + var datas = _unitOfWork.RepairRepository.GetRepairs(); + var result = new List(); + foreach (var item in datas) + { + var vm = new RepairViewModel(); + vm.InjectFrom(item); + result.Add(vm); + } + return result; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + finally + { + _logger.LogInformation($"GetRepairs Finish"); + } + } + + public PageViewModel> GetRepairs(SearchModel searchModel) + { + try + { + _logger.LogInformation($"GetRepairs Init"); + var data = _unitOfWork.RepairRepository.GetRepairs(); + + if (!string.IsNullOrEmpty(searchModel.Term)) + { + _logger.LogInformation($"GetRepairs searchModel.Term ={searchModel.Term}"); + data = data.Where(x => x.Title.Contains(searchModel.Term)); + } + + int count = data.Count(); + int pageCount = count % searchModel.PageSize != 0 ? (count / searchModel.PageSize) + 1 : count / searchModel.PageSize; + + switch (searchModel.Order.ToLower()) + { + case "id": + default: + data = searchModel.IsAsc ? data.OrderBy(x => x.Id) : data.OrderByDescending(x => x.Id); + break; + case "sendto": + data = searchModel.IsAsc ? data.OrderBy(x => x.SendTo).ThenBy(x => x.Id) : data.OrderByDescending(x => x.SendTo).ThenByDescending(x => x.Id); + break; + case "title": + data = searchModel.IsAsc ? data.OrderBy(x => x.Title).ThenBy(x => x.Id) : data.OrderByDescending(x => x.Title).ThenByDescending(x => x.Id); + break; + case "describe": + data = searchModel.IsAsc ? data.OrderBy(x => x.Content).ThenBy(x => x.Id) : data.OrderByDescending(x => x.Content).ThenByDescending(x => x.Id); + break; + } + + var eventTypes = _unitOfWork.EventTypeRepository.GetEventTypes(); + data = data.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var result = new List(); + foreach (var item in data) + { + var vm = new RepairViewModel(); + vm.InjectFrom(item); + result.Add(vm); + } + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = result, + }; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + finally + { + _logger.LogInformation($"GetRepairs Finish"); + } + } + + public RepairViewModel GetRepairById(int id) + { + try + { + _logger.LogDebug($"GetRepairById Init"); + _logger.LogDebug($"GetRepairById id = {id}"); + + var data = _unitOfWork.RepairRepository.GetRepairById(id); + if (data == null) + { + _logger.LogWarning($"GetRepairById id = {id} is Null"); + return null; + } + + var result = new RepairViewModel(); + result.InjectFrom(data); + + return result; + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + return null; + } + finally + { + _logger.LogDebug($"GetRepairById Finish"); + } + } + + public TradeResultModel InsertRepair(RepairViewModel viewModel) + { + try + { + var data = new Repair(); + data.InjectFrom(viewModel); + + if (viewModel.QuestionType == 0) + { + data.SendTo = _configuration["Repair:Email"]; + } + + var result = _unitOfWork.RepairRepository.InsertRepair(data); + _unitOfWork.Complete(); + + if (_configuration["MailServer:IsTest"] != "true") + { + var mail = new MailViewModel + { + From = "tfc017@mail.tycg.gov.tw", + To = data.SendTo.Split(','), + Subject = data.Title, + Body = data.Content, + }; + + _mailService.SendMail(mail); + } + + return new TradeResultModel { Success = result, Message = result ? "新增成功" : "新增失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatRepair(int id, RepairViewModel viewModel) + { + try + { + var data = new Repair(); + data.InjectFrom(viewModel); + data.Id = id; + + var result = _unitOfWork.RepairRepository.UpdateRepair(data); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel DeleteRepair(int id) + { + try + { + _logger.LogDebug($"DeleteRepair Init"); + var data = _unitOfWork.RepairRepository.GetRepairById(id); + if (data == null) + { + _logger.LogWarning($"UpdatRepair id = {id} 無此不開單原因"); + return new TradeResultModel { Success = false, Message = "查無此不開單原因" }; + } + + var result = _unitOfWork.RepairRepository.DeleteRepair(id); + _unitOfWork.Complete(); + + _logger.LogDebug($"DeleteRepair result is {result}"); + _logger.LogDebug($"DeleteRepair Finish"); + return new TradeResultModel { Success = result, Message = result ? "刪除成功" : "刪除失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + _logger.LogError(ex.Message); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + } +} diff --git a/Traffic.Service/Implements/ReportService.cs b/Traffic.Service/Implements/ReportService.cs new file mode 100644 index 0000000..95d9ed5 --- /dev/null +++ b/Traffic.Service/Implements/ReportService.cs @@ -0,0 +1,455 @@ +using Omu.ValueInjecter; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Enums; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class ReportService : IReportService + { + private readonly IUnitOfWork _unitOfWork; + + public ReportService(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + public ReportSiteEventTypesViewModel GetReportSiteEventTypes(List sites, List eventTypes, string startTime, string endTime) + { + try + { + + var result = new ReportSiteEventTypesViewModel(); + + var events = _unitOfWork.EventRepository.GetEventBySitesAndEventType(sites, eventTypes, startTime, endTime); + var siteGroup = events.GroupBy(i => i.SiteId); + var eachSiteList = new List(); + + foreach (var s in sites) + { + var data = siteGroup.Where(i => i.Key == s); + var siteName = _unitOfWork.SiteInformationRepository.GetSiteInformationBySiteId(s).SiteName; + if (data.Any()) + { + var vm = new EachSiteEventTypesViewModel + { + SiteId = s, + SiteName = siteName, + NoStatusCount = data.FirstOrDefault().Count(i => Convert.ToInt16(i.Punished) == 0 && Convert.ToInt16(i.CheckPunish) == 0 && Convert.ToInt16(i.Rejected) == 0 && string.IsNullOrWhiteSpace(i.Ps)), + CheckPunishCount = data.FirstOrDefault().Count(i => Convert.ToInt16(i.CheckPunish) == 1), + RejectedCount = data.FirstOrDefault().Count(i => Convert.ToInt16(i.Rejected) == 1), + PunishCount = data.FirstOrDefault().Count(i => Convert.ToInt16(i.Punished) == 1), + NoPunishCount = data.FirstOrDefault().Count(i => Convert.ToInt16(i.Punished) == 0 && Convert.ToInt16(i.CheckPunish) == 0 && Convert.ToInt16(i.Rejected) == 0 && !string.IsNullOrWhiteSpace(i.Ps)), + EventTotalCount = data.FirstOrDefault().Count() + }; + eachSiteList.Add(vm); + } + else + { + var vm = new EachSiteEventTypesViewModel + { + SiteId = s, + SiteName = siteName, + NoStatusCount = 0, + CheckPunishCount = 0, + RejectedCount = 0, + PunishCount = 0, + NoPunishCount = 0, + EventTotalCount = 0, + }; + eachSiteList.Add(vm); + } + } + + var eventGroup = events.GroupBy(i => i.EventType); + var eachEventList = new List(); + + foreach (var e in eventTypes) + { + var data = eventGroup.Where(i => i.Key == e); + var eventName = _unitOfWork.EventTypeRepository.GetEventTypeByEventType(e).EventName; + if (data.Any()) + { + var vm = new EachEventTypesSiteViewModel + { + EventName = eventName, + NoStatusCount = data.FirstOrDefault().Count(i => Convert.ToInt16(i.Punished) == 0 && Convert.ToInt16(i.CheckPunish) == 0 && Convert.ToInt16(i.Rejected) == 0 && string.IsNullOrWhiteSpace(i.Ps)), + CheckPunishCount = data.FirstOrDefault().Count(i => Convert.ToInt16(i.CheckPunish) == 1), + RejectedCount = data.FirstOrDefault().Count(i => Convert.ToInt16(i.Rejected) == 1), + PunishCount = data.FirstOrDefault().Count(i => Convert.ToInt16(i.Punished) == 1), + NoPunishCount = data.FirstOrDefault().Count(i => Convert.ToInt16(i.Punished) == 0 && Convert.ToInt16(i.CheckPunish) == 0 && Convert.ToInt16(i.Rejected) == 0 && !string.IsNullOrWhiteSpace(i.Ps)), + EventTotalCount = data.FirstOrDefault().Count() + }; + eachEventList.Add(vm); + } + else + { + var vm = new EachEventTypesSiteViewModel + { + EventName = eventName, + NoStatusCount = 0, + CheckPunishCount = 0, + RejectedCount = 0, + PunishCount = 0, + NoPunishCount = 0, + EventTotalCount = 0, + }; + eachEventList.Add(vm); + } + } + + result.EachSiteEventTypesViewModel = eachSiteList.OrderBy(i => i.SiteId).ToList(); + result.EachEventTypesSiteViewModel = eachEventList; + + return result; + } + catch (Exception) + { + return new ReportSiteEventTypesViewModel(); + } + } + + public IEnumerable GetTycgTableName() + { + try + { + var datas = _unitOfWork.TycgRepository.GetTycgsTableName(); + + var result = new List(); + foreach (var data in datas) + { + var vm = new TycgTableNameViewModel(); + vm.InjectFrom(data); + vm.Id = data.Id; + if (string.IsNullOrWhiteSpace(data.APIName)) + { + vm.APIName = data.LogName; + } + result.Add(vm); + } + + return result; + } + catch (Exception ex) + { + return new List(); + } + } + + public IEnumerable GetTycgLogAll(string tycgTableName) + { + try + { + if (string.IsNullOrWhiteSpace(tycgTableName)) + { + return new List(); + } + + var datas = _unitOfWork.TycgRepository.GetTycgs(tycgTableName); + + var result = new List(); + foreach (var data in datas) + { + var value = data.Value.Split(';'); + var vm = new TycgViewModel(); + vm.InjectFrom(data); + vm.Id = data.Id; + vm.Time = JavaTimeStampToDateTime(data.Timestamp); + vm.ip = value.Length > 2 ? value[0] : ""; + vm.api = value.Length > 2 ? value[2] : ""; + result.Add(vm); + } + + return result.OrderByDescending(i => i.Time); + } + catch (Exception ex) + { + return new List(); + } + } + + public PageViewModel> GetTycgLog(string tycgTableName, SearchModel searchModel) + { + try + { + if (string.IsNullOrWhiteSpace(tycgTableName)) + { + return new PageViewModel>(); + } + + var datas = _unitOfWork.TycgRepository.GetTycgs(tycgTableName); + + int count = datas.Count(); + int pageCount = count % searchModel.PageSize != 0 ? (count / searchModel.PageSize) + 1 : count / searchModel.PageSize; + + datas = datas.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var result = new List(); + foreach (var data in datas) + { + var value = data.Value.Split(';'); + var vm = new TycgViewModel(); + vm.InjectFrom(data); + vm.Id = data.Id; + vm.Time = JavaTimeStampToDateTime(data.Timestamp); + vm.ip = value.Length > 2 ? value[0] : ""; + vm.api = value.Length > 2 ? value[2] : ""; + result.Add(vm); + } + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = result, + }; + } + catch (Exception ex) + { + return new PageViewModel>(); + } + } + + private static string JavaTimeStampToDateTime(double javaTimeStamp) + { + // Java timestamp is milliseconds past epoch + DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + var strdateTime = dateTime.AddMilliseconds(javaTimeStamp).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"); + return strdateTime; + } + + public List GetEventType1(ReportRequestViewModel viewModel) + { + try + { + var start = Convert.ToDateTime(viewModel.StartDate).ToString("yyyy-MM-dd 00:00:00"); + var end = Convert.ToDateTime(viewModel.EndDate).ToString("yyyy-MM-dd 23:59:59"); + var data = _unitOfWork.EventRepository.GetEventBySitesAndEventType(viewModel.Sites, new List { "1" }, start, end); + + data = data.Where(i => Convert.ToDateTime(i.InTime).Hour >= viewModel.StartTime && Convert.ToDateTime(i.InTime).Hour <= viewModel.EndTime); + + var result = new List(); + var vmdata = data.Where(i => (Convert.ToDateTime(i.OutTime) - Convert.ToDateTime(i.InTime)).Minutes > 1 && (Convert.ToDateTime(i.OutTime) - Convert.ToDateTime(i.InTime)).Minutes <= 2); + var vm1 = new ReportEventType1ViewModel + { + DateTime = "一至兩分鐘", + CarCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Car).ToString()), + BusCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Coach).ToString()), + TaxiCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Taxi).ToString()), + MotorcycleCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Motorcycle).ToString()), + HasNumber = vmdata.Count(i => !string.IsNullOrWhiteSpace(i.Number)), + HasNoNumber = vmdata.Count(i => string.IsNullOrWhiteSpace(i.Number)) + }; + result.Add(vm1); + + vmdata = data.Where(i => (Convert.ToDateTime(i.OutTime) - Convert.ToDateTime(i.InTime)).Minutes > 2 && (Convert.ToDateTime(i.OutTime) - Convert.ToDateTime(i.InTime)).Minutes <= 3); + var vm2 = new ReportEventType1ViewModel + { + DateTime = "兩至三分鐘", + CarCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Car).ToString()), + BusCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Coach).ToString()), + TaxiCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Taxi).ToString()), + MotorcycleCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Motorcycle).ToString()), + HasNumber = vmdata.Count(i => !string.IsNullOrWhiteSpace(i.Number)), + HasNoNumber = vmdata.Count(i => string.IsNullOrWhiteSpace(i.Number)) + }; + result.Add(vm2); + + vmdata = data.Where(i => (Convert.ToDateTime(i.OutTime) - Convert.ToDateTime(i.InTime)).Minutes > 3); + var vm3 = new ReportEventType1ViewModel + { + DateTime = "兩至三分鐘", + CarCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Car).ToString()), + BusCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Coach).ToString()), + TaxiCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Taxi).ToString()), + MotorcycleCount = vmdata.Count(i => i.VehicleType == ((int)EnumVehicleType.Motorcycle).ToString()), + HasNumber = vmdata.Count(i => !string.IsNullOrWhiteSpace(i.Number)), + HasNoNumber = vmdata.Count(i => string.IsNullOrWhiteSpace(i.Number)) + }; + result.Add(vm3); + + var vm = new ReportEventType1ViewModel + { + DateTime = "總數", + CarCount = vm1.CarCount + vm2.CarCount + vm3.CarCount, + BusCount = vm1.BusCount + vm2.BusCount + vm3.BusCount, + TaxiCount = vm1.TaxiCount + vm2.TaxiCount + vm3.TaxiCount, + MotorcycleCount = vm1.MotorcycleCount + vm2.MotorcycleCount + vm3.MotorcycleCount, + HasNumber = vm1.HasNumber + vm2.HasNumber + vm3.HasNumber, + HasNoNumber = vm1.HasNoNumber + vm2.HasNoNumber + vm3.HasNoNumber, + }; + result.Add(vm); + + return result; + } + catch (Exception ex) + { + return new List(); + } + } + + public List GetEventType2(ReportRequestViewModel viewModel) + { + try + { + var start = Convert.ToDateTime(viewModel.StartDate).ToString("yyyy-MM-dd 00:00:00"); + var end = Convert.ToDateTime(viewModel.EndDate).ToString("yyyy-MM-dd 23:59:59"); + var data = _unitOfWork.EventRepository.GetEventBySitesAndEventType(viewModel.Sites, new List { "2" }, start, end); + + data = data.Where(i => Convert.ToDateTime(i.InTime).Hour >= viewModel.StartTime && Convert.ToDateTime(i.InTime).Hour <= viewModel.EndTime); + + var result = new List(); + var vm = new ReportEventType2ViewModel + { + Speed = "~80 km/h", + Count = data.Count(i => Convert.ToDouble(i.Speed) <= 80) + }; + result.Add(vm); + vm = new ReportEventType2ViewModel + { + Speed = "80~90 km/h", + Count = data.Count(i => Convert.ToDouble(i.Speed) > 80 && Convert.ToDouble(i.Speed) <= 90) + }; + result.Add(vm); + vm = new ReportEventType2ViewModel + { + Speed = "90~100 km/h", + Count = data.Count(i => Convert.ToDouble(i.Speed) > 90 && Convert.ToDouble(i.Speed) <= 100) + }; + result.Add(vm); + vm = new ReportEventType2ViewModel + { + Speed = "100~ km/h", + Count = data.Count(i => Convert.ToDouble(i.Speed) > 100) + }; + result.Add(vm); + + return result; + } + catch (Exception) + { + return new List(); + } + } + + public List GetEventType34(ReportRequestViewModel viewModel) + { + try + { + var start = Convert.ToDateTime(viewModel.StartDate).ToString("yyyy-MM-dd 00:00:00"); + var end = Convert.ToDateTime(viewModel.EndDate).ToString("yyyy-MM-dd 23:59:59"); + var data = _unitOfWork.EventRepository.GetEventBySitesAndEventType(viewModel.Sites, new List { "3", "4" }, start, end); + + data = data.Where(i => Convert.ToDateTime(i.InTime).Hour >= viewModel.StartTime && Convert.ToDateTime(i.InTime).Hour <= viewModel.EndTime); + + var result = new List(); + var vm = new ReportEventType34ViewModel + { + CarCount = data.Count(i => i.VehicleType == ((int)EnumVehicleType.Car).ToString()), + CoachCount = data.Count(i => i.VehicleType == ((int)EnumVehicleType.Coach).ToString()), + TruckCount = data.Count(i => i.VehicleType == ((int)EnumVehicleType.Truck).ToString()), + }; + result.Add(vm); + + return result; + } + catch (Exception ex) + { + return new List(); + } + } + + public List GetEventType6(ReportRequestViewModel viewModel) + { + try + { + var start = Convert.ToDateTime(viewModel.StartDate).ToString("yyyy-MM-dd 00:00:00"); + var end = Convert.ToDateTime(viewModel.EndDate).ToString("yyyy-MM-dd 23:59:59"); + var data = _unitOfWork.EventRepository.GetEventBySitesAndEventType(viewModel.Sites, new List { "6" }, start, end); + + data = data.Where(i => Convert.ToDateTime(i.InTime).Hour >= viewModel.StartTime && Convert.ToDateTime(i.InTime).Hour <= viewModel.EndTime); + + var result = new List(); + var vm = new ReportEventType6ViewModel + { + Ton = "0~15噸", + Count = data.Count(i => Convert.ToDouble(i.Ton) <= 15) + }; + result.Add(vm); + vm = new ReportEventType6ViewModel + { + Ton = "15~20噸", + Count = data.Count(i => Convert.ToDouble(i.Ton) > 15 && Convert.ToDouble(i.Ton) <= 20) + }; + result.Add(vm); + vm = new ReportEventType6ViewModel + { + Ton = "20~25噸", + Count = data.Count(i => Convert.ToDouble(i.Ton) > 20 && Convert.ToDouble(i.Ton) <= 25) + }; + result.Add(vm); + vm = new ReportEventType6ViewModel + { + Ton = "25~30噸", + Count = data.Count(i => Convert.ToDouble(i.Ton) > 25 && Convert.ToDouble(i.Ton) <= 30) + }; + result.Add(vm); + vm = new ReportEventType6ViewModel + { + Ton = "30噸以上", + Count = data.Count(i => Convert.ToDouble(i.Ton) > 30) + }; + result.Add(vm); + return result; + } + catch (Exception ex) + { + return new List(); + } + } + + public List GetMalfunction(ReportRequestViewModel viewModel) + { + try + { + + DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 當地時區 + var start = ((DateTimeOffset)Convert.ToDateTime(viewModel.StartDate)).ToUnixTimeSeconds().ToString(); + var end = ((DateTimeOffset)Convert.ToDateTime(viewModel.EndDate).AddDays(1)).ToUnixTimeSeconds().ToString(); + var data = _unitOfWork.MalfunctionRepository.GetMalfunctions(viewModel.Sites, start, end); + + var result = new List(); + foreach (var item in data) + { + DateTime dt = startTime.AddSeconds(Convert.ToInt32(item.Timestamp)); + + var vm = new ReportMalfunctionViewModel + { + Time = dt.ToString("yyyy-MM-dd HH:mm:ss"), + SiteId = item.Siteid, + SiteName = item.SiteName, + CompanyCode = item.CompanyCode, + DeviceID = item.DeviceID, + DeviceType = item.DeviceType, + Message = item.Message, + }; + result.Add(vm); + } + + result = result.Where(i => Convert.ToDateTime(i.Time).Hour >= viewModel.StartTime && Convert.ToDateTime(i.Time).Hour < viewModel.EndTime + 1).ToList(); + result = result.OrderBy(i => i.SiteId).ToList(); + return result; + } + catch (Exception ex) + { + return new List(); + } + } + } +} diff --git a/Traffic.Service/Implements/RoleService.cs b/Traffic.Service/Implements/RoleService.cs new file mode 100644 index 0000000..9048116 --- /dev/null +++ b/Traffic.Service/Implements/RoleService.cs @@ -0,0 +1,209 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class RoleService : IRoleService + { + private readonly IUnitOfWork _unitOfWork; + + public RoleService(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + /// + /// 新增權限 + /// + /// + /// + public TradeResultModel PostRoleDataList(int byWho, RoleData roleData) + { + var result = new TradeResultModel { Success = false }; + try + { + roleData.RoleName = roleData.RoleName; + roleData.CreatedOn = roleData.CreatedOn; + roleData.CreatedOn = DateTime.UtcNow.AddHours(8); + roleData.Status = roleData.Status; + + var role = new AccountRole() + { + RoleName = roleData.RoleName, + CreatorId = byWho, + CreatedOn = roleData.CreatedOn, + + }; + + var id = _unitOfWork.AccountRepository.InsertAccountRole(role); + _unitOfWork.Complete(); + } + catch (Exception ex) + { + result.Message = ex.Message; + return result; + } + result.Success = true; + return result; + } + + /// + /// 取得所有權限清單 + /// + /// + public PageViewModel> GetRoleDataList(SearchModel searchModel) + { + var roles = _unitOfWork.AccountRepository.GetAccountRoles(); + + if (!string.IsNullOrEmpty(searchModel.Term)) + { + roles = roles.Where(x => x.RoleName.Contains(searchModel.Term)); + } + int count = -1; + int pageCount = -1; + if (searchModel.Page == 1) + { + count = roles.Count(); + if (count % 10 != 0) + { + pageCount = (count / searchModel.PageSize) + 1; + } + else + { + pageCount = count / searchModel.PageSize; + } + } + switch (searchModel.Order) + { + case "Id": + roles = searchModel.IsAsc ? roles.OrderBy(x => x.Id) : roles.OrderByDescending(x => x.Id); + break; + case "RoleName": + roles = searchModel.IsAsc ? roles.OrderBy(x => x.RoleName).ThenBy(x => x.Id) : roles.OrderByDescending(x => x.RoleName).ThenByDescending(x => x.Id); + break; + default: + goto case "Id"; + } + + roles = roles.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var data = roles.ToList().Select(x => new RoleDataQuery + { + Id = x.Id, + RoleName = x.RoleName, + CreateID = x.CreatorId, + CreateTime = x.CreatedOn.ToString(), + }); + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = data, + }; + } + + /// + /// 取得群組對應碼 + /// + /// + public IEnumerable GetRoleInfoList() + { + var roles = _unitOfWork.AccountRepository.GetAccountRoles(); + var result = roles.ToList().Select(x => new RoleCodeInfo + { + Id = x.Id, + RoleName = x.RoleName + }); + return result; + } + + /// + /// 取得權限設定 + /// + /// + /// + public List GetRolePermissionInfo(int? roleId) + { + var rolePageList = _unitOfWork.RolePageRepository.GetRolePermissionInfo(roleId); + var result = rolePageList.ToList().Select(x => new RolePermissionDataQuery + { + RoleId = x.RoleId, + RoleName = x.RoleName, + PageId = x.PageId, + PageName = x.PageName + }); + return result.ToList(); + } + + public List GetAllPagePermission(int roleId) + { + var pages = _unitOfWork.RolePageRepository.GetPageLists(); + var PagePermission = new List(); + var hasPermission = _unitOfWork.RolePageRepository.GetRolePageByRoleId(roleId); + foreach (var item in pages) + { + if (hasPermission.Where(i=>i.PageId == item.Id).Any()) + { + PagePermission.Add(new PagePermissionDataQuery + { + PageId = item.Id, + PageName = item.PageName, + PageModule = item.PageModule, + RoleId = roleId, + PageUrl = item.PageURL, + Enable = true + }); + } + else + { + PagePermission.Add(new PagePermissionDataQuery + { + PageId = item.Id, + PageName = item.PageName, + PageModule = item.PageModule, + RoleId = roleId, + PageUrl = item.PageURL, + Enable = false + }); + } + } + + return PagePermission.ToList(); + } + + /// + /// 修改權限狀態 + /// + /// + /// + public bool PutPageRoleStatus(PagePermissionData pagePermission) + { + if (pagePermission.Enable) + { + _unitOfWork.RolePageRepository.InsertRolePage(new RolePage() + { + PageId = pagePermission.PageId, + RoleId = pagePermission.RoleId + }); + _unitOfWork.Complete(); + return true; + } + + var rolePage = _unitOfWork.RolePageRepository.GetRolePages().Where(x => x.PageId == pagePermission.PageId && x.RoleId == pagePermission.RoleId).FirstOrDefault(); + if (rolePage != null) + { + _unitOfWork.RolePageRepository.DeleteRolePage(rolePage.Id); + _unitOfWork.Complete(); + return true; + } + return false; + } + } +} diff --git a/Traffic.Service/Implements/SiteInformationService.cs b/Traffic.Service/Implements/SiteInformationService.cs new file mode 100644 index 0000000..1c1b6e0 --- /dev/null +++ b/Traffic.Service/Implements/SiteInformationService.cs @@ -0,0 +1,245 @@ +using Omu.ValueInjecter; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; +using Traffic.Repository.Infrastructures; +using Traffic.Service.Interfaces; + +namespace Traffic.Service.Implements +{ + public class SiteInformationService : ISiteInformationService + { + private readonly IUnitOfWork _unitOfWork; + + public SiteInformationService(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + public IEnumerable GetSiteInformations() + { + var datas = _unitOfWork.SiteInformationRepository.GetSiteInformations(); + var result = new List(); + var eventTypes = _unitOfWork.EventTypeRepository.GetEventTypes(); + var companys = _unitOfWork.CompanyInformationRepository.GetCompanyInformations(); + foreach (var data in datas) + { + var eventType = eventTypes.Where(i => i.EventType == data.EventType); + var vm = new SiteInformationViewModel(); + vm.InjectFrom(data); + vm.Id = data.Id; + vm.EventName = eventType.Any() ? eventType.FirstOrDefault().EventName : string.Empty; + var company = companys.Where(o => o.CompanyCode == vm.CompanyCode); + if (company.Any()) + { + vm.CompanyName = company.FirstOrDefault(i => i.CompanyCode == data.CompanyCode).CompanyName; + vm.CompanyEmail = company.FirstOrDefault(i => i.CompanyCode == data.CompanyCode).Email; + } + result.Add(vm); + } + + return result; + } + + public IEnumerable GetSiteInformationsByUser(int userId) + { + var sites = GetSiteInformations(); + var userSites = _unitOfWork.AccountRepository.GetAccountUserSite(userId); + + var result = new List(); + foreach (var item in userSites) + { + var site = sites.Where(i => i.Id == item.SiteId); + if (site.Any()) + { + result.Add(site.FirstOrDefault()); + } + } + + return result; + } + + public IEnumerable GetSiteInformationsByEventTypes(List eventTypes) + { + var datas = _unitOfWork.SiteInformationRepository.GetSiteInformations(eventTypes); + var result = new List(); + var eventTypeList = _unitOfWork.EventTypeRepository.GetEventTypes(); + var companys = _unitOfWork.CompanyInformationRepository.GetCompanyInformations(); + foreach (var data in datas) + { + var eventType = eventTypeList.Where(i => i.EventType == data.EventType); + var vm = new SiteInformationViewModel(); + vm.InjectFrom(data); + vm.Id = data.Id; + vm.EventName = eventType.Any() ? eventType.FirstOrDefault().EventName : string.Empty; + var company = companys.Where(o => o.CompanyCode == vm.CompanyCode); + if (company.Any()) + { + vm.CompanyName = company.FirstOrDefault(i => i.CompanyCode == data.CompanyCode).CompanyName; + vm.CompanyEmail = company.FirstOrDefault(i => i.CompanyCode == data.CompanyCode).Email; + } + result.Add(vm); + } + + return result; + } + + public PageViewModel> GetSiteInformations(SearchModel searchModel) + { + var datas = _unitOfWork.SiteInformationRepository.GetSiteInformations(); + + if (!string.IsNullOrEmpty(searchModel.Term)) + { + datas = datas.Where(x => x.County.Contains(searchModel.Term) || x.SiteID.Contains(searchModel.Term)); + } + + int count = datas.Count(); + int pageCount = count % searchModel.PageSize != 0 ? (count / searchModel.PageSize) + 1 : count / searchModel.PageSize; + + switch (searchModel.Order.ToLower()) + { + case "id": + default: + datas = searchModel.IsAsc ? datas.OrderBy(x => x.Id) : datas.OrderByDescending(x => x.Id); + break; + case "county": + datas = searchModel.IsAsc ? datas.OrderBy(x => x.County).ThenBy(x => x.Id) : datas.OrderByDescending(x => x.County).ThenByDescending(x => x.Id); + break; + case "area": + datas = searchModel.IsAsc ? datas.OrderBy(x => x.Area).ThenBy(x => x.Id) : datas.OrderByDescending(x => x.Area).ThenByDescending(x => x.Id); + break; + case "siteid": + datas = searchModel.IsAsc ? datas.OrderBy(x => x.SiteID).ThenBy(x => x.Id) : datas.OrderByDescending(x => x.SiteID).ThenByDescending(x => x.Id); + break; + case "sitename": + datas = searchModel.IsAsc ? datas.OrderBy(x => x.SiteName).ThenBy(x => x.Id) : datas.OrderByDescending(x => x.SiteName).ThenByDescending(x => x.Id); + break; + } + + var eventTypes = _unitOfWork.EventTypeRepository.GetEventTypes(); + + datas = datas.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize); + var result = new List(); + var companys = _unitOfWork.CompanyInformationRepository.GetCompanyInformations(); + foreach (var data in datas) + { + var eventType = eventTypes.Where(i => i.EventType == data.EventType); + var vm = new SiteInformationViewModel(); + vm.InjectFrom(data); + vm.Id = data.Id; + vm.EventName = eventType.Any() ? eventType.FirstOrDefault().EventName : string.Empty; + var company = companys.Where(o => o.CompanyCode == vm.CompanyCode); + if (company.Any()) + { + vm.CompanyName = company.FirstOrDefault(i => i.CompanyCode == data.CompanyCode).CompanyName; + vm.CompanyEmail = company.FirstOrDefault(i => i.CompanyCode == data.CompanyCode).Email; + } + result.Add(vm); + } + + return new PageViewModel> + { + RowCount = count, + PageCount = pageCount, + CurrentPage = searchModel.Page, + Data = result, + }; + } + + public SiteInformationViewModel GetSiteInformationById(int id) + { + try + { + var data = _unitOfWork.SiteInformationRepository.GetSiteInformationById(id); + if (data != null) + { + var eventType = _unitOfWork.EventTypeRepository.GetEventTypeByEventType(data.EventType); + var result = new SiteInformationViewModel(); + result.InjectFrom(data); + result.Id = data.Id; + result.EventName = eventType != null ? eventType.EventName : string.Empty; + var companys = _unitOfWork.CompanyInformationRepository.GetCompanyInformations(); + var company = companys.Where(o => o.CompanyCode == data.CompanyCode); + if (company.Any()) + { + result.CompanyName = company.FirstOrDefault(i => i.CompanyCode == data.CompanyCode).CompanyName; + result.CompanyEmail = company.FirstOrDefault(i => i.CompanyCode == data.CompanyCode).Email; + } + return result; + } + else + { + return null; + } + } + catch (Exception ex) + { + return null; + } + } + + public TradeResultModel InsertSiteInformation(SiteInformationViewModel viewModel) + { + try + { + var eventType = _unitOfWork.EventTypeRepository.GetEventTypeByEventType(viewModel.EventType); + if (eventType == null) + { + return new TradeResultModel { Success = false, Message = "查無此事件類型" }; + } + + var data = new SiteInformation(); + data.InjectFrom(viewModel); + + var result = _unitOfWork.SiteInformationRepository.InsertSiteInformation(data); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "新增成功" : "新增失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel UpdatSiteInformation(int id, SiteInformationViewModel viewModel) + { + try + { + var data = new SiteInformation(); + data.InjectFrom(viewModel); + data.Id = id; + var result = _unitOfWork.SiteInformationRepository.UpdateSiteInformation(data); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "修改成功" : "修改失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + + public TradeResultModel DeleteSiteInformation(int id) + { + try + { + var result = _unitOfWork.SiteInformationRepository.DeleteSiteInformation(id); + _unitOfWork.Complete(); + + return new TradeResultModel { Success = result, Message = result ? "刪除成功" : "刪除失敗" }; + } + catch (Exception ex) + { + _unitOfWork.Rollback(); + return new TradeResultModel() { Success = false, Message = ex.ToString() }; + } + } + } +} diff --git a/Traffic.Service/Interfaces/IAccountService.cs b/Traffic.Service/Interfaces/IAccountService.cs new file mode 100644 index 0000000..d778586 --- /dev/null +++ b/Traffic.Service/Interfaces/IAccountService.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Enums; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IAccountService + { + public TradeResultModel InserAccountUser(int byWho, UserData account); + public TradeResultModel UpdateAccountbyAdmin(int byWho, UserData account); + public TradeResultModel UpdateAccountbyUser(int byWho, UserData account); + public TradeResultModel UpdateAccountPasswordbyAdmin(int id, int byWho); + public TradeResultModel UpdateAccountPasswordByUser(int ByWho, UserData accountViewModel); + public TradeResultModel DeleteUserData(int id); + + public AccountUserViewModel GetAccountUser(int id); + public bool GetExistUser(string account); + public PageViewModel> GetUserDataList(SearchModel searchModel, int? id); + public IEnumerable GetUserNameList(); + public IEnumerable GetUserSite(int id); + public IEnumerable GetUserSiteInfo(int id); + public TradeResultModel PutUserbyAdmin(int byWho, int id, int status); + } +} diff --git a/Traffic.Service/Interfaces/IAnnounceService.cs b/Traffic.Service/Interfaces/IAnnounceService.cs new file mode 100644 index 0000000..e404046 --- /dev/null +++ b/Traffic.Service/Interfaces/IAnnounceService.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IAnnounceService + { + public PageViewModel> GetAnnounces(SearchModel searchModel); + + public AnnounceViewModel GetAnnounceById(int id); + + public TradeResultModel InsertAnnounce(int byWho, AnnounceInsertViewModel viewModel); + + public TradeResultModel UpdatAnnounce(int id, AnnounceInsertViewModel Announce, int byWho); + + public TradeResultModel DeleteAnnounce(int id); + } +} diff --git a/Traffic.Service/Interfaces/ICompanyInformationService.cs b/Traffic.Service/Interfaces/ICompanyInformationService.cs new file mode 100644 index 0000000..7350f6c --- /dev/null +++ b/Traffic.Service/Interfaces/ICompanyInformationService.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface ICompanyInformationService + { + public IEnumerable GetCompanyInformations(); + + public IEnumerable GetCompanyInformationsEmailNotNull(); + + public PageViewModel> GetCompanyInformations(SearchModel searchModel); + + public CompanyInformationViewModel GetCompanyInformationById(int id); + + public TradeResultModel InsertCompanyInformation(CompanyInformationViewModel CompanyInformation); + + public TradeResultModel UpdatCompanyInformation(int id, CompanyInformationViewModel CompanyInformation); + + public TradeResultModel DeleteCompanyInformation(int id); + } +} diff --git a/Traffic.Service/Interfaces/IEventService.cs b/Traffic.Service/Interfaces/IEventService.cs new file mode 100644 index 0000000..ae48dfc --- /dev/null +++ b/Traffic.Service/Interfaces/IEventService.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IEventService + { + public PageViewModel> GetEventsByCar(SearchModel searchModel); + + public PageViewModel> GetEventBySites(string id, SearchModel model); + + public PageViewModel> GetEventByEventType(int userId, string eventType, SearchModel searchModel); + + public IEnumerable GetEventsByEventType(int id, string eventType, string startTime, string endTime, string site, string status, string time, string speed); + + public EventViewModel GetEventById(int id); + + public int GetThisYearEventsCount(string account); + + public int GetThisMonthEventsCount(string account); + + public EventCountViewModel GetEventsCount(string startDatetime, string endDatetime); + + public TradeResultModel InsertEvent(EventViewModel Event); + + public TradeResultModel UpdatEvent(int id, EventViewModel Event); + + public TradeResultModel UpdatEventCheckPunish(string account, int eventId, string checkPunish, string law); + + public TradeResultModel UpdatEventCheckPunishList(string account, List eventId, string checkPunish, string law); + + public TradeResultModel UpdatEventNoPunish(string account, int eventId, string reason); + + public TradeResultModel UpdatEventCancel(string account, int id); + + public TradeResultModel UpdatEventVehicleType(int id, string vehicleType); + + public TradeResultModel UpdatEventVehicleNumber(int id, string vehicleNumber); + + public TradeResultModel DeleteEvent(int id); + + public TradeResultModel UpdatEventVehicle(int id, string vehicleType, string vehicleNumber); + + public IEnumerable GetVehicleTypes(); + } +} diff --git a/Traffic.Service/Interfaces/IEventTypeService.cs b/Traffic.Service/Interfaces/IEventTypeService.cs new file mode 100644 index 0000000..b2495eb --- /dev/null +++ b/Traffic.Service/Interfaces/IEventTypeService.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IEventTypeService + { + public IEnumerable GetEventTypes(); + + public IEnumerable GetEventType1s(); + + public PageViewModel> GetEventTypes(SearchModel searchModel); + + public EventTypeViewModel GetEventTypeById(int id); + + public EventTypeViewModel GetEventTypeByEventType(string eventType); + + public TradeResultModel InsertEventType(EventTypeViewModel EventType); + + public TradeResultModel UpdatEventType(int id, EventTypeViewModel EventType); + + public TradeResultModel DeleteEventType(int id); + } +} diff --git a/Traffic.Service/Interfaces/IFileService.cs b/Traffic.Service/Interfaces/IFileService.cs new file mode 100644 index 0000000..3e4af3d --- /dev/null +++ b/Traffic.Service/Interfaces/IFileService.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IFileService + { + public string ExportGetTycgLog(string tableName, IEnumerable data); + public string ExportEvent(string startTime, string endTime, string eventName, IEnumerable events); + public string ExportGetEventType1(string startTime, string endTime, List data); + public string ExportGetEventType2(string startTime, string endTime, List data); + public string ExportGetEventType34(string startTime, string endTime, List data); + public string ExportGetEventType6(string startTime, string endTime, List data); + public string ExportGetMalfunction(string startTime, string endTime, List data); + public string ExportGetSiteEvent(string startTime, string endTime, ReportSiteEventTypesViewModel data); + } +} diff --git a/Traffic.Service/Interfaces/ILoginService.cs b/Traffic.Service/Interfaces/ILoginService.cs new file mode 100644 index 0000000..9f1ce88 --- /dev/null +++ b/Traffic.Service/Interfaces/ILoginService.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface ILoginService + { + /// + /// 登入 + /// + /// + AccountUserViewModel Login(string account, string password, string ip = ""); + } +} diff --git a/Traffic.Service/Interfaces/IMailService.cs b/Traffic.Service/Interfaces/IMailService.cs new file mode 100644 index 0000000..777ef47 --- /dev/null +++ b/Traffic.Service/Interfaces/IMailService.cs @@ -0,0 +1,12 @@ +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IMailService + { + /// + /// 傳送 Mail + /// + public void SendMail(MailViewModel mailViewModel); + } +} diff --git a/Traffic.Service/Interfaces/IMalfunctionService.cs b/Traffic.Service/Interfaces/IMalfunctionService.cs new file mode 100644 index 0000000..2a28c02 --- /dev/null +++ b/Traffic.Service/Interfaces/IMalfunctionService.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IMalfunctionService + { + //public PageViewModel> GetMalfunctions(SearchModel searchModel); + + IEnumerable GetMalfunctions(int userid); + IEnumerable GetMalfunctionsOld(int userid); + + //public MalfunctionViewModel GetMalfunctionById(int id); + + //public TradeResultModel InsertMalfunction(MalfunctionViewModel Malfunction); + + //public TradeResultModel UpdatMalfunction(int id, MalfunctionViewModel Malfunction); + + //public TradeResultModel DeleteMalfunction(int id); + } +} diff --git a/Traffic.Service/Interfaces/INotPunishService.cs b/Traffic.Service/Interfaces/INotPunishService.cs new file mode 100644 index 0000000..dfc871a --- /dev/null +++ b/Traffic.Service/Interfaces/INotPunishService.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface INotPunishService + { + public IEnumerable GetNotPunishs(); + + public PageViewModel> GetNotPunishs(SearchModel searchModel); + + public NotPunishViewModel GetNotPunishById(int id); + + public TradeResultModel InsertNotPunish(NotPunishViewModel NotPunish); + + public TradeResultModel UpdatNotPunish(int id, NotPunishViewModel NotPunish); + + public TradeResultModel DeleteNotPunish(int id); + } +} diff --git a/Traffic.Service/Interfaces/IPageListService.cs b/Traffic.Service/Interfaces/IPageListService.cs new file mode 100644 index 0000000..e28f7c6 --- /dev/null +++ b/Traffic.Service/Interfaces/IPageListService.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IPageListService + { + TradeResultModel PostPageDataList(PageData pageData); + + TradeResultModel DeletePageData(int id); + + TradeResultModel PutPageData(PageData pageData); + + PageViewModel> GetPageDataList(SearchModel searchModel); + } +} diff --git a/Traffic.Service/Interfaces/IPoliceStationService.cs b/Traffic.Service/Interfaces/IPoliceStationService.cs new file mode 100644 index 0000000..9d4c1de --- /dev/null +++ b/Traffic.Service/Interfaces/IPoliceStationService.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IPoliceStationService + { + public PageViewModel> GetPoliceStations(SearchModel searchModel); + + public PoliceStationViewModel GetPoliceStationById(int id); + + public TradeResultModel InsertPoliceStation(PoliceStationViewModel PoliceStation); + + public TradeResultModel UpdatPoliceStation(PoliceStationViewModel PoliceStation); + + public TradeResultModel DeletePoliceStation(int id); + + IEnumerable GetGroupNameList(); + } +} diff --git a/Traffic.Service/Interfaces/IRepairService.cs b/Traffic.Service/Interfaces/IRepairService.cs new file mode 100644 index 0000000..b95e77d --- /dev/null +++ b/Traffic.Service/Interfaces/IRepairService.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IRepairService + { + public IEnumerable GetRepairs(); + + public PageViewModel> GetRepairs(SearchModel searchModel); + + public RepairViewModel GetRepairById(int id); + + public TradeResultModel InsertRepair(RepairViewModel Repair); + + public TradeResultModel UpdatRepair(int id, RepairViewModel Repair); + + public TradeResultModel DeleteRepair(int id); + } +} diff --git a/Traffic.Service/Interfaces/IReportService.cs b/Traffic.Service/Interfaces/IReportService.cs new file mode 100644 index 0000000..8dcfe3a --- /dev/null +++ b/Traffic.Service/Interfaces/IReportService.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IReportService + { + public IEnumerable GetTycgLogAll(string tycgTableName); + public PageViewModel> GetTycgLog(string tycgTableName, SearchModel searchModel); + public ReportSiteEventTypesViewModel GetReportSiteEventTypes(List sites, List eventTypes, string startTime, string endTime); + public List GetEventType1(ReportRequestViewModel viewModel); + public List GetEventType2(ReportRequestViewModel viewModel); + public List GetEventType34(ReportRequestViewModel viewModel); + public List GetEventType6(ReportRequestViewModel viewModel); + public List GetMalfunction(ReportRequestViewModel viewModel); + public IEnumerable GetTycgTableName(); + } +} diff --git a/Traffic.Service/Interfaces/IRoleService.cs b/Traffic.Service/Interfaces/IRoleService.cs new file mode 100644 index 0000000..4ced1ed --- /dev/null +++ b/Traffic.Service/Interfaces/IRoleService.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.Models; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface IRoleService + { + public TradeResultModel PostRoleDataList(int byWho, RoleData roleData); + public PageViewModel> GetRoleDataList(SearchModel searchModel); + public IEnumerable GetRoleInfoList(); + public List GetRolePermissionInfo(int? roleId); + public List GetAllPagePermission(int roleId); + public bool PutPageRoleStatus(PagePermissionData pagePermission); + } +} diff --git a/Traffic.Service/Interfaces/ISiteInformationService.cs b/Traffic.Service/Interfaces/ISiteInformationService.cs new file mode 100644 index 0000000..8f7f12a --- /dev/null +++ b/Traffic.Service/Interfaces/ISiteInformationService.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Traffic.Data.ViewModels; + +namespace Traffic.Service.Interfaces +{ + public interface ISiteInformationService + { + public IEnumerable GetSiteInformations(); + + public IEnumerable GetSiteInformationsByUser(int userId); + + public IEnumerable GetSiteInformationsByEventTypes(List eventTypes); + + public PageViewModel> GetSiteInformations(SearchModel searchModel); + + public SiteInformationViewModel GetSiteInformationById(int id); + + public TradeResultModel InsertSiteInformation(SiteInformationViewModel SiteInformation); + + public TradeResultModel UpdatSiteInformation(int id, SiteInformationViewModel SiteInformation); + + public TradeResultModel DeleteSiteInformation(int id); + } +} diff --git a/Traffic.Service/Traffic.Service.csproj b/Traffic.Service/Traffic.Service.csproj new file mode 100644 index 0000000..10eebdb --- /dev/null +++ b/Traffic.Service/Traffic.Service.csproj @@ -0,0 +1,22 @@ + + + + net5.0 + + + + + + + + + + + + + + + + + + diff --git a/Traffic.sln b/Traffic.sln new file mode 100644 index 0000000..cfa05e5 --- /dev/null +++ b/Traffic.sln @@ -0,0 +1,43 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31402.337 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Traffic.Api", "Traffic.Api\Traffic.Api.csproj", "{9D2C8E49-71BC-480C-A0CE-F516FFC0DDF7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Traffic.Data", "Traffic.Data\Traffic.Data.csproj", "{378C75B2-A5D3-4D21-8647-D5DECAB528FE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Traffic.Repository", "Traffic.Repository\Traffic.Repository.csproj", "{5B452AF6-AD05-4587-8466-6537521E2A4A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Traffic.Service", "Traffic.Service\Traffic.Service.csproj", "{112B3182-C054-4AC5-8E10-EE1CB1C16BBB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9D2C8E49-71BC-480C-A0CE-F516FFC0DDF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9D2C8E49-71BC-480C-A0CE-F516FFC0DDF7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9D2C8E49-71BC-480C-A0CE-F516FFC0DDF7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9D2C8E49-71BC-480C-A0CE-F516FFC0DDF7}.Release|Any CPU.Build.0 = Release|Any CPU + {378C75B2-A5D3-4D21-8647-D5DECAB528FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {378C75B2-A5D3-4D21-8647-D5DECAB528FE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {378C75B2-A5D3-4D21-8647-D5DECAB528FE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {378C75B2-A5D3-4D21-8647-D5DECAB528FE}.Release|Any CPU.Build.0 = Release|Any CPU + {5B452AF6-AD05-4587-8466-6537521E2A4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5B452AF6-AD05-4587-8466-6537521E2A4A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5B452AF6-AD05-4587-8466-6537521E2A4A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5B452AF6-AD05-4587-8466-6537521E2A4A}.Release|Any CPU.Build.0 = Release|Any CPU + {112B3182-C054-4AC5-8E10-EE1CB1C16BBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {112B3182-C054-4AC5-8E10-EE1CB1C16BBB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {112B3182-C054-4AC5-8E10-EE1CB1C16BBB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {112B3182-C054-4AC5-8E10-EE1CB1C16BBB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3091E7C6-1801-4FA9-BE3F-BB2476E3B358} + EndGlobalSection +EndGlobal