commit 896fd63a2de78986161dfcf31a9bc662fd9a115c Author: Luis Angel Rendon Arrazola Date: Wed Apr 5 17:28:34 2023 -0500 5 abril 2023 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..75bd10e --- /dev/null +++ b/.gitignore @@ -0,0 +1,400 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +bin/* +Bin/* +obj/* +Obj/* +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# 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 +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# 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/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# 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 +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..fff059a --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,36 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/bin/Debug/net6.0/AOLBackend.dll", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+https?://\\S+", + "uriFormat": "https://localhost:5050/swagger/index.html" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..e8f94ed --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,41 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/AOLBackend.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/AOLBackend.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/AOLBackend.csproj" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/AOLBackend.csproj b/AOLBackend.csproj new file mode 100644 index 0000000..dc86edf --- /dev/null +++ b/AOLBackend.csproj @@ -0,0 +1,22 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + + + + + diff --git a/AOLBackend.sln b/AOLBackend.sln new file mode 100644 index 0000000..bb2c066 --- /dev/null +++ b/AOLBackend.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32526.322 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AOLBackend", "AOLBackend.csproj", "{7200C42A-214F-4EEB-B703-79C90AD24815}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7200C42A-214F-4EEB-B703-79C90AD24815}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7200C42A-214F-4EEB-B703-79C90AD24815}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7200C42A-214F-4EEB-B703-79C90AD24815}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7200C42A-214F-4EEB-B703-79C90AD24815}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {1868CC6D-99CC-4682-B36A-3B28E5F09813} + EndGlobalSection +EndGlobal diff --git a/Context/DapperContext.cs b/Context/DapperContext.cs new file mode 100644 index 0000000..d78f6c3 --- /dev/null +++ b/Context/DapperContext.cs @@ -0,0 +1,22 @@ +//using Microsoft.Data.SqlClient; +using System.Data; +using System.Data.SqlClient; +/*using MySqlConnector;*/ + +using MySql.Data.MySqlClient; +namespace AOLBackend.Context +{ + public class DapperContext + { + private readonly IConfiguration _configuration; + private readonly string _connectionString; + public DapperContext(IConfiguration configuration) + { + _configuration = configuration; + _connectionString = _configuration.GetConnectionString("Mysql"); + } + /* public IDbConnection CreateConnection() + => new SqlConnection(_connectionString); */ + public IDbConnection CreateConnection() => new MySqlConnection(_connectionString); + } +} diff --git a/Contracts/Catalogos/ICatClientesRepository.cs b/Contracts/Catalogos/ICatClientesRepository.cs new file mode 100644 index 0000000..d009c7c --- /dev/null +++ b/Contracts/Catalogos/ICatClientesRepository.cs @@ -0,0 +1,11 @@ +using AOLBackend.Models.Catalogos; + +namespace AOLBackend.Contracts.Catalogos +{ + public interface ICatClientesRepository + { + public Task Append(ICatClientes data); + public Task> GetAll(); + public Task Delete(int id); + } +} \ No newline at end of file diff --git a/Contracts/Catalogos/ICatProveedoresRepository.cs b/Contracts/Catalogos/ICatProveedoresRepository.cs new file mode 100644 index 0000000..d8ab53d --- /dev/null +++ b/Contracts/Catalogos/ICatProveedoresRepository.cs @@ -0,0 +1,12 @@ +using AOLBackend.Models.Catalogos; + +namespace AOLBackend.Contracts.Catalogos +{ + public interface ICatProveedoresRepository + { + public Task Append(ICatProveedores data); + public Task> GetAll(); + public Task Delete(int id); + + } +} \ No newline at end of file diff --git a/Contracts/Catalogos/ICatRutasRepository.cs b/Contracts/Catalogos/ICatRutasRepository.cs new file mode 100644 index 0000000..31ac76c --- /dev/null +++ b/Contracts/Catalogos/ICatRutasRepository.cs @@ -0,0 +1,12 @@ +using AOLBackend.Models.Catalogos; +using AOLBackend.DTO.Catalogos; + +namespace AOLBackend.Contracts.Catalogos +{ + public interface ICatRutasRepository + { + public Task Append(ICatRutas data); + public Task> GetAll(); + public Task Delete(int id); + } +} \ No newline at end of file diff --git a/Contracts/Catalogos/ICatServiciosRepository.cs b/Contracts/Catalogos/ICatServiciosRepository.cs new file mode 100644 index 0000000..78f7805 --- /dev/null +++ b/Contracts/Catalogos/ICatServiciosRepository.cs @@ -0,0 +1,11 @@ +using AOLBackend.Models.Catalogos; + +namespace AOLBackend.Contracts.Catalogos +{ + public interface ICatServiciosRepository + { + public Task Append(ICatServicios data); + public Task> GetAll(); + public Task Delete(int id); + } +} \ No newline at end of file diff --git a/Contracts/Catalogos/ICatTipoUnidadRepository.cs b/Contracts/Catalogos/ICatTipoUnidadRepository.cs new file mode 100644 index 0000000..b012a2c --- /dev/null +++ b/Contracts/Catalogos/ICatTipoUnidadRepository.cs @@ -0,0 +1,11 @@ +using AOLBackend.Models.Catalogos; + +namespace AOLBackend.Contracts.Catalogos +{ + public interface ICatTipoUnidadRepository + { + public Task Append(ICatTipoUnidad data); + public Task> GetAll(); + public Task Delete(int id); + } +} \ No newline at end of file diff --git a/Contracts/Catalogos/ICatUbicacionesRepository.cs b/Contracts/Catalogos/ICatUbicacionesRepository.cs new file mode 100644 index 0000000..6749bec --- /dev/null +++ b/Contracts/Catalogos/ICatUbicacionesRepository.cs @@ -0,0 +1,11 @@ +using AOLBackend.Models.Catalogos; + +namespace AOLBackend.Contracts.Catalogos +{ + public interface ICatUbicacionesRepository + { + public Task Append(ICatUbicaciones data); + public Task> GetAll(); + public Task Delete(int id); + } +} \ No newline at end of file diff --git a/Contracts/IMenuRepository.cs b/Contracts/IMenuRepository.cs new file mode 100644 index 0000000..f8765bf --- /dev/null +++ b/Contracts/IMenuRepository.cs @@ -0,0 +1,9 @@ +using AOLBackend.Models; + +namespace AOLBackend.Contracts +{ + public interface IMenuRepository + { + public Task> GetItemsMenu(IUsuarios user); + } +} diff --git a/Contracts/IUsuarioRepository.cs b/Contracts/IUsuarioRepository.cs new file mode 100644 index 0000000..d12a84b --- /dev/null +++ b/Contracts/IUsuarioRepository.cs @@ -0,0 +1,28 @@ +using AOLBackend.DTO; +using AOLBackend.DTO.Usuario; +using AOLBackend.Models; + +namespace AOLBackend.Contracts +{ + public interface IUsuarioRepository + { + public Task> GetAllUsuariosShort(); + + public Task> GetAllUsuarios(); + + public Task GetUsuarioById(int id); + + public Task GetUsuario(DTOLogin user); + + public Task SearchUsuario(DTOLogin user); + + public Task ResetPassword(DTOLogin user); + + public Task CreateUsuario(IUsuarios user); + + public Task> ClonarUsuario(DTOClonarUsuario user); + + public Task Activate(int id, int Activo); + + } +} diff --git a/Contracts/Operaciones/IOpViajesRepository.cs b/Contracts/Operaciones/IOpViajesRepository.cs new file mode 100644 index 0000000..d0878ad --- /dev/null +++ b/Contracts/Operaciones/IOpViajesRepository.cs @@ -0,0 +1,17 @@ +using AOLBackend.DTO.Operaciones; + +namespace AOLBackend.Contracts.Operaciones +{ + public interface IOpViajesRepository + { + public Task Append(DTOOpViajes data); + public Task> AppendServicio(DTOOpViajesServicios data); + public Task> GetAll(); + public Task> GetAllServices(int Status); + public Task GetLastTrailerBox(int idViaje); + public Task> GetStatusSecuence(); + public Task ChangeTripStatus(DTOChangeTripStatus data); + public Task Delete(int id); + public Task DeleteService(int id); + } +} \ No newline at end of file diff --git a/Contracts/Utils/IFileManagerRepository.cs b/Contracts/Utils/IFileManagerRepository.cs new file mode 100644 index 0000000..191ea6c --- /dev/null +++ b/Contracts/Utils/IFileManagerRepository.cs @@ -0,0 +1,12 @@ +using AOLBackend.Models.Utils; +namespace AOLBackend.Contracts.Utils +{ + public interface IFileManagerRepository + { + public Task FileManager(FileManager data); + public Task getFileByProcess(long id, int Proceso); + public Task> getAllFilesByProcess(long Tags, int Proceso); + public Task getFileById(long id); + public Task deleteFileByProcess(long id, int Proceso); + } +} \ No newline at end of file diff --git a/Contracts/Utils/IFilePaths4ProcessRepository.cs b/Contracts/Utils/IFilePaths4ProcessRepository.cs new file mode 100644 index 0000000..eec9bc7 --- /dev/null +++ b/Contracts/Utils/IFilePaths4ProcessRepository.cs @@ -0,0 +1,9 @@ +using AOLBackend.Models.Utils; + +namespace AOLBackend.Contracts.Utils +{ + public interface IFilePaths4ProcessRepository + { + public Task getPaths4ProcessById(long id); + } +} \ No newline at end of file diff --git a/Controllers/Catalogos/CatClientesController.cs b/Controllers/Catalogos/CatClientesController.cs new file mode 100644 index 0000000..a40ddfc --- /dev/null +++ b/Controllers/Catalogos/CatClientesController.cs @@ -0,0 +1,44 @@ +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +namespace AOLBackend.Controllers.Catalogos +{ + [Authorize] + [ApiController] + [Route("api/Catalogos/[controller]")] + public class CatClientesController : ControllerBase + { + private readonly ICatClientesRepository _Repo; + + public CatClientesController(ICatClientesRepository Repo) + { + _Repo = Repo; + } + + [HttpPost] + [Route("Append")] + public async Task Append([FromBody] ICatClientes data) + { + var entrada = await _Repo.Append(data); + return entrada; + } + + [HttpGet] + [Route("Get")] + public async Task> GetAll() + { + var entrada = await _Repo.GetAll(); + return entrada; + } + + [HttpDelete("Delete/{id}")] + public async Task Delete(int id) + { + await _Repo.Delete(id); + return new OkObjectResult(new { respuesta = "Se elimino el registro" }); + } + + } +} \ No newline at end of file diff --git a/Controllers/Catalogos/CatProveedoresController.cs b/Controllers/Catalogos/CatProveedoresController.cs new file mode 100644 index 0000000..9431092 --- /dev/null +++ b/Controllers/Catalogos/CatProveedoresController.cs @@ -0,0 +1,43 @@ +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +namespace AOLBackend.Controllers.Catalogos +{ + /*[Authorize]*/ + [ApiController] + [Route("api/Catalogos/[controller]")] + public class CatProveedoresController : ControllerBase + { + private readonly ICatProveedoresRepository _Repo; + + public CatProveedoresController(ICatProveedoresRepository Repo) + { + _Repo = Repo; + } + + [HttpPost] + [Route("Append")] + public async Task Append([FromBody] ICatProveedores data) + { + var entrada = await _Repo.Append(data); + return entrada; + } + + [HttpGet] + [Route("Get")] + public async Task> GetAll() + { + var entrada = await _Repo.GetAll(); + return entrada; + } + + [HttpDelete("Delete/{id}")] + public async Task Delete(int id) + { + await _Repo.Delete(id); + return new OkObjectResult(new { respuesta = "Se elimino el registro" }); + } + } +} \ No newline at end of file diff --git a/Controllers/Catalogos/CatRutasController.cs b/Controllers/Catalogos/CatRutasController.cs new file mode 100644 index 0000000..9cf4ecb --- /dev/null +++ b/Controllers/Catalogos/CatRutasController.cs @@ -0,0 +1,44 @@ +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using AOLBackend.DTO.Catalogos; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +namespace AOLBackend.Controllers.Catalogos +{ + [Authorize] + [ApiController] + [Route("api/Catalogos/[controller]")] + public class CatRutasController : ControllerBase + { + private readonly ICatRutasRepository _Repo; + + public CatRutasController(ICatRutasRepository Repo) + { + _Repo = Repo; + } + + [HttpPost] + [Route("Append")] + public async Task Append([FromBody] ICatRutas data) + { + var entrada = await _Repo.Append(data); + return entrada; + } + + [HttpGet] + [Route("Get")] + public async Task> GetAll() + { + var entrada = await _Repo.GetAll(); + return entrada; + } + + [HttpDelete("Delete/{id}")] + public async Task Delete(int id) + { + await _Repo.Delete(id); + return new OkObjectResult(new { respuesta = "Se elimino el registro" }); + } + } +} \ No newline at end of file diff --git a/Controllers/Catalogos/CatServiciosController.cs b/Controllers/Catalogos/CatServiciosController.cs new file mode 100644 index 0000000..8d29a62 --- /dev/null +++ b/Controllers/Catalogos/CatServiciosController.cs @@ -0,0 +1,43 @@ +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +namespace AOLBackend.Controllers.Catalogos +{ + [Authorize] + [ApiController] + [Route("api/Catalogos/[controller]")] + public class CatServiciosController : ControllerBase + { + private readonly ICatServiciosRepository _Repo; + + public CatServiciosController(ICatServiciosRepository Repo) + { + _Repo = Repo; + } + + [HttpPost] + [Route("Append")] + public async Task Append([FromBody] ICatServicios data) + { + var entrada = await _Repo.Append(data); + return entrada; + } + + [HttpGet] + [Route("Get")] + public async Task> GetAll() + { + var entrada = await _Repo.GetAll(); + return entrada; + } + + [HttpDelete("Delete/{id}")] + public async Task Delete(int id) + { + await _Repo.Delete(id); + return new OkObjectResult(new { respuesta = "Se elimino el registro" }); + } + } +} \ No newline at end of file diff --git a/Controllers/Catalogos/CatTipoUnidadController.cs b/Controllers/Catalogos/CatTipoUnidadController.cs new file mode 100644 index 0000000..a6ea117 --- /dev/null +++ b/Controllers/Catalogos/CatTipoUnidadController.cs @@ -0,0 +1,42 @@ +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +namespace AOLBackend.Controllers.Catalogos +{ + [Authorize] + [ApiController] + [Route("api/Catalogos/[controller]")] + public class CatTipoUnidadController : ControllerBase + { + private readonly ICatTipoUnidadRepository _Repo; + public CatTipoUnidadController(ICatTipoUnidadRepository Repo) + { + _Repo = Repo; + } + + [HttpPost] + [Route("Append")] + public async Task Append([FromBody] ICatTipoUnidad data) + { + var entrada = await _Repo.Append(data); + return entrada; + } + + [HttpGet] + [Route("Get")] + public async Task> GetAll() + { + var entrada = await _Repo.GetAll(); + return entrada; + } + + [HttpDelete("Delete/{id}")] + public async Task Delete(int id) + { + await _Repo.Delete(id); + return new OkObjectResult(new { respuesta = "Se elimino el registro" }); + } + } +} \ No newline at end of file diff --git a/Controllers/Catalogos/CatUbicacionesController.cs b/Controllers/Catalogos/CatUbicacionesController.cs new file mode 100644 index 0000000..d3111db --- /dev/null +++ b/Controllers/Catalogos/CatUbicacionesController.cs @@ -0,0 +1,42 @@ +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +namespace AOLBackend.Controllers.Catalogos +{ + [Authorize] + [ApiController] + [Route("api/Catalogos/[controller]")] + public class CatUbicacionesController : ControllerBase + { + private readonly ICatUbicacionesRepository _Repo; + public CatUbicacionesController(ICatUbicacionesRepository Repo) + { + _Repo = Repo; + } + + [HttpPost] + [Route("Append")] + public async Task Append([FromBody] ICatUbicaciones data) + { + var entrada = await _Repo.Append(data); + return entrada; + } + + [HttpGet] + [Route("Get")] + public async Task> GetAll() + { + var entrada = await _Repo.GetAll(); + return entrada; + } + + [HttpDelete("Delete/{id}")] + public async Task Delete(int id) + { + await _Repo.Delete(id); + return new OkObjectResult(new { respuesta = "Se elimino el registro" }); + } + } +} \ No newline at end of file diff --git a/Controllers/Operaciones/OpViajesController.cs b/Controllers/Operaciones/OpViajesController.cs new file mode 100644 index 0000000..8da6f2e --- /dev/null +++ b/Controllers/Operaciones/OpViajesController.cs @@ -0,0 +1,90 @@ +using AOLBackend.Contracts.Operaciones; +using AOLBackend.DTO.Operaciones; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +namespace AOLBackend.Controllers.Operaciones +{ + [Authorize] + [ApiController] + [Route("api/Operaciones/[controller]")] + public class OpViajesController : ControllerBase + { + private readonly IOpViajesRepository _Repo; + + public OpViajesController(IOpViajesRepository Repo) + { + _Repo = Repo; + } + + [HttpPost] + [Route("Append")] + public async Task Append([FromBody] DTOOpViajes data) + { + var entrada = await _Repo.Append(data); + return entrada; + } + + [HttpPost] + [Route("AppendService")] + public async Task> Append([FromBody] DTOOpViajesServicios data) + { + var entrada = await _Repo.AppendServicio(data); + return entrada; + } + + [HttpGet] + [Route("Get")] + public async Task> GetAll() + { + var entrada = await _Repo.GetAll(); + return entrada; + } + + [HttpGet] + [Route("GetAllServices")] + public async Task> GetAllServices(int Status) + { + var entrada = await _Repo.GetAllServices(Status); + return entrada; + } + + [HttpGet] + [Route("GetLastTrailerBox")] + public async Task GetLastTrailerBox(int idViaje) + { + var entrada = await _Repo.GetLastTrailerBox(idViaje); + return entrada; + } + + [HttpGet] + [Route("GetStatusSecuence")] + public async Task> GetStatusSecuence() + { + var entrada = await _Repo.GetStatusSecuence(); + return entrada; + } + + [HttpPut("ChangeTripStatus/{id}")] + public async Task Update2(int id, [FromBody] DTOChangeTripStatus data) + { + var entrada = await _Repo.ChangeTripStatus(data); + return entrada; + } + + [HttpDelete("Delete/{id}")] + public async Task Delete(int id) + { + await _Repo.Delete(id); + return new OkObjectResult(new { respuesta = "Se elimino el registro" }); + } + + [HttpDelete("DeleteService/{id}")] + public async Task DeleteService(int id) + { + await _Repo.DeleteService(id); + return new OkObjectResult(new { respuesta = "Se elimino el registro" }); + } + + } +} \ No newline at end of file diff --git a/Controllers/Usuarios/AuthController.cs b/Controllers/Usuarios/AuthController.cs new file mode 100644 index 0000000..1bb6214 --- /dev/null +++ b/Controllers/Usuarios/AuthController.cs @@ -0,0 +1,143 @@ +using AOLBackend.Contracts; +using AOLBackend.DTO; +using AOLBackend.DTO.Usuario; +using AOLBackend.Models; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using AOLBackend.Services.EmailSender; +using System.Text; + +namespace AOLBackend.Controllers.Usuarios +{ + [Route("api/[controller]")] + [ApiController] + public class AuthController : ControllerBase + { + public IConfiguration _config; + private readonly IUsuarioRepository _usuariosRepo; + private readonly IMenuRepository _menuRepo; + + public AuthController(IConfiguration config, IUsuarioRepository usuariosRepo, IMenuRepository menuRepo) + { + _config = config; + _usuariosRepo = usuariosRepo; + _menuRepo = menuRepo; + } + + [Route("Login")] + [HttpPost] + public async Task Post(DTOLogin _userData) + { + if (_userData.Contrasena == _config.GetValue("DefaultUser:Password")) + { + return StatusCode(401, "La primera vez que accese debera cambiar su contraseña!"); + } + if (_userData != null && _userData.Usuario != null && _userData.Contrasena != null) + { + var user = await _usuariosRepo.GetUsuario(_userData); + if (user == null) return BadRequest("Invalid credentials"); + if (user != null) + { + var menu = await _menuRepo.GetItemsMenu(user); + var claims = new List(); + claims.Add(new Claim(JwtRegisteredClaimNames.Sub, _config["Jwt:Subject"])); + claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); + claims.Add(new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString())); + claims.Add(new Claim("UserId", user.Id.ToString())); + claims.Add(new Claim("Usuario", user.Usuario)); + claims.Add(new Claim("UserType", (user != null) ? user.TipoUsuario.ToString() : "0")); + if (menu != null) + { + foreach (IMenu item in menu) { claims.Add(new Claim(ClaimTypes.Role, item.Url)); } + } + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); + var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + var token = new JwtSecurityToken( + _config["Jwt:Issuer"], + _config["Jwt:Audience"], + claims, + expires: DateTime.UtcNow.AddHours(Int32.Parse(_config["Jwt:ExpirationHours"])), + //expires: DateTime.UtcNow.AddMinutes(2), + signingCredentials: signIn); + + var _token = new JwtSecurityTokenHandler().WriteToken(token); + return new OkObjectResult(new { menu = menu, token = _token }); + } + else + { + return BadRequest("Invalid credentials"); + } + } + else + { + return BadRequest(); + } + } + + /*[Authorize]*/ + [Route("Validate")] + [HttpGet] + public IActionResult GetValidation() + { + return StatusCode(200, "Its Ok"); + } + + [Route("resetPassword")] + [HttpPost] + public async Task ResetPassword(DTOLogin user) + { + try + { + var result = await _usuariosRepo.ResetPassword(user); + if (result == null) + { + return StatusCode(400, "Cuenta de usuario no existe"); + } + var encrypted = AOLBackend.Services.Tools.CryptDecrypt.Encryption(user.Usuario); + EmailSender eSender = new EmailSender(_config); + string htmlContent = $@" + + + + + +
Hola: {user.Usuario}, mediante el siguiente correo electronico, se le notifica que se ha cambiado su contraseña
Para validar que usted cambio su contraseña, favor de dar click al siguiente link
Que tenga un excelente dia!
+ + "; + string resultSendEmail = eSender.SrvSendEmail(htmlContent, "Confirmacion de credenciales de alphaomega.com.mx", user.Usuario); + return Ok(resultSendEmail); + } + catch (Exception ex) + { + return StatusCode(500, ex); + } + } + + [Route("AcceptReset")] + [HttpGet] + public async Task AcceptReset(string key) + { + { + var decrypted = AOLBackend.Services.Tools.CryptDecrypt.Decryption(@key); + try + { + var usuarios = await _usuariosRepo.GetAllUsuariosShort(); + foreach (DTOUsuarioShort usr in usuarios) + { + if (usr.Usuario == decrypted) + { + Boolean result = await _usuariosRepo.Activate(usr.id, 1); + if (result) return Ok("Cuenta activada!"); + else return StatusCode(500, "Ocurrio un error!"); + } + } + } + catch (Exception ex) { return StatusCode(500, ex.Message); } + return StatusCode(200, "Cuenta activada!"); + } + } + } +} diff --git a/Controllers/Usuarios/UsuariosController.cs b/Controllers/Usuarios/UsuariosController.cs new file mode 100644 index 0000000..bb12c30 --- /dev/null +++ b/Controllers/Usuarios/UsuariosController.cs @@ -0,0 +1,181 @@ +using AOLBackend.Contracts; +using AOLBackend.DTO; +using AOLBackend.DTO.Usuario; +using AOLBackend.Models; +using AOLBackend.Services.EmailSender; +using Microsoft.AspNetCore.Mvc; + +namespace AOLBackend.Controllers.Usuarios +{ + [Route("api/Catalogos/[controller]")] + [ApiController] + public class UsuariosController : ControllerBase + { + private readonly IUsuarioRepository _usuariosRepo; + private readonly IConfiguration _config; + + public UsuariosController(IUsuarioRepository usuariosRepo, IConfiguration config) + { + _usuariosRepo = usuariosRepo; + _config = config; + } + + [Route("getUsuarioById")] + [HttpGet] + public async Task GetAllUsuarios(int id) + { + try + { + var usuario = await _usuariosRepo.GetUsuarioById(id); + if (usuario == null) return NotFound(); + return Ok(usuario); + } + catch (Exception ex) { return StatusCode(500, ex.Message); } + } + + [Route("GetAll")] + [HttpGet] + public async Task GetAll() + { + try + { + var usuarios = await _usuariosRepo.GetAllUsuarios(); + return Ok(usuarios); + } + catch (Exception ex) { return StatusCode(500, ex.Message); } + } + + [Route("getAllUsuariosShort")] + [HttpGet] + public async Task GetAllUsuariosShort() + { + try + { + var usuarios = await _usuariosRepo.GetAllUsuariosShort(); + return Ok(usuarios); + } + catch (Exception ex) { return StatusCode(500, ex.Message); } + } + + [Route("Auth")] + [HttpPost] + public async Task Auth(DTOLogin user) + { + try + { + var usuarios = await _usuariosRepo.GetUsuario(user); + return Ok(usuarios); + } + catch (Exception ex) { return StatusCode(500, ex.Message); } + } + + [Route("searchUsuario")] + [HttpPost] + public async Task SearchUsuario(DTOLogin user) + { + try + { + var result = await _usuariosRepo.SearchUsuario(user); + if (result != null) return StatusCode(409, new { message = "Usuario registrado previamente" }); + return Ok(new { message = "Usuario libre, no registrado previamente" }); + } + catch (Exception ex) + { + return StatusCode(500, ex); + } + } + + [Route("Append")] + [HttpPost] + public async Task Append(IUsuarios user) + { + try + { + var usuario = await _usuariosRepo.CreateUsuario(user); + if (user.Id == 0) + { + EmailSender eSender = new EmailSender(_config); + string htmlContent = $@" + + + + + + + + + + + +
Hola: {user.Nombre}, mediante el siguiente correo electronico, se le notifica que se le ha creado un nuevo acceso
Para acceder a su cuenta, favor de entrar a: https://www.alphaomega.com.mx/
Nombre de usuario: {user.Usuario}
Para poder entrar por primera vez, es necesario que establezca su contraseña
Para cambiar/establecer la contraseña, entre a link y de un click al link Olvido contraseña
Si por alguna razon, no recuerda su contrasena, repita este proceso de resetear su contraseña
No es necesario responder a este correo, ya que fue generado en automatico por el sistema.
Nota: Las credenciales de acceso son responsabilidad personal, nadie solo usted debe conocerlas
Que tenga un excelente dia!
+ + "; + string result = eSender.SrvSendEmail(htmlContent, "Confirmacion de credenciales de alphaomega.com.mx", user.Usuario); + return Ok(result); + } + return Ok(usuario); + } + catch (Exception ex) { return StatusCode(500, ex.Message); } + } + + [Route("clonarUsuario")] + [HttpPost] + public async Task clonarUsuario(DTOClonarUsuario user) + { + try + { + var usuarios = await _usuariosRepo.ClonarUsuario(user); + return Ok(usuarios); + } + catch (Exception ex) { return StatusCode(500, ex.Message); } + } + + [Route("SendEmail")] + [HttpGet] + public async Task SendEmail(string Usuario, string Nombre, string Correo) + { + var content = Usuario; + EmailSender eSender = new EmailSender(_config); + string htmlContent = $@" + + + + + + + + + + + +
Hola: {Nombre}, mediante el siguiente correo electronico, se le notifica que se le ha creado un nuevo acceso
Para acceder a su cuenta, favor de entrar a: https://www.alphaomega.com.mx/
Nombre de usuario: {Usuario}
Para poder entrar por primera vez, es necesario que establezca su contraseña
Para cambiar/establecer la contraseña, puede ir al menu Reset, proporcione su nombre de usuario y su nueva contraseña
Si por alguna razon, no recuerda su contrasena, repita este proceso de resetear su contraseña
No es necesario responder a este correo, ya que fue generado en automatico por el sistema.
Nota: Las credenciales de acceso son responsabilidad personal, nadie solo usted debe conocerlas
Que tenga un excelente dia!
+ + "; + string result = eSender.SrvSendEmail(htmlContent, "Confirmacion de credenciales de alphaomega.com.mx", Correo); + return Ok(result); + } + + /* [Route("AcceptReset")] + [HttpGet] + public async Task AcceptReset(string key) + { + var decrypted = AOLBackend.Services.Tools.CryptDecrypt.Decryption(@key); + try + { + // return Ok(decrypted); + var usuarios = await _usuariosRepo.GetAllUsuariosShort(); + foreach (DTOUsuarioShort usr in usuarios) + { + if (usr.Usuario == decrypted) + { + Boolean result = await _usuariosRepo.Activate(usr.id, 1); + if (result) return Ok("Cuenta activada!"); + else return StatusCode(500, "Ocurrio un error!"); + } + } + } + catch (Exception ex) { return StatusCode(500, ex.Message); } + return StatusCode(200, "Cuenta activada!"); + } */ + } +} diff --git a/Controllers/Utils/FileManagerController.cs b/Controllers/Utils/FileManagerController.cs new file mode 100644 index 0000000..e52fabe --- /dev/null +++ b/Controllers/Utils/FileManagerController.cs @@ -0,0 +1,148 @@ +using AOLBackend.Contracts.Utils; +using AOLBackend.Models.Utils; +using Microsoft.AspNetCore.Mvc; + +namespace AOLBackend.Controllers.Utils +{ + [ApiController] + [Route("api/[controller]")] + public class FileManagerController : ControllerBase + { + + private readonly IFileManagerRepository _Repo; + private readonly IFilePaths4ProcessRepository _RepoRelativePath; + private readonly IConfiguration _config; + private readonly string RootPathCorresponsales; + public FileManagerController(IFileManagerRepository Repo, + IFilePaths4ProcessRepository RepoRelativePath, + IConfiguration config) + { + _config = config; + _Repo = Repo; + _RepoRelativePath = RepoRelativePath; + RootPathCorresponsales = _config.GetValue("AllFiles"); + } + + [Route("GetFileInfoByProcess")] + [HttpGet] + public async Task GetFileInfoByProcess([FromQuery] int id, int Proceso) + { + FileManager data = new FileManager(); + data = await _Repo.getFileByProcess(id, Proceso); + return data; + } + + [Route("GetFileInfoById")] + [HttpGet] + public async Task GetFileInfoByProcess([FromQuery] int id) + { + FileManager data = new FileManager(); + data = await _Repo.getFileById(id); + return data; + } + + [Route("AppendFileByProcess")] + [HttpPost] + public async Task AppendFileByProcess(IFormFile file, int IdUsuario, int Proceso, string Tags, int crud) + { + DateTime time = DateTime.Now; + FilePaths4Process RelativePath = await _RepoRelativePath.getPaths4ProcessById(Proceso); + string fullPath = ""; + fullPath = RootPathCorresponsales + RelativePath.Path; + string fileMime = file.FileName.Substring(file.FileName.Length - 4); + string newFileName = file.FileName.Replace(fileMime, "") + "_" + time.ToString("yyyy_MM_dd_HH_mm_ss") + fileMime; + FileManager data = new FileManager(); + data.id = 0; + data.IdUsuario = IdUsuario; + data.NombreArchivo = newFileName; + data.Proceso = Proceso; + data.FechaRegistro = ""; + data.Tags = Tags; + data.Activo = 1; + long fileLength = 0; + if (@crud == 1) + { + if (file.Length > 0) + { + var filePath = fullPath + newFileName; + using (var stream = System.IO.File.Create(filePath)) + { + await file.CopyToAsync(stream); + } + fileLength = new System.IO.FileInfo(filePath).Length / 1024; + data.Size = fileLength; + if (fileLength > 0) + { + return await _Repo.FileManager(data); + } + } + } + return data; + } + + + [Route("getFile")] + [HttpGet, DisableRequestSizeLimit] + public async Task getFileFromFileManager([FromQuery] long id, int Proceso) + { + Boolean ExisteEnDisco = false; + FileManager recFound = await _Repo.getFileByProcess(id, Proceso); + FilePaths4Process RelativePath = await _RepoRelativePath.getPaths4ProcessById(Proceso); + string fullPath = ""; + fullPath = RootPathCorresponsales + RelativePath.Path; + if (!String.IsNullOrEmpty(recFound.NombreArchivo)) + { + try + { + if (System.IO.File.Exists(Path.Combine(fullPath, recFound.NombreArchivo))) + { + ExisteEnDisco = true; + } + else return BadRequest(new { respuesta = "Ese archivo no existe" }); + } + catch (IOException ex) + { + return BadRequest(new { respuesta = "Ese archivo no existe" + ex.ToString() }); + } + if (ExisteEnDisco) + { + string fileMime = recFound.NombreArchivo.Substring(recFound.NombreArchivo.Length - 3).ToLower(); + var mime = "application/" + fileMime.ToLower(); + string targetFile = fullPath + recFound.NombreArchivo; + if (System.IO.File.Exists(targetFile)) + { + byte[] pdfBytes = System.IO.File.ReadAllBytes(targetFile); + MemoryStream ms = new MemoryStream(pdfBytes); + return new FileStreamResult(ms, mime); + } + } + } + return BadRequest(new { respuesta = "Ese archivo no existe" }); + } + + [HttpDelete("DeleteById/{id}")] + public async Task DeleteByProcess(long id) + { + FileManager Found = await _Repo.getFileById(id); + FilePaths4Process RelativePath = await _RepoRelativePath.getPaths4ProcessById(Found.Proceso); + string fullPath = ""; + fullPath = RootPathCorresponsales + RelativePath.Path; + try + { + if (System.IO.File.Exists(Path.Combine(fullPath, Found.NombreArchivo))) + { + System.IO.File.Delete(Path.Combine(fullPath, Found.NombreArchivo)); + await _Repo.deleteFileByProcess(Found.id, Found.Proceso); + } + else return new OkObjectResult(new { respuesta = "Ese archivo no existe" }); + } + catch (IOException ex) + { + return new OkObjectResult(new { respuesta = "Ocurrio un error al intentar eliminar el registro: " + ex.ToString() }); + } + return new OkObjectResult(new { respuesta = "Se elimino el registro" }); + } + + + } +} \ No newline at end of file diff --git a/Controllers/Utils/MFileManagerController.cs b/Controllers/Utils/MFileManagerController.cs new file mode 100644 index 0000000..ac052f5 --- /dev/null +++ b/Controllers/Utils/MFileManagerController.cs @@ -0,0 +1,56 @@ +using Microsoft.AspNetCore.Mvc; +using AOLBackend.Services.MFileManager; +using AOLBackend.Contracts.Utils; +using AOLBackend.Models.Utils; + +namespace AOLBackend.Controllers.Utils +{ + [Route("api/Utils/[controller]")] + public class MFileManagerController : Controller + { + private readonly IFileManagerRepository _Repo; + private readonly IConfiguration _config; + private readonly IFilePaths4ProcessRepository _RepoRelativePath; + private readonly string RootPath; + + public MFileManagerController(IConfiguration config, IFilePaths4ProcessRepository RepoRelativePath, IFileManagerRepository Repo) + { + _config = config; + _RepoRelativePath = RepoRelativePath; + _Repo = Repo; + RootPath = _config.GetValue("AllFiles"); + } + + [HttpGet] + [Route("GetFilesFromLog")] + public async Task> GetFilesFromLog(int Tags, int Proceso) + { + FilePaths4Process RelativePath = await _RepoRelativePath.getPaths4ProcessById(Proceso); + SvcMFileManager FM = new SvcMFileManager(_config, _Repo, RootPath + RelativePath.Path + "\\"); + return await FM.GetFilesFromLog(Tags, Proceso); + } + + + [HttpGet] + [Route("GetFileContentById")] + public async Task GetFileContentById(long id, int Proceso) + { + FilePaths4Process RelativePath = await _RepoRelativePath.getPaths4ProcessById(Proceso); + SvcMFileManager FM = new SvcMFileManager(_config, _Repo, RootPath + RelativePath.Path); + return await FM.getFileContentById(id); + } + + + [HttpPost] + [Route("Append")] + public async Task> Append(List FileList, int Tags, int Proceso, int Usuario) + { + List data = new List(); + FilePaths4Process RelativePath = await _RepoRelativePath.getPaths4ProcessById(Proceso); + SvcMFileManager FM = new SvcMFileManager(_config, _Repo, RootPath + RelativePath.Path + "\\"); + List filePaths = await FM.SaveFile2DiskList(FileList); + var fileData = await FM.SaveFileLog(filePaths, Tags, Proceso, Usuario); + return fileData; + } + } +} \ No newline at end of file diff --git a/Controllers/WeatherForecastController.cs b/Controllers/WeatherForecastController.cs new file mode 100644 index 0000000..3efa190 --- /dev/null +++ b/Controllers/WeatherForecastController.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Mvc; + +namespace AOLBackend.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet(Name = "GetWeatherForecast")] + public IEnumerable Get() + { + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} \ No newline at end of file diff --git a/DTO/Catalogos/DTOCatRutas.cs b/DTO/Catalogos/DTOCatRutas.cs new file mode 100644 index 0000000..8533953 --- /dev/null +++ b/DTO/Catalogos/DTOCatRutas.cs @@ -0,0 +1,24 @@ +namespace AOLBackend.DTO.Catalogos +{ + public class DTOCatRutas + { + public int id { get; set; } + public int Cliente { get; set; } = 0; + public string sCliente { get; set; } = null!; + public int Servicio { get; set; } = 0; + public string sServicio { get; set; } = null!; + public double Precio { get; set; } = 0; + public int Proveedor { get; set; } = 0; + public string sProveedor { get; set; } = null!; + public double Costo { get; set; } = 0; + public int Origen { get; set; } = 0; + public string sOrigen { get; set; } = null!; + public int Destino { get; set; } = 0; + public string sDestino { get; set; } = null!; + public int TipoUnidad { get; set; } = 0; + public string sTipoUnidad { get; set; } = null!; + public string FCreacion { get; set; } = null!; + public string FActualizacion { get; set; } = null!; + public Byte Activo { get; set; } = 0!; + } +} \ No newline at end of file diff --git a/DTO/DTOLogin.cs b/DTO/DTOLogin.cs new file mode 100644 index 0000000..f1541fa --- /dev/null +++ b/DTO/DTOLogin.cs @@ -0,0 +1,8 @@ +namespace AOLBackend.DTO +{ + public class DTOLogin + { + public string Usuario { get; set; } = null!; + public string Contrasena { get; set; } = null!; + } +} diff --git a/DTO/Operaciones/DTOChangeTripStatus.cs b/DTO/Operaciones/DTOChangeTripStatus.cs new file mode 100644 index 0000000..c422c58 --- /dev/null +++ b/DTO/Operaciones/DTOChangeTripStatus.cs @@ -0,0 +1,8 @@ +namespace AOLBackend.DTO.Operaciones +{ + public class DTOChangeTripStatus + { + public int IdViaje { get; set; } = 0; + public int IdEstatus { get; set; } = 0; + } +} \ No newline at end of file diff --git a/DTO/Operaciones/DTOOpViajes.cs b/DTO/Operaciones/DTOOpViajes.cs new file mode 100644 index 0000000..1258566 --- /dev/null +++ b/DTO/Operaciones/DTOOpViajes.cs @@ -0,0 +1,26 @@ +namespace AOLBackend.DTO.Operaciones +{ + public class DTOOpViajes + { + public int id { get; set; } = 0; + public string FAlta { get; set; } = null!; + public int Usuario { get; set; } = 0; + public string RefAgenciaAduanal { get; set; } = null!; + public int Cliente { get; set; } = 0; + public string? sCliente { get; set; } = null!; + public byte TipoUnidad { get; set; } = 0; + public string? sTipoUnidad { get; set; } = null!; + public string NoCaja { get; set; } = null!; + public string PickUpNumber { get; set; } = null!; + public int Origen { get; set; } = 0; + public string? sOrigen { get; set; } = null!; + public int Destino { get; set; } = 0; + public string? sDestino { get; set; } = null!; + public byte Hazmat { get; set; } = 0; + public byte TipoOperacion { get; set; } = 1; + public string sTipoOperacion { get; set; } = null!; + public string Pedimento { get; set; } = null!; + public int Status { get; set; } = 0; + public int Activo { get; set; } = 0; + } +} \ No newline at end of file diff --git a/DTO/Operaciones/DTOOpViajesEstatusSecuencia.cs b/DTO/Operaciones/DTOOpViajesEstatusSecuencia.cs new file mode 100644 index 0000000..6e636fd --- /dev/null +++ b/DTO/Operaciones/DTOOpViajesEstatusSecuencia.cs @@ -0,0 +1,14 @@ +namespace AOLBackend.DTO.Operaciones +{ + public class DTOOpViajesEstatusSecuencia + { + public int id { get; set; } = 0; + public byte TipoOperacion { get; set; } = 0; + public string sTipoOperacion { get; set; } = null!; + public byte Estatus { get; set; } = 0; + public string sEstatus { get; set; } = null!; + public byte Secuencia { get; set; } = 0; + public byte Activo { get; set; } = 0; + + } +} \ No newline at end of file diff --git a/DTO/Operaciones/DTOOpViajesServicios.cs b/DTO/Operaciones/DTOOpViajesServicios.cs new file mode 100644 index 0000000..3c8fb4c --- /dev/null +++ b/DTO/Operaciones/DTOOpViajesServicios.cs @@ -0,0 +1,17 @@ +namespace AOLBackend.DTO.Operaciones +{ + public class DTOOpViajesServicios + { + public int id { get; set; } = 0; + public int IdViaje { get; set; } = 0; + public int IdServicio { get; set; } = 0; + public string? sServicio { get; set; } = null!; + public int Aduana { get; set; } = 0; + public string Comentarios { get; set; } = null!; + public int IdProveedor { get; set; } = 0; + public string sProveedor { get; set; } = null!; + public string NoCaja { get; set; } = null!; + public byte Activo { get; set; } = 1; + public string Cita { get; set; } = null!; + } +} \ No newline at end of file diff --git a/DTO/Operaciones/DTOResultTripStatus.cs b/DTO/Operaciones/DTOResultTripStatus.cs new file mode 100644 index 0000000..877ec50 --- /dev/null +++ b/DTO/Operaciones/DTOResultTripStatus.cs @@ -0,0 +1,8 @@ +namespace AOLBackend.DTO.Operaciones +{ + public class DTOResultTripStatus + { + public int IdViaje { get; set; } = 0; + public int Secuencia { get; set; } = 0; + } +} \ No newline at end of file diff --git a/DTO/Operaciones/DTOUltimaCaja.cs b/DTO/Operaciones/DTOUltimaCaja.cs new file mode 100644 index 0000000..9834a88 --- /dev/null +++ b/DTO/Operaciones/DTOUltimaCaja.cs @@ -0,0 +1,7 @@ +namespace AOLBackend.DTO.Operaciones +{ + public class DTOUltimaCaja + { + public string UltimaCaja { get; set; } = null!; + } +} \ No newline at end of file diff --git a/DTO/Usuario/DTOClonarUsuario.cs b/DTO/Usuario/DTOClonarUsuario.cs new file mode 100644 index 0000000..e1727eb --- /dev/null +++ b/DTO/Usuario/DTOClonarUsuario.cs @@ -0,0 +1,8 @@ +namespace AOLBackend.DTO.Usuario +{ + public class DTOClonarUsuario + { + public int IDUsuarioOrigen { get; set; } = 0!; + public int IdUsuarioDestino { get; set; } = 0!; + } +} diff --git a/DTO/Usuario/DTOUsuarioSendEmail.cs b/DTO/Usuario/DTOUsuarioSendEmail.cs new file mode 100644 index 0000000..a245811 --- /dev/null +++ b/DTO/Usuario/DTOUsuarioSendEmail.cs @@ -0,0 +1,10 @@ +namespace AOLBackend.DTO.Usuario +{ + public class DTOUsuarioSendEmail + { + public string Usuario { get; set; } = null!; + public string Nombre { get; set; } = null!; + public string Correo { get; set; } = null!; + + } +} \ No newline at end of file diff --git a/DTO/Usuario/DTOUsuarioShort.cs b/DTO/Usuario/DTOUsuarioShort.cs new file mode 100644 index 0000000..0e7336b --- /dev/null +++ b/DTO/Usuario/DTOUsuarioShort.cs @@ -0,0 +1,8 @@ +namespace AOLBackend.DTO.Usuario +{ + public class DTOUsuarioShort + { + public int id { get; set; } = 0!; + public string Usuario { get; set; } = null!; + } +} diff --git a/Models/Catalogos/ICatClientes.cs b/Models/Catalogos/ICatClientes.cs new file mode 100644 index 0000000..3c1c70a --- /dev/null +++ b/Models/Catalogos/ICatClientes.cs @@ -0,0 +1,9 @@ +namespace AOLBackend.Models.Catalogos +{ + public class ICatClientes + { + public int id { get; set; } = 0; + public string Cliente { get; set; } = null!; + public Byte Activo { get; set; } = 0!; + } +} \ No newline at end of file diff --git a/Models/Catalogos/ICatProveedores.cs b/Models/Catalogos/ICatProveedores.cs new file mode 100644 index 0000000..e3fbff0 --- /dev/null +++ b/Models/Catalogos/ICatProveedores.cs @@ -0,0 +1,9 @@ +namespace AOLBackend.Models.Catalogos +{ + public class ICatProveedores + { + public int id { get; set; } + public string Proveedor { get; set; } = null!; + public Byte Activo { get; set; } = 0!; + } +} \ No newline at end of file diff --git a/Models/Catalogos/ICatRutas.cs b/Models/Catalogos/ICatRutas.cs new file mode 100644 index 0000000..182b430 --- /dev/null +++ b/Models/Catalogos/ICatRutas.cs @@ -0,0 +1,18 @@ +namespace AOLBackend.Models.Catalogos +{ + public class ICatRutas + { + public int id { get; set; } + public int Cliente { get; set; } = 0; + public int Servicio { get; set; } = 0; + public double Precio { get; set; } = 0; + public int Proveedor { get; set; } = 0; + public double Costo { get; set; } = 0; + public int Origen { get; set; } = 0; + public int Destino { get; set; } = 0; + public int TipoUnidad { get; set; } = 0; + public string? FCreacion { get; set; } = null!; + public string? FActualizacion { get; set; } = null!; + public Byte Activo { get; set; } = 0!; + } +} \ No newline at end of file diff --git a/Models/Catalogos/ICatServicios.cs b/Models/Catalogos/ICatServicios.cs new file mode 100644 index 0000000..7c3adf1 --- /dev/null +++ b/Models/Catalogos/ICatServicios.cs @@ -0,0 +1,10 @@ + +namespace AOLBackend.Models.Catalogos +{ + public class ICatServicios + { + public int id { get; set; } + public string Servicio { get; set; } = null!; + public Byte Activo { get; set; } = 0!; + } +} \ No newline at end of file diff --git a/Models/Catalogos/ICatTipoUnidad.cs b/Models/Catalogos/ICatTipoUnidad.cs new file mode 100644 index 0000000..63ade35 --- /dev/null +++ b/Models/Catalogos/ICatTipoUnidad.cs @@ -0,0 +1,9 @@ +namespace AOLBackend.Models.Catalogos +{ + public class ICatTipoUnidad + { + public int id { get; set; } = 0!; + public string TipoUnidad { get; set; } = null!; + public Byte Activo { get; set; } = 0!; + } +} \ No newline at end of file diff --git a/Models/Catalogos/ICatUbicaciones.cs b/Models/Catalogos/ICatUbicaciones.cs new file mode 100644 index 0000000..87afc19 --- /dev/null +++ b/Models/Catalogos/ICatUbicaciones.cs @@ -0,0 +1,10 @@ +namespace AOLBackend.Models.Catalogos +{ + public class ICatUbicaciones + { + public int id { get; set; } + public string Ubicacion { get; set; } = null!; + public Byte Clasificacion { get; set; } = 0!; + public Byte Activo { get; set; } = 0!; + } +} \ No newline at end of file diff --git a/Models/IMenu.cs b/Models/IMenu.cs new file mode 100644 index 0000000..b17e6ec --- /dev/null +++ b/Models/IMenu.cs @@ -0,0 +1,11 @@ +namespace AOLBackend.Models +{ + public class IMenu + { + public int Id { get; set; } + public string Descripcion { get; set; } = null!; + public int PadreId { get; set; } + public int Posicion { get; set; } + public string Url { get; set; } = null!; + } +} diff --git a/Models/IUsuarios.cs b/Models/IUsuarios.cs new file mode 100644 index 0000000..c5eb4ab --- /dev/null +++ b/Models/IUsuarios.cs @@ -0,0 +1,13 @@ +namespace AOLBackend.Models +{ + public class IUsuarios + { + public int Id { get; set; } = 0!; + public string Usuario { get; set; } = null!; + public string Nombre { get; set; } = null!; + public string Contrasena { get; set; } = null!; + public byte TipoUsuario { get; set; } = 2; + public byte Activo { get; set; } = 1; + public int IdPerfil { get; set; } = 0!; + } +} diff --git a/Models/Operaciones/IOpViajes.cs b/Models/Operaciones/IOpViajes.cs new file mode 100644 index 0000000..4fbfab5 --- /dev/null +++ b/Models/Operaciones/IOpViajes.cs @@ -0,0 +1,29 @@ +namespace AOLBackend.Models.Operaciones +{ + public class IOpViajes + { + public int id { get; set; } = 0; + public string FAlta { get; set; } = null!; + public int Usuario { get; set; } = 0; + public string FCruce { get; set; } = null!; + public string RefAgenciaAduanal { get; set; } = null!; + public int Cliente { get; set; } = 0; + public int Proveedor { get; set; } = 0; + public byte Hazmat { get; set; } = 0; + public byte TipoUnidad { get; set; } = 0; + public string NoCaja { get; set; } = null!; + public string PickUpNumber { get; set; } = null!; + public int Origen { get; set; } = 0; + public int Destino { get; set; } = 0; + public string FacturaProveedor { get; set; } = null!; + public string FacturaAlphaOmega { get; set; } = null!; + public string FPagoFactura { get; set; } = null!; + public byte MetodoPago { get; set; } = 0; + public string FPagoProveedor { get; set; } = null!; + public int NoChequeAOL { get; set; } = 0; + public int FacturarA { get; set; } = 0; + public string FEntrega { get; set; } = null!; + public int Status { get; set; } = 0; + public int Activo { get; set; } = 0; + } +} \ No newline at end of file diff --git a/Models/Operaciones/IOpViajesServicios.cs b/Models/Operaciones/IOpViajesServicios.cs new file mode 100644 index 0000000..aec13d9 --- /dev/null +++ b/Models/Operaciones/IOpViajesServicios.cs @@ -0,0 +1,10 @@ +namespace AOLBackend.Models.Operaciones +{ + public class IOpViajesServicios + { + public int id { get; set; } = 0; + public int IdViaje { get; set; } = 0; + public int IdServicio { get; set; } = 0; + public byte Activo { get; set; } = 1; + } +} \ No newline at end of file diff --git a/Models/Utils/FileManager.cs b/Models/Utils/FileManager.cs new file mode 100644 index 0000000..29e363b --- /dev/null +++ b/Models/Utils/FileManager.cs @@ -0,0 +1,14 @@ +namespace AOLBackend.Models.Utils +{ + public class FileManager + { + public long id { get; set; } = 0!; + public int IdUsuario { get; set; } = 0!; + public int Proceso { get; set; } = 0!; + public string NombreArchivo { get; set; } = null!; + public string FechaRegistro { get; set; } = null!; + public string Tags { get; set; } = null!; + public long Size { get; set; } = 0!; + public byte Activo { get; set; } = 0!; + } +} \ No newline at end of file diff --git a/Models/Utils/FilePaths4Process.cs b/Models/Utils/FilePaths4Process.cs new file mode 100644 index 0000000..59cbc3b --- /dev/null +++ b/Models/Utils/FilePaths4Process.cs @@ -0,0 +1,7 @@ +namespace AOLBackend.Models.Utils +{ + public class FilePaths4Process + { + public string Path { set; get; } = string.Empty; + } +} \ No newline at end of file diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..3a76e3a --- /dev/null +++ b/Program.cs @@ -0,0 +1,84 @@ +using AOLBackend.Context; +using AOLBackend.Contracts; +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Contracts.Operaciones; +using AOLBackend.Contracts.Utils; + +using AOLBackend.Repository; +using AOLBackend.Repository.Catalogos; +using AOLBackend.Repository.Operaciones; +using AOLBackend.Repository.Utils; + +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.IdentityModel.Tokens; +using System.Text; + +var builder = WebApplication.CreateBuilder(args); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +// Catalogos +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +//Operaciones +builder.Services.AddScoped(); + +//Utilerias +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +builder.Services.AddControllers(); +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => +{ + options.RequireHttpsMetadata = false; + options.SaveToken = true; + options.TokenValidationParameters = new TokenValidationParameters() + { + ValidateIssuer = true, + ValidateAudience = true, + ValidAudience = builder.Configuration["Jwt:Audience"], + ValidIssuer = builder.Configuration["Jwt:Issuer"], + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])) + }; +}); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +//services cors +builder.Services.AddCors(p => p.AddPolicy("corsapp", builder => +{ + //builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader(); + + builder.WithOrigins("http://localhost:3000", + "http://localhost:7001", + "http://localhost:5000", + "https://localhost:5001", + "https://alphaomega.com.mx", + "https://www.alphaomega.com.mx", + "https://74.208.165.122", + "https://www.alphaomega.com.mx:443", + "https://74.208.165.122:443", + "http://localhost", + "http://74.208.165.122:5000").AllowAnyMethod().AllowAnyHeader(); +})); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); +app.UseAuthentication(); +app.UseCors("corsapp"); +app.UseAuthorization(); +app.MapControllers(); +app.Run(); diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json new file mode 100644 index 0000000..a74113c --- /dev/null +++ b/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:1112", + "sslPort": 44300 + } + }, + "profiles": { + "AOLBackend": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:5050;http://localhost:5001", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Repository/Catalogos/CatClientesRepository.cs b/Repository/Catalogos/CatClientesRepository.cs new file mode 100644 index 0000000..588b8c7 --- /dev/null +++ b/Repository/Catalogos/CatClientesRepository.cs @@ -0,0 +1,47 @@ +using AOLBackend.Context; +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using Dapper; +using System.Data; + +namespace AOLBackend.Repository.Catalogos +{ + public class CatClientesRepository : ICatClientesRepository + { + private readonly DapperContext _context; + private readonly IConfiguration _config; + public CatClientesRepository(DapperContext context, IConfiguration config) + { + _context = context; + _config = config; + } + + public async Task Append(ICatClientes data) + { + var query = "CatClientes_Append"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = data.id, + mCliente = data.Cliente, + }, commandType: CommandType.StoredProcedure); + return entrada.First(); + } + public async Task> GetAll() + { + var query = "CatClientes_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { }, commandType: CommandType.StoredProcedure); + return entrada; + } + + public async Task Delete(int id) + { + var query = "CatClientes_Delete"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { mid=id }, commandType: CommandType.StoredProcedure); + return true; + } + + } +} \ No newline at end of file diff --git a/Repository/Catalogos/CatProveedoresRepository.cs b/Repository/Catalogos/CatProveedoresRepository.cs new file mode 100644 index 0000000..7a31a2b --- /dev/null +++ b/Repository/Catalogos/CatProveedoresRepository.cs @@ -0,0 +1,46 @@ +using AOLBackend.Context; +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using Dapper; +using System.Data; + +namespace AOLBackend.Repository.Catalogos +{ + public class CatProveedoresRepository : ICatProveedoresRepository + { + private readonly DapperContext _context; + private readonly IConfiguration _config; + public CatProveedoresRepository(DapperContext context, IConfiguration config) + { + _context = context; + _config = config; + } + + public async Task Append(ICatProveedores data) + { + var query = "CatProveedores_Append"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = data.id, + mProveedor = data.Proveedor, + }, commandType: CommandType.StoredProcedure); + return entrada.First(); + } + public async Task> GetAll() + { + var query = "CatProveedores_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { }, commandType: CommandType.StoredProcedure); + return entrada; + } + + public async Task Delete(int id) + { + var query = "CatProveedores_Delete"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { mid=id }, commandType: CommandType.StoredProcedure); + return true; + } + } +} \ No newline at end of file diff --git a/Repository/Catalogos/CatRutasRepository.cs b/Repository/Catalogos/CatRutasRepository.cs new file mode 100644 index 0000000..1cd9839 --- /dev/null +++ b/Repository/Catalogos/CatRutasRepository.cs @@ -0,0 +1,55 @@ +using AOLBackend.Context; +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using AOLBackend.DTO.Catalogos; +using Dapper; +using System.Data; + +namespace AOLBackend.Repository.Catalogos +{ + public class CatRutasRepository : ICatRutasRepository + { + private readonly DapperContext _context; + private readonly IConfiguration _config; + public CatRutasRepository(DapperContext context, IConfiguration config) + { + _context = context; + _config = config; + } + + public async Task Append(ICatRutas data) + { + var query = "CatRutas_Append"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = data.id, + mCliente = data.Cliente, + mServicio = data.Servicio, + mPrecio = data.Precio, + mProveedor = data.Proveedor, + mCosto = data.Costo, + mOrigen = data.Origen, + mDestino = data.Destino, + mTipoUnidad = data.TipoUnidad, + mActivo = data.Activo + }, commandType: CommandType.StoredProcedure); + return entrada.First(); + } + public async Task> GetAll() + { + var query = "CatRutas_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { }, commandType: CommandType.StoredProcedure); + return entrada; + } + + public async Task Delete(int mid) + { + var query = "CatRutas_Delete"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { mid }, commandType: CommandType.StoredProcedure); + return true; + } + } +} \ No newline at end of file diff --git a/Repository/Catalogos/CatServiciosRepository.cs b/Repository/Catalogos/CatServiciosRepository.cs new file mode 100644 index 0000000..503cf06 --- /dev/null +++ b/Repository/Catalogos/CatServiciosRepository.cs @@ -0,0 +1,46 @@ +using AOLBackend.Context; +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using Dapper; +using System.Data; + +namespace AOLBackend.Repository.Catalogos +{ + public class CatServiciosRepository : ICatServiciosRepository + { + private readonly DapperContext _context; + private readonly IConfiguration _config; + public CatServiciosRepository(DapperContext context, IConfiguration config) + { + _context = context; + _config = config; + } + + public async Task Append(ICatServicios data) + { + var query = "CatServicios_Append"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = data.id, + mServicio = data.Servicio + }, commandType: CommandType.StoredProcedure); + return entrada.First(); + } + public async Task> GetAll() + { + var query = "CatServicios_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { }, commandType: CommandType.StoredProcedure); + return entrada; + } + + public async Task Delete(int id) + { + var query = "CatServicios_Delete"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { mid= @id }, commandType: CommandType.StoredProcedure); + return true; + } + } +} \ No newline at end of file diff --git a/Repository/Catalogos/CatTipoUnidadRepository.cs b/Repository/Catalogos/CatTipoUnidadRepository.cs new file mode 100644 index 0000000..bb7901f --- /dev/null +++ b/Repository/Catalogos/CatTipoUnidadRepository.cs @@ -0,0 +1,46 @@ +using AOLBackend.Context; +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using Dapper; +using System.Data; + +namespace AOLBackend.Repository.Catalogos +{ + public class CatTipoUnidadRepository : ICatTipoUnidadRepository + { + private readonly DapperContext _context; + private readonly IConfiguration _config; + public CatTipoUnidadRepository(DapperContext context, IConfiguration config) + { + _context = context; + _config = config; + } + + public async Task Append(ICatTipoUnidad data) + { + var query = "CatTipoUnidad_Append"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = data.id, + mTipoUnidad = data.TipoUnidad, + }, commandType: CommandType.StoredProcedure); + return entrada.First(); + } + public async Task> GetAll() + { + var query = "CatTipoUnidad_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { }, commandType: CommandType.StoredProcedure); + return entrada; + } + + public async Task Delete(int mid) + { + var query = "CatTipoUnidad_Delete"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { mid }, commandType: CommandType.StoredProcedure); + return true; + } + } +} \ No newline at end of file diff --git a/Repository/Catalogos/CatUbicacionesRepository.cs b/Repository/Catalogos/CatUbicacionesRepository.cs new file mode 100644 index 0000000..0b4a2ed --- /dev/null +++ b/Repository/Catalogos/CatUbicacionesRepository.cs @@ -0,0 +1,48 @@ +using AOLBackend.Context; +using AOLBackend.Contracts.Catalogos; +using AOLBackend.Models.Catalogos; +using Dapper; +using System.Data; + +namespace AOLBackend.Repository.Catalogos +{ + public class CatUbicacionesRepository : ICatUbicacionesRepository + { + private readonly DapperContext _context; + private readonly IConfiguration _config; + public CatUbicacionesRepository(DapperContext context, IConfiguration config) + { + _context = context; + _config = config; + } + + public async Task Append(ICatUbicaciones data) + { + var query = "CatUbicaciones_Append"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = data.id, + mUbicacion = data.Ubicacion, + mClasificacion = data.Clasificacion + }, commandType: CommandType.StoredProcedure); + return entrada.First(); + } + public async Task> GetAll() + { + var query = "CatUbicaciones_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { }, commandType: CommandType.StoredProcedure); + return entrada; + } + + public async Task Delete(int id) + { + var query = "CatUbicaciones_Delete"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { mid =id }, commandType: CommandType.StoredProcedure); + return true; + } + + } +} \ No newline at end of file diff --git a/Repository/MenuRepository.cs b/Repository/MenuRepository.cs new file mode 100644 index 0000000..bc3c901 --- /dev/null +++ b/Repository/MenuRepository.cs @@ -0,0 +1,25 @@ +using AOLBackend.Context; +using AOLBackend.Contracts; +using AOLBackend.Models; +using Dapper; +using System.Data; + +namespace AOLBackend.Repository +{ + public class MenuRepository : IMenuRepository + { + + private readonly DapperContext _context; + public MenuRepository(DapperContext context) { _context = context; } + public async Task> GetItemsMenu(IUsuarios user) + { + //var query = "[Menu.Get]"; + var query = "Menu_Get"; + using (var connection = _context.CreateConnection()) + { + var menu = await connection.QueryAsync(query, new { mid = user.Id }, commandType: CommandType.StoredProcedure); + return menu.ToList(); + } + } + } +} diff --git a/Repository/Operaciones/OpViajesRepository.cs b/Repository/Operaciones/OpViajesRepository.cs new file mode 100644 index 0000000..09ee95c --- /dev/null +++ b/Repository/Operaciones/OpViajesRepository.cs @@ -0,0 +1,110 @@ +using AOLBackend.Context; +using AOLBackend.Contracts.Operaciones; +using AOLBackend.DTO.Operaciones; +using Dapper; +using System.Data; + +namespace AOLBackend.Repository.Operaciones +{ + public class OpViajesRepository : IOpViajesRepository + { + private readonly DapperContext _context; + private readonly IConfiguration _config; + public OpViajesRepository(DapperContext context, IConfiguration config) + { + _context = context; + _config = config; + } + public async Task Append(DTOOpViajes data) + { + var query = "Operaciones_Viajes_Append"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = data.id, + mUsuario = data.Usuario, + mRefAgenciaAduanal = data.RefAgenciaAduanal, + mCliente = data.Cliente, + mTipoUnidad = data.TipoUnidad, + mNoCaja = data.NoCaja, + mPickUpNumber = data.PickUpNumber, + mOrigen = data.Origen, + mDestino = data.Destino, + mHazmat = data.Hazmat, + mTipoOperacion = data.TipoOperacion, + mPedimento = data.Pedimento, + }, commandType: CommandType.StoredProcedure); + return entrada.First(); + } + public async Task> AppendServicio(DTOOpViajesServicios data) + { + var query = "Operaciones_Viajes_Servicios_Append"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = data.id, + mIdViaje = data.IdViaje, + mIdServicio = data.IdServicio, + mAduana = data.Aduana, + mComentarios = data.Comentarios, + mIdProveedor = data.IdProveedor, + mNoCaja = data.NoCaja, + mCita = data.Cita + }, commandType: CommandType.StoredProcedure); + return entrada.ToList(); + } + public async Task> GetAll() + { + var query = "Operaciones_Viajes_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { }, commandType: CommandType.StoredProcedure); + return entrada; + } + public async Task> GetAllServices(int mStatus ) + { + var query = "Operaciones_Viajes_Servicios_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { mStatus }, commandType: CommandType.StoredProcedure); + return entrada; + } + public async Task GetLastTrailerBox(int mIdViaje) + { + var query = "Operaciones_Viajes_GetLastTrailerBox"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { mIdViaje }, commandType: CommandType.StoredProcedure); + return entrada.First(); + } + public async Task> GetStatusSecuence() + { + var query = "Operaciones_Viajes_Estatus_Secuencia_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { }, commandType: CommandType.StoredProcedure); + return entrada; + } + public async Task ChangeTripStatus(DTOChangeTripStatus data) + { + var query = "Operaciones_Viajes_ChangeStatus"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mIdViaje = data.IdViaje, + mSecuencia = data.IdEstatus + }, commandType: CommandType.StoredProcedure); + return entrada.First(); + } + public async Task Delete(int mid) + { + var query = "Operaciones_Viajes_Delete"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { mid }, commandType: CommandType.StoredProcedure); + return true; + } + public async Task DeleteService(int mid) + { + var query = "Operaciones_Viajes_Servicios_Delete"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new { mid }, commandType: CommandType.StoredProcedure); + return true; + } + } +} \ No newline at end of file diff --git a/Repository/UsuariosRepository.cs b/Repository/UsuariosRepository.cs new file mode 100644 index 0000000..179aca8 --- /dev/null +++ b/Repository/UsuariosRepository.cs @@ -0,0 +1,151 @@ +using AOLBackend.Context; +using AOLBackend.Contracts; +using AOLBackend.DTO; +using AOLBackend.DTO.Usuario; +using AOLBackend.Models; +using AOLBackend.Services.Tools; +using Dapper; +using System.Data; + +namespace AOLBackend.Repository +{ + public class UsuariosRepository : IUsuarioRepository + { + private readonly DapperContext _context; + private readonly IConfiguration _config; + public UsuariosRepository(DapperContext context, IConfiguration config) + { + _context = context; + _config = config; + } + + public async Task> GetAllUsuariosShort() + { + var query = "SELECT id, Usuario FROM Usuario WHERE Usuario<>'Admin'"; + using (var connection = _context.CreateConnection()) + { + var usuarios = await connection.QueryAsync(query); + return usuarios.ToList(); + } + } + + public async Task> GetAllUsuarios() + { + var query = "SELECT * FROM Usuario"; + using (var connection = _context.CreateConnection()) + { + var usuarios = await connection.QueryAsync(query); + return usuarios.ToList(); + } + } + + public async Task GetUsuarioById(int id) + { + var query = "SELECT * FROM Usuario WHERE id=@id"; + using (var connection = _context.CreateConnection()) + { + var usuario = await connection.QueryAsync(query, new { id = id }); + var usr = usuario.First(); + return usr; + } + } + + public async Task GetUsuario(DTOLogin user) + { + /* var query = "[Usuario.Get]"; */ + var query = "Usuario_Get"; + using (var connection = _context.CreateConnection()) + { + string passwordCrypto = CryptDecrypt.Encrypt(user.Contrasena); + var usuarios = await connection.QueryAsync(query, + new + { + mUsuario = user.Usuario, + mContrasena = user.Contrasena, + mHashContrasena = passwordCrypto, + }, commandType: CommandType.StoredProcedure); + IUsuarios userFound = usuarios.First(); + if (userFound == null) return userFound!; + var hashed = CryptDecrypt.Decrypt(userFound.Contrasena); + if (hashed != user.Contrasena) return null!; + return userFound; + } + } + + public async Task SearchUsuario(DTOLogin user) + { + var query = "SELECT * FROM Usuario WHERE Usuario=@Usuario"; + using (var connection = _context.CreateConnection()) + { + var usuario = await connection.QueryAsync(query, new { @Usuario = user.Usuario }); + var usr = usuario.First(); + return usr; + } + } + + public async Task ResetPassword(DTOLogin user) + { + var query = "[Usuario.ResetPassword]"; + using (var connection = _context.CreateConnection()) + { + var usuarios = await connection.QueryAsync(query, new + { + mUsuario = user.Usuario, + mContrasena = user.Contrasena, + mHashContrasena = CryptDecrypt.Encrypt(user.Contrasena), + }, commandType: CommandType.StoredProcedure); + if (usuarios.Count() == 0) return null!; + var userFound = usuarios.First(); + return userFound; + } + } + + public async Task CreateUsuario(IUsuarios user) + { + var query = "Usuario_Append"; + using (var connection = _context.CreateConnection()) + { + if (user.Id == 0) user.Contrasena = _config.GetValue("DefaultUser:Password"); + var usuario = await connection.QueryAsync(query, new + { + mid = user.Id, + mUsuario = user.Usuario, + mNombre = user.Nombre, + mContrasena = CryptDecrypt.Encrypt(user.Contrasena), + mTipoUsuario = user.TipoUsuario, + mActivo = user.Activo, + }, commandType: CommandType.StoredProcedure); + return usuario.First(); + } + } + + public async Task> ClonarUsuario(DTOClonarUsuario user) + { + var query = "clonarUsuario"; + using (var connection = _context.CreateConnection()) + { + var usuario = await connection.QueryAsync(query, new + { + mIdUsuarioOrigen = user.IDUsuarioOrigen, + mIdUsuarioDestino = user.IdUsuarioDestino + }, commandType: CommandType.StoredProcedure); + return usuario.ToList(); + } + } + + public async Task Activate(int id, int Activo) + { + var query = "Usuario.Activate"; + using (var connection = _context.CreateConnection()) + { + var usuario = await connection.QueryAsync(query, new + { + mid = id, + mActivo = Activo, + }, commandType: CommandType.StoredProcedure); + return true; + } + } + + } +} diff --git a/Repository/Utils/FileManagerRepository.cs b/Repository/Utils/FileManagerRepository.cs new file mode 100644 index 0000000..36478c1 --- /dev/null +++ b/Repository/Utils/FileManagerRepository.cs @@ -0,0 +1,89 @@ +using Dapper; +using AOLBackend.Context; +using AOLBackend.Contracts.Utils; +using AOLBackend.Models.Utils; +using System.Data; + +namespace AOLBackend.Repository.Utils +{ + public class FileManagerRepository : IFileManagerRepository + { + private readonly DapperContext _context; + public FileManagerRepository(DapperContext context) { _context = context; } + + public async Task FileManager(FileManager data) + { + var query = "Utils_FileManager_Append"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = 0, + mIdUsuario = data.IdUsuario, + mProceso = data.Proceso, + mNombreArchivo = data.NombreArchivo, + mTags = data.Tags, + mSize = data.Size + }, + commandType: CommandType.StoredProcedure); + return entrada.First(); + } + + public async Task getFileByProcess(long id, int Proceso) + { + var query = "Utils_FileManager_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = 0, + mProceso = Proceso, + mNombreArchivo = "", + mTags = id, + }, + commandType: CommandType.StoredProcedure); + return entrada.FirstOrDefault(new FileManager { id = id, Proceso = Proceso, NombreArchivo = "", Tags = "", Size = 0 }); + } + + public async Task getFileById(long id) + { + var query = "Utils_FileManager_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = id, + mProceso = 0, + mNombreArchivo = "", + mTags = id, + }, + commandType: CommandType.StoredProcedure); + return entrada.FirstOrDefault(new FileManager { id = id, Proceso = 0, NombreArchivo = "", Tags = "", Size = 0 }); + } + + public async Task> getAllFilesByProcess(long Tags, int Proceso) + { + var query = "Utils_FileManager_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = 0, + mProceso = Proceso, + mNombreArchivo = "", + mTags = Tags, + }, + commandType: CommandType.StoredProcedure); + return entrada.ToList(); + } + + public async Task deleteFileByProcess(long id, int Proceso) + { + var query = "Utils_FileManager_Delete"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = id, + mProceso = Proceso, + }, + commandType: CommandType.StoredProcedure); + return true; + } + } +} \ No newline at end of file diff --git a/Repository/Utils/FilePaths4ProcessRepository.cs b/Repository/Utils/FilePaths4ProcessRepository.cs new file mode 100644 index 0000000..e31dd03 --- /dev/null +++ b/Repository/Utils/FilePaths4ProcessRepository.cs @@ -0,0 +1,26 @@ +using Dapper; +using AOLBackend.Contracts.Utils; +using AOLBackend.Context; +using AOLBackend.Models.Utils; +using System.Data; + +namespace AOLBackend.Repository.Utils +{ + public class FilePaths4ProcessRepository : IFilePaths4ProcessRepository + { + private readonly DapperContext _context; + public FilePaths4ProcessRepository(DapperContext context) { _context = context; } + + public async Task getPaths4ProcessById(long id) + { + var query = "Utils_FileManager_RootPath_Get"; + using var connection = _context.CreateConnection(); + var entrada = await connection.QueryAsync(query, new + { + mid = id, + }, + commandType: CommandType.StoredProcedure); + return entrada.First(); + } + } +} \ No newline at end of file diff --git a/Services/EmailSender/EmailSender.cs b/Services/EmailSender/EmailSender.cs new file mode 100644 index 0000000..9673e47 --- /dev/null +++ b/Services/EmailSender/EmailSender.cs @@ -0,0 +1,61 @@ +using System.Net.Mail; +using System.Net; +using System; +using System.Collections.Generic; +using System.Text; +//using EASendMail; + +namespace AOLBackend.Services.EmailSender +{ + public class EmailSender + { + private IConfiguration _config; + + public EmailSender(IConfiguration config) + { + _config = config; + } + public String SrvSendEmail(string htmlContent, string Subject, string toEmail) + { + string EmailServer = _config.GetValue("EmailServer"); + string EmailAccount = _config.GetValue("EmailAccount"); + string[] Email = EmailAccount.Split('@'); + int EmailPort = Convert.ToInt32(_config.GetValue("EmailPort")); + string EmailPassword = _config.GetValue("EmailPassword"); + string EmailUser = Email[0]; + string EmailDomain = Email[1].Replace("@", ""); + DateTime now = DateTime.Now; + try + { + using (var smtp = new SmtpClient(EmailServer, EmailPort)) + { + smtp.UseDefaultCredentials = false; + smtp.Credentials = new NetworkCredential(EmailAccount, EmailPassword); + smtp.Host = EmailServer; + var correo = new MailMessage(EmailAccount, toEmail); + correo.From = new MailAddress("<" + EmailAccount + ">", "<" + EmailUser + ">"); + correo.Sender = new MailAddress("<" + EmailAccount + ">", "<" + EmailUser + ">"); + correo.Headers.Add("Message-Id", String.Concat("<", now.ToString("yyMMdd"), ".", now.ToString("HHmmss"), "@alphaomega.com.mx>")); + correo.To.Add(toEmail); + correo.Subject = Subject; + correo.Body = "htmlContent"; + correo.BodyEncoding = System.Text.Encoding.UTF8; + correo.SubjectEncoding = System.Text.Encoding.Default; + correo.IsBodyHtml = true; + smtp.Send(correo); + return "Message Sent Succesfully"; + } + } + catch (Exception ex) + { + return ex.ToString(); + } + } + + + public String SrvSendEmail2(string htmlContent, string Subject, string toEmail) + { + return ""; + } + } +} \ No newline at end of file diff --git a/Services/MFileManager/SvcMFileManager.cs b/Services/MFileManager/SvcMFileManager.cs new file mode 100644 index 0000000..dd64a6b --- /dev/null +++ b/Services/MFileManager/SvcMFileManager.cs @@ -0,0 +1,106 @@ +using AOLBackend.Models.Utils; +using AOLBackend.Contracts.Utils; +using Microsoft.AspNetCore.Mvc; + +namespace AOLBackend.Services.MFileManager +{ + public class SvcMFileManager + { + private readonly IFileManagerRepository _Repo; + private readonly IConfiguration _config; + // private readonly IFilePaths4ProcessRepository _RepoRelativePath; + private readonly string rootPath; + + public SvcMFileManager(IConfiguration config, IFileManagerRepository Repo, string _rootPath) + { + _config = config; + _Repo = Repo; + rootPath = _rootPath; + } + + public async Task> GetFilesFromLog(int Tags, int Proceso) + { + return await _Repo.getAllFilesByProcess(Tags, Proceso); + } + + public async Task getFileContentById(long id) + { + Boolean ExisteEnDisco = false; + byte[] emptyFile = System.IO.File.ReadAllBytes("c:\\downs\\empty.png"); + //byte[] emptyFile = System.IO.File.ReadAllBytes("D:\\data\\empty.png"); + MemoryStream emptyms = new MemoryStream(emptyFile); + FileManager recFound = await _Repo.getFileById(id); + if (!String.IsNullOrEmpty(recFound.NombreArchivo)) + { + try + { + if (System.IO.File.Exists(Path.Combine(rootPath, recFound.NombreArchivo))) + { + ExisteEnDisco = true; + } + else + { + return new FileStreamResult(emptyms, "image/png"); + } + } + catch (IOException ex) + { + return new FileStreamResult(emptyms, "image/png"); + } + if (ExisteEnDisco) + { + string fileMime = recFound.NombreArchivo.Substring(recFound.NombreArchivo.Length - 3).ToLower(); + var mime = "application/" + fileMime.ToLower(); + string targetFile = rootPath + "\\" + recFound.NombreArchivo; + if (System.IO.File.Exists(targetFile)) + { + byte[] pdfBytes = System.IO.File.ReadAllBytes(targetFile); + MemoryStream ms = new MemoryStream(pdfBytes); + return new FileStreamResult(ms, mime); + } + } + } + return new FileStreamResult(emptyms, "image/png"); + } + + public async Task> SaveFile2DiskList(List FileList) + { + DateTime time = DateTime.Now; + var filePaths = new List(); + FileManager data = new FileManager(); + foreach (var file in FileList) + { + string fileMime = file.FileName.Substring(file.FileName.Length - 4); + string newFileName = file.FileName.Replace(fileMime, "") + "_" + time.ToString("yyyy_MM_dd_HH_mm_ss") + fileMime; + if (file.Length > 0) + { + var filePath = rootPath + newFileName; + using (var stream = System.IO.File.Create(filePath)) + { + await file.CopyToAsync(stream); + filePaths.Add(newFileName); + } + } + } + return filePaths; + } + + public async Task> SaveFileLog(List files, int Tags, int Proceso, int Usuario) + { + List resultados = new List(); + foreach (string file in files) + { + FileManager data = new FileManager(); + long fileLength = new System.IO.FileInfo(rootPath + file).Length / 1024; + data.id = 0; + data.IdUsuario = Usuario; + data.Proceso = Proceso; + data.NombreArchivo = file; + data.Tags = Tags.ToString(); + data.Size = fileLength; + await _Repo.FileManager(data); + } + return await _Repo.getAllFilesByProcess(Tags, Proceso); + } + } +} diff --git a/Services/Tools/CryptDecrypt.cs b/Services/Tools/CryptDecrypt.cs new file mode 100644 index 0000000..10e9967 --- /dev/null +++ b/Services/Tools/CryptDecrypt.cs @@ -0,0 +1,227 @@ +using System.Security.Cryptography; +using System.Text; + +namespace AOLBackend.Services.Tools +{ + public class CryptDecrypt + { + private readonly static string keyString = "G3mc0H42hk3y2!0$2*2#n4813dc2h47p"; + private readonly static int BlockSize = 128; + public static string Encrypt(string text) + { + byte[] iv = new byte[16]; + byte[] array; + using (Aes aes = Aes.Create()) + { + aes.Key = Encoding.UTF8.GetBytes(keyString); + aes.IV = iv; + ICryptoTransform encrypt = aes.CreateEncryptor(aes.Key, aes.IV); + using (MemoryStream ms = new MemoryStream()) + { + using (CryptoStream cryptoStream = new CryptoStream((Stream)ms, encrypt, CryptoStreamMode.Write)) + { + using (StreamWriter streamWriter = new StreamWriter(cryptoStream)) + { + streamWriter.Write(text); + } + array = ms.ToArray(); + } + } + } + return Convert.ToBase64String(array); + } + + public static string Decrypt(string text) + { + byte[] iv = new byte[16]; + byte[] buffer = Convert.FromBase64String(text); + using (Aes aes = Aes.Create()) + { + aes.Key = Encoding.UTF8.GetBytes(keyString); + aes.IV = iv; + ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); + using (MemoryStream ms = new MemoryStream(buffer)) + { + using (CryptoStream cryptoStream = new CryptoStream((Stream)ms, decryptor, CryptoStreamMode.Read)) + { + using (StreamReader sr = new StreamReader(cryptoStream)) + { + return sr.ReadToEnd(); + } + } + } + } + } + + /* public static string EncryptString(string text) + { + var key = Encoding.UTF8.GetBytes(keyString); + using (var aesAlg = Aes.Create()) + { + using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV)) + { + using (var msEncrypt = new MemoryStream()) + { + using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) + using (var swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(text); } + var iv = aesAlg.IV; + var decryptedContent = msEncrypt.ToArray(); + var result = new byte[iv.Length + decryptedContent.Length]; + Buffer.BlockCopy(iv, 0, result, 0, iv.Length); + Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length); + msEncrypt.Flush(); + msEncrypt.Close(); + return Convert.ToBase64String(result); + } + } + } + } + + public static string DecryptString(string cipherText) + { + var fullCipher = Convert.FromBase64String(cipherText); + var iv = new byte[16]; + var cipher = new byte[16]; + Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length); + Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length); + var key = Encoding.UTF8.GetBytes(keyString); + using (var aesAlg = Aes.Create()) + { + using (var decryptor = aesAlg.CreateDecryptor(key, iv)) + { + string result; + using (var msDecrypt = new MemoryStream(cipher)) + { + using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) + { + using (var srDecrypt = new StreamReader(csDecrypt)) + { + result = srDecrypt.ReadToEnd(); + } + } + } + return result; + } + } + } + + private static char Cipher(char ch, int key) + { + if (!char.IsLetter(ch)) + return ch; + + char offset = char.IsUpper(ch) ? 'A' : 'a'; + return (char)((((ch + key) - offset) % 26) + offset); + } + + public static string Encipher(string input, int key) + { + string output = string.Empty; + + foreach (char ch in input) + output += Cipher(ch, key); + + return output; + } + + public static string Decipher(string input, int key) + { + return Encipher(input, 26 - key); + } + + + static public byte[] Encryption(byte[] Data, bool DoOAEPPadding) + { + try + { + byte[] encryptedData; + using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) + { + RSA.ImportParameters(RSA.ExportParameters(false)); + encryptedData = RSA.Encrypt(Data, DoOAEPPadding); + } + return encryptedData; + } + catch (CryptographicException e) + { + Console.WriteLine(e.Message); + return null; + } + } + + static public byte[] Decryption(byte[] Data, bool DoOAEPPadding) + { + try + { + byte[] decryptedData; + using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) + { + RSA.ImportParameters(RSA.ExportParameters(true)); + decryptedData = RSA.Decrypt(Data, DoOAEPPadding); + } + return decryptedData; + } + catch (CryptographicException e) + { + Console.WriteLine(e.ToString()); + return null; + } + } + */ + public static string Encryption(string strText) + { + var publicKey = "21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=AQAB"; + + var testData = Encoding.UTF8.GetBytes(strText); + + using (var rsa = new RSACryptoServiceProvider(1024)) + { + try + { + // client encrypting data with public key issued by server + rsa.FromXmlString(publicKey.ToString()); + + var encryptedData = rsa.Encrypt(testData, true); + + var base64Encrypted = Convert.ToBase64String(encryptedData); + + return base64Encrypted; + } + finally + { + rsa.PersistKeyInCsp = false; + } + } + } + + public static string Decryption(string strText) + { + var privateKey = "21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=AQAB

/aULPE6jd5IkwtWXmReyMUhmI/nfwfkQSyl7tsg2PKdpcxk4mpPZUdEQhHQLvE84w2DhTyYkPHCtq/mMKE3MHw==

3WV46X9Arg2l9cxb67KVlNVXyCqc/w+LWt/tbhLJvV2xCF/0rWKPsBJ9MC6cquaqNPxWWEav8RAVbmmGrJt51Q==8TuZFgBMpBoQcGUoS2goB4st6aVq1FcG0hVgHhUI0GMAfYFNPmbDV3cY2IBt8Oj/uYJYhyhlaj5YTqmGTYbATQ==FIoVbZQgrAUYIHWVEYi/187zFd7eMct/Yi7kGBImJStMATrluDAspGkStCWe4zwDDmdam1XzfKnBUzz3AYxrAQ==QPU3Tmt8nznSgYZ+5jUo9E0SfjiTu435ihANiHqqjasaUNvOHKumqzuBZ8NRtkUhS6dsOEb8A2ODvy7KswUxyA==cgoRoAUpSVfHMdYXW9nA3dfX75dIamZnwPtFHq80ttagbIe4ToYYCcyUz5NElhiNQSESgS5uCgNWqWXt5PnPu4XmCXx6utco1UVH8HGLahzbAnSy6Cj3iUIQ7Gj+9gQ7PkC434HTtHazmxVgIR5l56ZjoQ8yGNCPZnsdYEmhJWk=
"; + + var testData = Encoding.UTF8.GetBytes(strText); + + using (var rsa = new RSACryptoServiceProvider(1024)) + { + try + { + var base64Encrypted = strText; + + // server decrypting data with private key + rsa.FromXmlString(privateKey); + + var resultBytes = Convert.FromBase64String(base64Encrypted); + var decryptedBytes = rsa.Decrypt(resultBytes, true); + var decryptedData = Encoding.UTF8.GetString(decryptedBytes); + return decryptedData.ToString(); + } + finally + { + rsa.PersistKeyInCsp = false; + } + } + } + + + } + +} diff --git a/WeatherForecast.cs b/WeatherForecast.cs new file mode 100644 index 0000000..9e94a01 --- /dev/null +++ b/WeatherForecast.cs @@ -0,0 +1,13 @@ +namespace AOLBackend +{ + public class WeatherForecast + { + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string? Summary { get; set; } + } +} \ No newline at end of file diff --git a/appsettings.Development.json b/appsettings.Development.json new file mode 100644 index 0000000..41f8241 --- /dev/null +++ b/appsettings.Development.json @@ -0,0 +1,18 @@ + { + "ConnectionStrings": { + "SqlConnection": "server=.; database=AOL; Integrated Security=true;TrustServerCertificate=True;", + "MySQLConnection": "Server=localhost; User ID=root; Password=toor1234.; Database=AOL" + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "pathArchivoElectronico": "C:\\downs\\ArchivoElectronicoSIR\\www.gemcousa.com\\SIR-GEMCO\\DOCS-SIR\\", + "pathTemp": "C:\\downs\\temp\\", + "pathFotosBodega": "c:\\data\\Bodega\\Fotos\\", + "pathZipCorresponsales": "C:\\data\\", + "CorresponsalesFilePath": "C:\\data\\", + "Allfiles": "C:\\data\\AOL\\" +} diff --git a/appsettings.json b/appsettings.json new file mode 100644 index 0000000..0a49959 --- /dev/null +++ b/appsettings.json @@ -0,0 +1,37 @@ +{ + "ConnectionStrings": { + "SqlConnection": "server=localhost; database=AOL; User Id=sa;Password=toor1234;Encrypt=False;", + "Mysql": "Server=127.0.0.1;Database=aol;Uid=root;Pwd=Chispa10192;" + + }, + "DefaultUser": { + "Password": "Bienvenido123!" + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Jwt": { + "Key": "GFE1j5KLolZHDK9iKw5xK17Rz4ty7BlbXgnjPL6dNwVCCNQWU8uRGVyZmAZPWZMs4XX0phFMS849p25Lrwsn31Bi4J7GT2HQ9xeWlJLarJPDyoRZZvChpovwgrquQ9Pd", + "Issuer": "JWTAuthenticationServer", + "Audience": "JWTServicePostmanClient", + "Subject": "JWTServiceAccessToken", + "ExpirationHours": 4, + "ExpirationMinutes": 1 + }, + "EmailServer": "alphaomega-com-mx.mail.protection.outlook.com", + "EmailPort": "25", + "EmailUser": "noreply", + "EmailDomian": "alphaomega.com.mx", + "EmailAccount": "noreply@alphaomega.com.mx", + "EmailPassword": "Al%G22a3", + "pathArchivoElectronico": "D:\\data\\ArchivoElectronicoSIR\\www.gemcousa.com\\SIR-GEMCO\\DOCS-SIR\\", + "pathTemp": "D:\\data\\temp\\", + "pathFotosBodega": "D:\\data\\Bodega\\Fotos\\", + "pathZipCorresponsales": "D:\\data\\Corresponsales\\Zips\\", + "CorresponsalesFilePath": "D:\\data\\Corresponsales\\", + "AllFiles": "D:\\data\\AOL\\" +}