boilerPlate

main
unknown 2 years ago
commit fb82476edc
  1. BIN
      .vs/AMAZONBackend/DesignTimeBuild/.dtbcache.v2
  2. BIN
      .vs/AMAZONBackend/FileContentIndex/48d7a7fa-ec86-4c38-a995-4d9e552846e7.vsidx
  3. BIN
      .vs/AMAZONBackend/FileContentIndex/f90e6fc6-7c3b-4df6-8557-2eeb0951c186.vsidx
  4. BIN
      .vs/AMAZONBackend/FileContentIndex/fcfa20c1-43b4-47e9-ac27-82aed8934872.vsidx
  5. BIN
      .vs/AMAZONBackend/FileContentIndex/fdbe9cea-09e1-4b43-b2e2-244b37b7adf8.vsidx
  6. 0
      .vs/AMAZONBackend/FileContentIndex/read.lock
  7. 1026
      .vs/AMAZONBackend/config/applicationhost.config
  8. BIN
      .vs/AMAZONBackend/v17/.futdcache.v2
  9. BIN
      .vs/AMAZONBackend/v17/.suo
  10. BIN
      .vs/ProjectEvaluation/amazonbackend.metadata.v5.2
  11. BIN
      .vs/ProjectEvaluation/amazonbackend.projects.v5.2
  12. 25
      AMAZONBackend.sln
  13. 19
      AMAZONBackend/AMAZONBackend.csproj
  14. 38
      AMAZONBackend/Clientes/Amazon/Contracts/IAmazonRepository.cs
  15. 8
      AMAZONBackend/Clientes/Amazon/DTO/DTO2096CheckDetail.cs
  16. 9
      AMAZONBackend/Clientes/Amazon/DTO/DTO2096Descripcioncs.cs
  17. 10
      AMAZONBackend/Clientes/Amazon/DTO/DTO2096Fraccion.cs
  18. 11
      AMAZONBackend/Clientes/Amazon/DTO/DTO2096FraccionDescripcion.cs
  19. 10
      AMAZONBackend/Clientes/Amazon/DTO/DTO2096ItemAutorizado.cs
  20. 14
      AMAZONBackend/Clientes/Amazon/DTO/DTO2096NoParte.cs
  21. 9
      AMAZONBackend/Clientes/Amazon/DTO/DTO2096SightLinecs.cs
  22. 7
      AMAZONBackend/Clientes/Amazon/Model/DashBoardTotal.cs
  23. 49
      AMAZONBackend/Clientes/Amazon/Model/I2096Detail.cs
  24. 31
      AMAZONBackend/Clientes/Amazon/Model/I2096Header.cs
  25. 7
      AMAZONBackend/Clientes/Amazon/Model/I2096ListaIDs.cs
  26. 24
      AMAZONBackend/Clientes/Amazon/Model/I2096NoPartes.cs
  27. 8
      AMAZONBackend/Clientes/Amazon/Model/I2096PaisClaves.cs
  28. 19
      AMAZONBackend/Clientes/Amazon/Model/I2096ShipFromAddress.cs
  29. 416
      AMAZONBackend/Clientes/Amazon/Repository/AmazonRepository.cs
  30. 18
      AMAZONBackend/Context/DapperContext.cs
  31. 15
      AMAZONBackend/Contracts/Clientes/CasaCuervo/ICasaCuervoRepository.cs
  32. 9
      AMAZONBackend/Contracts/IMenuRepository.cs
  33. 20
      AMAZONBackend/Contracts/IPerfilesRepository.cs
  34. 21
      AMAZONBackend/Contracts/IUsuarioRepository.cs
  35. 15
      AMAZONBackend/Contracts/Utils/IFileManagerRepository.cs
  36. 9
      AMAZONBackend/Contracts/Utils/IFilePaths4ProcessRepository.cs
  37. 9
      AMAZONBackend/Contracts/Utils/IPDFGenerator.cs
  38. 7
      AMAZONBackend/Contracts/Utils/IvalidaFraccion.cs
  39. 139
      AMAZONBackend/Controllers/AuthController.cs
  40. 357
      AMAZONBackend/Controllers/Clientes/Amazon/AmazonInvoiceController.cs
  41. 202
      AMAZONBackend/Controllers/FileManagerController.cs
  42. 175
      AMAZONBackend/Controllers/UsuariosController.cs
  43. 63
      AMAZONBackend/Controllers/Utils/MfileManagerController.cs
  44. 55
      AMAZONBackend/Crypto/CrypDecrypto.cs
  45. 8
      AMAZONBackend/DTO/Clientes/CasaCuervo/DTO325AduanaPedidos.cs
  46. 16
      AMAZONBackend/DTO/Clientes/CasaCuervo/DTO325ComplementaPedido.cs
  47. 18
      AMAZONBackend/DTO/Clientes/CasaCuervo/DTO325UpdateFromWeb.cs
  48. 10
      AMAZONBackend/DTO/DTOIteamMenuPerfil.cs
  49. 8
      AMAZONBackend/DTO/DTOLogin.cs
  50. 8
      AMAZONBackend/DTO/DTORespuestacs.cs
  51. 10
      AMAZONBackend/DTO/DTORolesAsignados.cs
  52. 8
      AMAZONBackend/DTO/Usuario/DTOClonarUsuario.cs
  53. 8
      AMAZONBackend/DTO/Usuario/DTOPerfilCreate.cs
  54. 9
      AMAZONBackend/DTO/Usuario/DTOUsuariosPerfilParecido.cs
  55. 8
      AMAZONBackend/DTO/Usuario/DtoUsuarioShort.cs
  56. 89
      AMAZONBackend/Interface/IExelDataReader.cs
  57. 9
      AMAZONBackend/Models/CatRoles.cs
  58. 31
      AMAZONBackend/Models/Clientes/CasaCuervo/I3225Pedidos.cs
  59. 11
      AMAZONBackend/Models/Menu.cs
  60. 8
      AMAZONBackend/Models/Perfiles.cs
  61. 16
      AMAZONBackend/Models/PerfilesMenu.cs
  62. 12
      AMAZONBackend/Models/Provedores.cs
  63. 11
      AMAZONBackend/Models/Transportistas.cs
  64. 37
      AMAZONBackend/Models/Usuarios.cs
  65. 14
      AMAZONBackend/Models/Utils/FileManager.cs
  66. 7
      AMAZONBackend/Models/Utils/FilePaths4Process.cs
  67. 73
      AMAZONBackend/Program.cs
  68. 31
      AMAZONBackend/Properties/launchSettings.json
  69. 148
      AMAZONBackend/Repositorio/Clientes/CasaCuervo.cs
  70. 24
      AMAZONBackend/Repositorio/MenuRepository.cs
  71. 107
      AMAZONBackend/Repositorio/PerfilRepository.cs
  72. 174
      AMAZONBackend/Repositorio/UsuariosRepository.cs
  73. 88
      AMAZONBackend/Repositorio/Utils/FileManagerRepository.cs
  74. 26
      AMAZONBackend/Repositorio/Utils/FilePaths4ProcessRepository.cs
  75. 160
      AMAZONBackend/Services/Clientes/SCasaCuervo/SCasaCuervo.cs
  76. 107
      AMAZONBackend/Services/MFileManager/SvcMFileManager.cs
  77. 54
      AMAZONBackend/Services/PDFGenerator.cs/PDFGenerator.cs
  78. 59
      AMAZONBackend/Services/Utilerias.cs
  79. 102
      AMAZONBackend/Services/ValidarFraccion/SrvValidaFraccion.cs
  80. 13
      AMAZONBackend/WeatherForecast.cs
  81. 8
      AMAZONBackend/appsettings.Development.json
  82. 22
      AMAZONBackend/appsettings.json
  83. 1510
      AMAZONBackend/bin/Debug/net6.0/AMAZONBackend.deps.json
  84. BIN
      AMAZONBackend/bin/Debug/net6.0/AMAZONBackend.dll
  85. BIN
      AMAZONBackend/bin/Debug/net6.0/AMAZONBackend.exe
  86. BIN
      AMAZONBackend/bin/Debug/net6.0/AMAZONBackend.pdb
  87. 19
      AMAZONBackend/bin/Debug/net6.0/AMAZONBackend.runtimeconfig.json
  88. BIN
      AMAZONBackend/bin/Debug/net6.0/Dapper.dll
  89. BIN
      AMAZONBackend/bin/Debug/net6.0/DinkToPdf.dll
  90. BIN
      AMAZONBackend/bin/Debug/net6.0/ExcelDataReader.DataSet.dll
  91. BIN
      AMAZONBackend/bin/Debug/net6.0/ExcelDataReader.dll
  92. BIN
      AMAZONBackend/bin/Debug/net6.0/Microsoft.IdentityModel.Abstractions.dll
  93. BIN
      AMAZONBackend/bin/Debug/net6.0/Microsoft.IdentityModel.JsonWebTokens.dll
  94. BIN
      AMAZONBackend/bin/Debug/net6.0/Microsoft.IdentityModel.Logging.dll
  95. BIN
      AMAZONBackend/bin/Debug/net6.0/Microsoft.IdentityModel.Tokens.dll
  96. BIN
      AMAZONBackend/bin/Debug/net6.0/Microsoft.OpenApi.dll
  97. BIN
      AMAZONBackend/bin/Debug/net6.0/Swashbuckle.AspNetCore.Swagger.dll
  98. BIN
      AMAZONBackend/bin/Debug/net6.0/Swashbuckle.AspNetCore.SwaggerGen.dll
  99. BIN
      AMAZONBackend/bin/Debug/net6.0/Swashbuckle.AspNetCore.SwaggerUI.dll
  100. BIN
      AMAZONBackend/bin/Debug/net6.0/System.Data.SqlClient.dll
  101. Some files were not shown because too many files have changed in this diff Show More

File diff suppressed because it is too large Load Diff

Binary file not shown.

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33205.214
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AMAZONBackend", "AMAZONBackend\AMAZONBackend.csproj", "{015FF3E8-F9CF-4182-8FBD-47C36573FD17}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{015FF3E8-F9CF-4182-8FBD-47C36573FD17}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{015FF3E8-F9CF-4182-8FBD-47C36573FD17}.Debug|Any CPU.Build.0 = Debug|Any CPU
{015FF3E8-F9CF-4182-8FBD-47C36573FD17}.Release|Any CPU.ActiveCfg = Release|Any CPU
{015FF3E8-F9CF-4182-8FBD-47C36573FD17}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1888385F-8FEB-4DA6-9F39-6DDF77107315}
EndGlobalSection
EndGlobal

@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.123" />
<PackageReference Include="DinkToPdf" Version="1.0.8" />
<PackageReference Include="ExcelDataReader" Version="3.6.0" />
<PackageReference Include="ExcelDataReader.DataSet" Version="3.6.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.5" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.26.0" />
</ItemGroup>
</Project>

@ -0,0 +1,38 @@
using AMAZONBackend.Clientes.Amazon.DTO;
using AMAZONBackend.Clientes.Amazon.Models;
using AMAZONBackend.DTO;
namespace AMAZONBackend.Clientes.Amazon.Contracts
{
public interface IAmazonRepository
{
public Task<List<I2096Header>> AmazonPendingClasificationInvoiceGet();
public Task<List<I2096Header>> InvoicePendingFromAmazonGet();
public Task<List<I2096Header>> AmazonFinishedClasificationInvoiceGet();
public Task<List<I2096Header>> AmazonPendingTraficInvoiceGet();
public Task<List<I2096Header>> AmazonLinkInvoice2TrafficGet();
public Task<I2096Detail> AutorizadoItemFactura(DTO2096FraccionDescripcion data);
public Task<I2096Detail> SetFraccionDescripcion(DTO2096FraccionDescripcion data);
public Task<I2096Detail> FraccionSet(DTO2096Fraccion data);
public Task<I2096Detail> DescripcionSet(DTO2096Descripcion data);
// public Task<I2096Detail> ItemAutorizadoSet(DTO2096ItemAutorizado data);
public Task<IEnumerable<DTO2096Fraccion>> GetFraccionesPendientesValidar();
public Task<bool> SetFraccionPendienteValidar(int id, bool valor);
public Task<bool> TerminaClasificarFactura(int id);
public Task<IEnumerable<I2096NoPartes>> NoPartesGet(string Search);
public Task<IEnumerable<I2096PaisClaves>> PaisClavesGet();
public Task<DashboardTotal> DashboardInvoicesGet(short Mode);
public Task<DTORespuesta> SePuedeTerminardeClasificarFactura(int id);
public Task<DTORespuesta> SePuedeTerminardeClasificarFacturaEsperandoRespuesta(int id);
public Task<DTO2096SightLine> SightLineSET(DTO2096SightLine data);
public Task<DTORespuesta> SePuedeTerminarXTraficoFactura(int id);
public Task<bool> TerminaXTraficoFactura(int id);
public Task<List<I2096Header>> AmazonInvoiceGet(int id);
public Task<IEnumerable<I2096ShipFromAddress>> AmazonShippingInfo(int id);
public Task<I2096Detail> CheckDetail(int id);
public Task<bool> EnviaEsperaRespuestaAmazon(int id);
public Task<bool> AssignInvoice(int IdUsuario, int IdFactura);
}
}

@ -0,0 +1,8 @@
namespace AMAZONBackend.Clientes.Amazon.DTO
{
public class DTO2096CheckDetail
{
public int Id { get; set; } = 0;
public Boolean Check { get; set; } = false;
}
}

@ -0,0 +1,9 @@
namespace AMAZONBackend.Clientes.Amazon.DTO
{
public class DTO2096Descripcion
{
public int Id { get; set; } = 0;
public string Descripcion { get; set; } = null!;
public byte ConfirmaDescripcion { set; get; } = 0;
}
}

@ -0,0 +1,10 @@
namespace AMAZONBackend.Clientes.Amazon.DTO
{
public class DTO2096Fraccion
{
public int Id { get; set; } = 0;
public string Fraccion { get; set; } = null!;
public byte ConfirmaFraccion { get; set; } = 0;
}
}

@ -0,0 +1,11 @@
namespace AMAZONBackend.Clientes.Amazon.DTO
{
public class DTO2096FraccionDescripcion
{
public int Id { get; set; } = 0;
public string Fraccion { get; set; } = null!;
public string CumplimientoNormativo { get; set; } = null!;
public string Comentarios { get; set; } = null!;
public string DescripcionGEMCO { get; set; } = null!;
}
}

@ -0,0 +1,10 @@
namespace AMAZONBackend.Clientes.Amazon.DTO
{
public class DTO2096ItemAutorizado
{
public int Id { get; set; } = 0;
public Boolean Autorizado { get; set; } = false;
public string RequerimientoNormativo { get; set; } = null!;
public string Comentarios { get; set; } = null!;
}
}

@ -0,0 +1,14 @@
namespace AMAZONBackend.Clientes.Amazon.DTO
{
public class DTO2096NoParte
{
public int Id { get; set; } = 0;
public int TipoOperacion { get; set; } = 0;
public string Fraccion { get; set; } = null!;
public string DescripcionFactura { get; set; } = null!;
public string DescripcionAgenteAduanal { get; set; } = null!;
public string PaisOrigen { get; set; } = null!;
public string UMF { get; set; } = null!;
public string UMC { get; set; } = null!;
}
}

@ -0,0 +1,9 @@
namespace AMAZONBackend.Clientes.Amazon.DTO
{
public class DTO2096SightLine
{
public int Id { get; set; } = 0;
public Boolean SightLine { get; set; } = false;
public string ComentariosSightLine { get; set; } = null!;
}
}

@ -0,0 +1,7 @@
namespace AMAZONBackend.Clientes.Amazon.Models
{
public class DashboardTotal
{
public int Total { get; set; } = 0;
}
}

@ -0,0 +1,49 @@
namespace AMAZONBackend.Clientes.Amazon.Models
{
public class I2096Detail
{
public int Id { get; set; } = 0;
public int IdHeader { get; set; } = 0;
public string InvoiceNumber { get; set; } = null!;
public string AmazonShipmentReferenceId { get; set; } = null!;
public string TrailerId { get; set; } = null!;
public string ItemId { get; set; } = null!;
public string ItemIdType { get; set; } = null!;
public string ItemDescription { get; set; } = null!;
public string PedimentoDescription { get; set; } = null!;
public string DestinationHTSCode { get; set; } = null!;
public byte ValidaFraccionOriginal { get; set; } = 0;
public byte ConfirmaFraccion { get; set; } = 0;
public string FraccionGEMCO { get; set; } = null!;
public byte ConfirmaDescripcion { get; set; } = 0;
public string DescripcionGEMCO { get; set; } = null!;
public string SourceHTSCode { get; set; } = null!;
public string ECCN { get; set; } = null!;
public string LicEx { get; set; } = null!;
public string CountryOfOrigin { get; set; } = null!;
public string ProductGroup { get; set; } = null!;
public string UPC { get; set; } = null!;
public string Brand { get; set; } = null!;
public string Model { get; set; } = null!;
public string ItemQuantityUnitOfMeasure { get; set; } = null!;
public int Quantity { get; set; } = 0;
public string NetWeightUnitOfMeasure { get; set; } = null!;
public double WeightValue { get; set; } = 0;
public string ActualUnitCostChargeOrAllowance { get; set; } = null!;
public string ActualUnitCostCurrencyISOCode { get; set; } = null!;
public double ActualUnitCostMonetaryAmount { get; set; } = 0;
public string TotalUnitValueChargeOrAllowance { get; set; } = null!;
public string TotalUnitValueCurrencyISOCode { get; set; } = null!;
public double TotalUnitValueMonetaryAmount { get; set; } = 0;
public string Archivo { get; set; } = null!;
public string FCreacion { get; set; } = null!;
public short Estatus { get; set; } = 0;
public bool Autorizado { get; set; } = false;
public string CumplimientoNormativo { get; set; } = null!;
public string Comentarios { get; set; } = null!;
public bool SightLine { get; set; } = false;
public string ComentariosSightLine { get; set; } = null!;
public bool Checked { get; set; } = false;
public byte Activo { get; set; } = 0;
}
}

@ -0,0 +1,31 @@
namespace AMAZONBackend.Clientes.Amazon.Models
{
public class I2096Header
{
public int Id { get; set; } = 0;
public string CommercialInvoiceDate { get; set; } = null!;
public string InvoiceNumber { get; set; } = null!;
public string Name { get; set; } = null!;
public string TrailerNumber { get; set; } = null!;
public string TrailerId { get; set; } = null!;
public string PorOfLoading { get; set; } = null!;
public string PortOfEntry { get; set; } = null!;
public string PaymentsTerms { get; set; } = null!;
public string Incoterms { get; set; } = null!;
public string HAWB { get; set; } = null!;
public string TotalInvoiceQuantityUnitOfMeasure { get; set; } = null!;
public int TotalInvoiceQuantity { get; set; } = 0;
public string TotalInvoiceWeightUnitOfMeasure { get; set; } = null!;
public double TotalInvoiceWeight { get; set; } = 0;
public string TotalInvoiceValueChargeOrAllowance { get; set; } = null!;
public string TotalInvoiceValueCurrencyISOCode { get; set; } = null!;
public double TotalInvoiceValueMonetaryAmount { get; set; } = 0;
public string FootNote { get; set; } = null!;
public string Archivo { get; set; } = null!;
public string FCreacion { get; set; } = null!;
public int Clasificador { get; set; } = 0!;
public short Estatus { get; set; } = 0;
public bool max { get; set; } = false;
public List<I2096Detail> Detail { get; set; } = new List<I2096Detail>();
}
}

@ -0,0 +1,7 @@
namespace AMAZONBackend.Clientes.Amazon.Model
{
public class I2096ListaIDs
{
public int id { get; set; } = 0;
}
}

@ -0,0 +1,24 @@
namespace AMAZONBackend.Clientes.Amazon.Models
{
public class I2096NoPartes
{
public int id { get; set; } = 0;
public int ClaveCliente { get; set; } = 0;
public string Parte { get; set; } = null!;
public int ClaveProveedor { get; set; } = 0;
public byte TipoOperacion { get; set; } = 0;
public string Fraccion { get; set; } = null!;
public string Subdivision { get; set; } = null!;
public string DescripcionFactura { get; set; } = null!;
public string DescripcionAgenteAduanal { get; set; } = null!;
public string PaisOrigen { get; set; } = null!;
public string UnidadMedidaFactura { get; set; } = null!;
public string UnidadMedidaCOVE { get; set; } = null!;
public string FechaConfirmacion { get; set; } = null!;
public int UsuarioConfirmacion { get; set; } = 0;
public string FechaModificacion { get; set; } = null!;
public int UsuarioModificacion { get; set; } = 0;
public byte Activo { get; set; } = 0;
}
}

@ -0,0 +1,8 @@
namespace AMAZONBackend.Clientes.Amazon.Models
{
public class I2096PaisClaves
{
public string PaisNom { get; set; } = null!;
public string Clave_a3 { get; set; } = null!;
}
}

@ -0,0 +1,19 @@
namespace AMAZONBackend.Clientes.Amazon.Models
{
public class I2096ShipFromAddress
{
public int Id { get; set; } = 0;
public int IdHeader { get; set; } = 0;
public string InvoiceNumber { get; set; } = null!;
public string AddressType { get; set; } = null!;
public string Name { get; set; } = null!;
public string AddressLine1 { get; set; } = null!;
public string City { get; set; } = null!;
public string StateProvince { get; set; } = null!;
public string Zip { get; set; } = null!;
public string CountryCode { get; set; } = null!;
public string CountryName { get; set; } = null!;
public string Archivo { get; set; } = null!;
public string FCreacion { get; set; } = null!;
}
}

@ -0,0 +1,416 @@
using System.Data;
using Dapper;
using AMAZONBackend.Clientes.Amazon.Contracts;
using AMAZONBackend.Clientes.Amazon.DTO;
using AMAZONBackend.Clientes.Amazon.Model;
using AMAZONBackend.Clientes.Amazon.Models;
using AMAZONBackend.Context;
using AMAZONBackend.DTO;
namespace AMAZONBackend.Clientes.Amazon.Repository
{
public class AmazonRepository : IAmazonRepository
{
private readonly DapperContext _context;
public AmazonRepository(DapperContext context)
{
_context = context;
}
public async Task<List<I2096Header>> AmazonPendingClasificationInvoiceGet()
{
using var connection = _context.CreateConnection();
var sql = "SELECT id FROM [Clientes.Amazon.Invoice.Header] WHERE Estatus in (0,1)";
// var sql = "SELECT DISTINCT(IdHeader) as id FROM[Clientes.Amazon.Invoice.Detail] WHERE(Estatus = 0 and Autorizado = 1) or(Estatus = 1 and Autorizado = 1) ORDER BY 1";
var rows = connection.Query<I2096ListaIDs>(sql);
connection.Close();
List<I2096Header> data = new List<I2096Header>();
foreach (var row in rows)
{
var query = "SELECT a.*, b.Name FROM [Clientes.Amazon.Invoice.Header] a JOIN[Clientes.Amazon.Invoice.ShipFromAddress] b on a.id = b.IdHeader WHERE a.Id =@Id and b.AddressType = 'SHIPPER';" +
"SELECT * FROM [Clientes.Amazon.Invoice.Detail] WHERE IdHeader = @Id";
using (var connection2 = _context.CreateConnection())
using (var multi = await connection2.QueryMultipleAsync(query, new
{
id = row.id
}))
{
var result = await multi.ReadSingleOrDefaultAsync<I2096Header>();
if (result != null)
{
result.Detail = (await multi.ReadAsync<I2096Detail>()).ToList();
data.Add(result);
}
}
}
return data;
}
public async Task<List<I2096Header>> InvoicePendingFromAmazonGet()
{
using var connection = _context.CreateConnection();
var sql = "SELECT id FROM [Clientes.Amazon.Invoice.Header] WHERE Estatus=-1 ORDER BY id";
// var sql = "SELECT DISTINCT(IdHeader) as id FROM[Clientes.Amazon.Invoice.Detail] WHERE(Estatus = 0 and Autorizado = 1) or(Estatus = 1 and Autorizado = 1) ORDER BY 1";
var rows = connection.Query<I2096ListaIDs>(sql);
connection.Close();
List<I2096Header> data = new List<I2096Header>();
foreach (var row in rows)
{
var query = "SELECT a.*, b.Name FROM [Clientes.Amazon.Invoice.Header] a JOIN[Clientes.Amazon.Invoice.ShipFromAddress] b on a.id = b.IdHeader WHERE a.Id =@Id and b.AddressType = 'SHIPPER' ORDER BY a.id;" +
"SELECT * FROM [Clientes.Amazon.Invoice.Detail] WHERE IdHeader = @Id";
using (var connection2 = _context.CreateConnection())
using (var multi = await connection2.QueryMultipleAsync(query, new
{
id = row.id
}))
{
var result = await multi.ReadSingleOrDefaultAsync<I2096Header>();
if (result != null)
{
result.Detail = (await multi.ReadAsync<I2096Detail>()).ToList();
data.Add(result);
}
}
}
return data;
}
public async Task<List<I2096Header>> AmazonFinishedClasificationInvoiceGet()
{
using var connection = _context.CreateConnection();
var sql = "SELECT id FROM [Clientes.Amazon.Invoice.Header] WHERE Estatus>=2";
var rows = connection.Query<I2096ListaIDs>(sql);
connection.Close();
List<I2096Header> data = new List<I2096Header>();
foreach (var row in rows)
{
var query = "SELECT * FROM [Clientes.Amazon.Invoice.Header] WHERE Id = @Id;" +
"SELECT * FROM [Clientes.Amazon.Invoice.Detail] WHERE IdHeader = @Id";
using (var connection2 = _context.CreateConnection())
using (var multi = await connection2.QueryMultipleAsync(query, new
{
id = row.id
}))
{
var result = await multi.ReadSingleOrDefaultAsync<I2096Header>();
if (result != null)
{
result.Detail = (await multi.ReadAsync<I2096Detail>()).ToList();
data.Add(result);
}
}
}
return data;
}
public async Task<List<I2096Header>> AmazonPendingTraficInvoiceGet()
{
using var connection = _context.CreateConnection();
var sql = "SELECT id FROM [Clientes.Amazon.Invoice.Header] WHERE Estatus=3";
var rows = connection.Query<I2096ListaIDs>(sql);
connection.Close();
List<I2096Header> data = new List<I2096Header>();
foreach (var row in rows)
{
var query = "SELECT * FROM [Clientes.Amazon.Invoice.Header] WHERE Id = @Id;" +
"SELECT * FROM [Clientes.Amazon.Invoice.Detail] WHERE IdHeader = @Id";
using (var connection2 = _context.CreateConnection())
using (var multi = await connection2.QueryMultipleAsync(query, new
{
id = row.id
}))
{
var result = await multi.ReadSingleOrDefaultAsync<I2096Header>();
if (result != null)
{
result.Detail = (await multi.ReadAsync<I2096Detail>()).ToList();
data.Add(result);
}
}
}
return data;
}
public async Task<List<I2096Header>> AmazonLinkInvoice2TrafficGet()
{
using var connection = _context.CreateConnection();
var sql = "SELECT id FROM [Clientes.Amazon.Invoice.Header] WHERE Estatus=4";
var rows = connection.Query<I2096ListaIDs>(sql);
connection.Close();
List<I2096Header> data = new List<I2096Header>();
foreach (var row in rows)
{
var query = "SELECT * FROM [Clientes.Amazon.Invoice.Header] WHERE Id = @Id;" +
"SELECT * FROM [Clientes.Amazon.Invoice.Detail] WHERE IdHeader = @Id";
using (var connection2 = _context.CreateConnection())
using (var multi = await connection2.QueryMultipleAsync(query, new
{
id = row.id
}))
{
var result = await multi.ReadSingleOrDefaultAsync<I2096Header>();
if (result != null)
{
result.Detail = (await multi.ReadAsync<I2096Detail>()).ToList();
data.Add(result);
}
}
}
return data;
}
public async Task<I2096Detail> SetFraccionDescripcion(DTO2096FraccionDescripcion data)
{
var query = "[Clientes.Amazon.Invoice.Detail.FraccionDescripcion.Set]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I2096Detail>(query, new
{
@data.Id,
@data.Fraccion,
@data.CumplimientoNormativo,
@data.Comentarios,
@data.DescripcionGEMCO
},
commandType: CommandType.StoredProcedure);
return entrada.FirstOrDefault(new I2096Detail());
}
public async Task<I2096Detail> FraccionSet(DTO2096Fraccion data)
{
var query = "[Clientes.Amazon.Invoice.Detail.Fraccion.Set]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I2096Detail>(query, new
{
@data.Id,
@data.Fraccion,
@data.ConfirmaFraccion
},
commandType: CommandType.StoredProcedure);
return entrada.FirstOrDefault(new I2096Detail());
}
public async Task<I2096Detail> DescripcionSet(DTO2096Descripcion data)
{
var query = "[Clientes.Amazon.Invoice.Detail.Descripcion.Set]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I2096Detail>(query, new
{
@data.Id,
@data.Descripcion,
@data.ConfirmaDescripcion
},
commandType: CommandType.StoredProcedure);
return entrada.FirstOrDefault(new I2096Detail());
}
/* public async Task<I2096Detail> ItemAutorizadoSet(DTO2096ItemAutorizado data)
{
var query = "[Clientes.Amazon.Invoice.Detail.Autorizado.Set]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I2096Detail>(query, new
{
@data.Id,
@data.Autorizado,
@data.RequerimientoNormativo,
@data.Comentarios
},
commandType: CommandType.StoredProcedure);
return entrada.FirstOrDefault(new I2096Detail());
} */
public async Task<I2096Detail> AutorizadoItemFactura(DTO2096FraccionDescripcion data)
{
var query = "[Clientes.Amazon.Invoice.Detail.Autorizado.Set]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I2096Detail>(query, new
{
@data.Id,
@data.Fraccion,
@data.CumplimientoNormativo,
@data.Comentarios,
@data.DescripcionGEMCO
},
commandType: CommandType.StoredProcedure);
return entrada.FirstOrDefault(new I2096Detail());
}
public async Task<IEnumerable<DTO2096Fraccion>> GetFraccionesPendientesValidar()
{
var query = "[Clientes.Amazon.Invoice.Detail.Fracciones.Iniciales.Get]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<DTO2096Fraccion>(query, new { }, commandType: CommandType.StoredProcedure);
return entrada;
}
public async Task<Boolean> SetFraccionPendienteValidar(int id, Boolean valor)
{
var query = "[Clientes.Amazon.Invoice.Detail.Fracciones.Iniciales.Set]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<DTO2096Fraccion>(query, new
{
@id,
@valor
}, commandType: CommandType.StoredProcedure);
return true;
}
public async Task<Boolean> TerminaClasificarFactura(int id)
{
var query = "[Clientes.Amazon.Invoice.Clasification.Finish]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<DTO2096Fraccion>(query, new
{
@id
}, commandType: CommandType.StoredProcedure);
return true;
}
public async Task<Boolean> EnviaEsperaRespuestaAmazon(int id)
{
var query = "[Clientes.Amazon.Invoice.Clasification.Send2Waiting]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<DTO2096Fraccion>(query, new
{
@id
}, commandType: CommandType.StoredProcedure);
return true;
}
public async Task<IEnumerable<I2096NoPartes>> NoPartesGet(string Search)
{
var query = "[Clientes.Amazon.Invoice.NoPartes.Get]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I2096NoPartes>(query, new { @Search }, commandType: CommandType.StoredProcedure);
return entrada.ToList();
}
public async Task<IEnumerable<I2096PaisClaves>> PaisClavesGet()
{
var query = "[Catalogo.PaisClaves.Get]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I2096PaisClaves>(query, new { }, commandType: CommandType.StoredProcedure);
return entrada.ToList();
}
public async Task<DashboardTotal> DashboardInvoicesGet(Int16 Mode)
{
var query = "[Dashboard.Clasificacion.Amazon.Invoices.Finished]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<DashboardTotal>(query, new { @Mode }, commandType: CommandType.StoredProcedure);
return entrada.First();
}
public async Task<DTORespuesta> SePuedeTerminardeClasificarFactura(int id)
{
var query = "SELECT dbo.IsAmazonInvoiceClasificationReady(@id)"; // This is a function, not a stored procedure
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<Boolean>(query, new { @id }, commandType: CommandType.Text);
DTORespuesta answer = new DTORespuesta();
answer.code = 200;
answer.respuesta = entrada.First() == true ? "Factura lista" : "Factura incompleta";
return answer;
}
public async Task<DTORespuesta> SePuedeTerminardeClasificarFacturaEsperandoRespuesta(int id)
{
var query = "SELECT dbo.IsAmazonInvoiceClasificationReady4AmazonAnswer(@id)"; // This is a function, not a stored procedure
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<Boolean>(query, new { @id }, commandType: CommandType.Text);
DTORespuesta answer = new DTORespuesta();
answer.code = 200;
answer.respuesta = entrada.First() == true ? "Factura lista" : "Factura incompleta";
return answer;
}
public async Task<DTO2096SightLine> SightLineSET(DTO2096SightLine data)
{
var query = "[Clientes.Amazon.Invoice.Detail.SightLine.Set]"; // This is a function, not a stored procedure
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<DTO2096SightLine>(query, new { @data.Id, @data.SightLine, @data.ComentariosSightLine }, commandType: CommandType.StoredProcedure);
return entrada.FirstOrDefault(new DTO2096SightLine());
}
public async Task<DTORespuesta> SePuedeTerminarXTraficoFactura(int id)
{
var query = "SELECT dbo.IsAmazonInvoiceTraficReady(@id)"; // This is a function, not a stored procedure
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<Boolean>(query, new { @id }, commandType: CommandType.Text);
DTORespuesta answer = new DTORespuesta();
answer.code = 200;
answer.respuesta = entrada.First() == true ? "Factura lista" : "Factura incompleta";
return answer;
}
public async Task<Boolean> TerminaXTraficoFactura(int id)
{
var query = "[Clientes.Amazon.Invoice.Traffic.Finish]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<DTO2096Fraccion>(query, new
{
@id
}, commandType: CommandType.StoredProcedure);
return true;
}
public async Task<List<I2096Header>> AmazonInvoiceGet(int id)
{
using var connection = _context.CreateConnection();
List<I2096Header> data = new List<I2096Header>();
var query = "SELECT * FROM [Clientes.Amazon.Invoice.Header] WHERE Id =@Id;" +
"SELECT * FROM [Clientes.Amazon.Invoice.Detail] WHERE IdHeader = @Id";
using (var connection2 = _context.CreateConnection())
using (var multi = await connection2.QueryMultipleAsync(query, new { @id }))
{
var result = await multi.ReadSingleOrDefaultAsync<I2096Header>();
if (result != null)
{
result.Detail = (await multi.ReadAsync<I2096Detail>()).ToList();
data.Add(result);
}
}
return data;
}
public async Task<IEnumerable<I2096ShipFromAddress>> AmazonShippingInfo(int id)
{
var query = "[Clientes.Amazon.Invoice.ShipFromAddress.Get]";
using var connection = _context.CreateConnection();
var result = await connection.QueryAsync<I2096ShipFromAddress>(query, new
{
@id
}, commandType: CommandType.StoredProcedure);
return result;
}
public async Task<I2096Detail> CheckDetail(int id)
{
var query = "[Clientes.Amazon.Invoice.Detail.Check]";
using var connection = _context.CreateConnection();
var result = await connection.QueryAsync<I2096Detail>(query, new
{
@id
}, commandType: CommandType.StoredProcedure);
return result.FirstOrDefault(new I2096Detail());
}
public async Task<Boolean> AssignInvoice(int IdUsuario, int IdFactura)
{
var query = "[Clientes.Amazon.Invoice.Assign]";
using var connection = _context.CreateConnection();
var result = await connection.QueryAsync<I2096Header>(query, new
{
@IdUsuario,
@IdFactura
}, commandType: CommandType.StoredProcedure);
return true;
}
}
}

@ -0,0 +1,18 @@
using System.Data;
using System.Data.SqlClient;
namespace AMAZONBackend.Context
{
public class DapperContext
{
private readonly IConfiguration _configuration;
private readonly string _connectionString;
public DapperContext(IConfiguration configuration)
{
_configuration = configuration;
_connectionString = _configuration.GetConnectionString("SqlConnection");
}
public IDbConnection CreateConnection()
=> new SqlConnection(_connectionString);
}
}

@ -0,0 +1,15 @@
using AMAZONBackend.DTO.Clientes.CasaCuervo;
using AMAZONBackend.Models.Clientes.CasaCuervo;
namespace AMAZONBackend.Contracts.Clientes.CasaCuervo
{
public interface ICasaCuervoRepository
{
public Task<Boolean> Append(List<I325Pedidos> data);
public Task<Boolean> UpdateInfoFromCorresponsal(List<DTO325ComplementaPedido> data);
public Task<IEnumerable<I325Pedidos>> getAll(string Inicio, string Fin, string Aduana);
public Task<I325Pedidos> GetById(int Id);
public Task<I325Pedidos> UpdateInfoFromWeb(DTO325UpdateFromWeb data);
public Task<IEnumerable<DTO325AduanasPedidos>> getAduanas(int Usuario, int TipoUsuario);
}
}

@ -0,0 +1,9 @@
using AMAZONBackend.Models;
namespace AMAZONBackend.Contracts
{
public interface IMenuRepository
{
public Task<IEnumerable<Menu>> GetItemsMenu(Usuarios user);
}
}

@ -0,0 +1,20 @@
using AMAZONBackend.DTO;
using AMAZONBackend.DTO.Usuario;
using AMAZONBackend.Models;
namespace AMAZONBackend.Contracts
{
public interface IPerfilesRepository
{
public Task<IEnumerable<Perfiles>> getPerfiles();
public Task<Perfiles> PerfilGetById(int id);
public Task<IEnumerable<Menu>> getMenu();
public Task<IEnumerable<PerfilesMenu>> getPerfilMenuById(int id);
public Task<IEnumerable<PerfilesMenu>> getAllPerfilesMenu();
public Task<IEnumerable<DTOPerfilCreate>> createPerfil(DTOPerfilCreate data);
public Task<IEnumerable<Menu>> createItemMenu(Menu data);
public Task<IEnumerable<DTOItemMenuPerfil>> asignaItemMenuPerfil(DTOItemMenuPerfil data);
public Task<IEnumerable<Transportistas>> getAllTransportistas(int id);
public Task<IEnumerable<Proveedores>> getAllProveedores(int id);
}
}

@ -0,0 +1,21 @@
using AMAZONBackend.DTO;
using AMAZONBackend.DTO.Usuario;
using AMAZONBackend.Models;
namespace AMAZONBackend.Contracts
{
public interface IUsuariosRepository
{
public Task<IEnumerable<DTOUsuariosShort>> getAllUsuariosShort();
public Task<IEnumerable<Usuarios>> getAllUsuarios();
public Task<Usuarios> GetUsuario(DTOLogin user);
public Task<Usuarios> searchUsuario(DTOLogin user);
public Task<Usuarios> GetUsuarioById(int id);
public Task<Usuarios> createUsuario(Usuarios user);
public Task<DTOLogin> resetPassword(DTOLogin user);
public Task<IEnumerable<DTOClonarUsuario>> clonarUsuario(DTOClonarUsuario user);
public Task<IEnumerable<CatRoles>> CatalogoRolesGET();
public Task<IEnumerable<DTORolesAsignados>> RolesAsignadosGET(int id);
public Task<IEnumerable<DTOUsuariosPerfilParecido>> GETPerfilesParecidos(string Perfil);
}
}

@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Identity;
using AMAZONBackend.Models.Utils;
namespace AMAZONBackend.Contracts.Utils
{
public interface IFileManagerRepository
{
public Task<FileManager> FileManager(FileManager data);
public Task<FileManager> getFileByProcess(long id, int Proceso);
public Task<List<FileManager>> getAllFilesByProcess(long Tags, int Proceso);
public Task<FileManager> getFileById(long id);
public Task deleteFileByProcess(long id, int Proceso);
}
}

@ -0,0 +1,9 @@
using AMAZONBackend.Models.Utils;
namespace AMAZONBackend.Contracts.Utils
{
public interface IFilePaths4ProcessRepository
{
public Task<FilePaths4Process> getPaths4ProcessById(long id);
}
}

@ -0,0 +1,9 @@

namespace AMAZONBackend.Contracts.Utils
{
public interface IPDFGenerator
{
public Task<byte[]> GeneratePdfFromString(string htmlContent);
}
}

@ -0,0 +1,7 @@
namespace AMAZONBackend.Contracts.Utils
{
public interface IValidaFraccion
{
public Boolean ValidaFraccion(string Fraccion);
}
}

@ -0,0 +1,139 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using AMAZONBackend.Contracts;
using AMAZONBackend.DTO;
using AMAZONBackend.Models;
namespace AMAZONBackend.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
public IConfiguration _config;
private readonly IUsuariosRepository _usuariosRepo;
private readonly IPerfilesRepository _perfilesRepo;
private readonly IMenuRepository _menuRepo;
public AuthController(IConfiguration config, IUsuariosRepository usuariosRepo, IMenuRepository menuRepo, IPerfilesRepository perfilesRepo)
{
_config = config;
_usuariosRepo = usuariosRepo;
_perfilesRepo = perfilesRepo;
_menuRepo = menuRepo;
}
[HttpPost]
public async Task<IActionResult> Post(DTOLogin _userData)
{
if (_userData.Contrasena == _config.GetValue<string>("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<Claim>();
var ProfileData = await _perfilesRepo.PerfilGetById(user.Id);
claims.Add(new Claim(JwtRegisteredClaimNames.Sub, _config["Jwt:Subject"])); //aqui truena
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("Departamento", (user.sDept ?? user.sDept ?? "No asignado")));
claims.Add(new Claim("UserType", (user != null) ? user.TipoUsuario.ToString() : "0"));
claims.Add(new Claim("Perfil", ProfileData.Perfil));
foreach (Menu 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(5),
signingCredentials: signIn);
var _token = new JwtSecurityTokenHandler().WriteToken(token);
return new OkObjectResult(new { menu = menu, token = _token });
}
else
{
return BadRequest("Invalid credentials");
}
}
else
{
return BadRequest();
}
}
[HttpGet]
[Route("GetPermissions")]
public async Task<IActionResult> GetPermissions(string Usuario, string Contrasena)
{
DTOLogin _userData = new DTOLogin();
_userData.Usuario = Usuario;
_userData.Contrasena = Contrasena;
if (_userData.Contrasena == _config.GetValue<string>("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<Claim>();
/* 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("Departamento", (user.sDept ?? user.sDept ?? "No asignado")));
claims.Add(new Claim("UserType", (user != null) ? user.TipoUsuario.ToString() : "0")); */
foreach (Menu 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(5),
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");
}
}
}

@ -0,0 +1,357 @@
using System.Net;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using AMAZONBackend.Clientes.Amazon.Contracts;
using AMAZONBackend.Clientes.Amazon.DTO;
using AMAZONBackend.Clientes.Amazon.Models;
using AMAZONBackend.Contracts.Utils;
using AMAZONBackend.DTO;
using AMAZONBackend.Services.ValidarFraccion;
namespace AMAZONBackend.Controllers.Clientes.Amazon
{
[ApiController]
[Route("api/[controller]")]
public class AmazonInvoiceController : ControllerBase
{
public IConfiguration _config;
private readonly IAmazonRepository _Repo;
private readonly String _connectionString;
private readonly IPDFGenerator _RepoPDFGenerator;
public AmazonInvoiceController(IConfiguration config, IAmazonRepository Repo, IPDFGenerator RepoPDFGenerator)
{
_config = config;
_Repo = Repo;
_RepoPDFGenerator = RepoPDFGenerator;
_connectionString = _config.GetConnectionString("SqlConnection");
}
/*************************************** Procesos Iniciales *************************************/
[HttpGet]
[Route("C2096ValidaFraccion")]
public IActionResult C2096ValidaFraccion(string Fraccion)
{
if (Fraccion.Length != 10)
{
return Ok(new { Respuesta = "No" });
}
SrvValidaFraccion SrvValFraccion = new SrvValidaFraccion();
Boolean resultado = SrvValFraccion.ValidaFraccion(Fraccion);
if (resultado) return Ok(new { Respuesta = "Si" });
return Ok(new { Respuesta = "No" });
}
[HttpGet]
[Route("ValidaFraccionesIniciales")]
public async Task<Boolean> ValidaFraccionesIniciales()
{
var Fracciones = await _Repo.GetFraccionesPendientesValidar();
SrvValidaFraccion SrvValFraccion = new SrvValidaFraccion();
foreach (DTO2096Fraccion row in Fracciones)
{
await _Repo.SetFraccionPendienteValidar(row.Id, SrvValFraccion.ValidaFraccion(row.Fraccion.Replace(".", "")));
}
return true;
}
[HttpPut]
[Route("AsignaFactura")]
public async Task<Boolean> AsignaFactura(int IdUsuario, int IdFactura)
{
return await _Repo.AssignInvoice(IdUsuario, IdFactura);
}
/*************************************** Procesos Iniciales *************************************/
/*************************************** Pending Clasification *************************************/
[HttpGet]
[Route("AmazonPendingClasificationInvoiceGet")]
public async Task<List<I2096Header>> AmazonPendingClasificationInvoice()
{
var entrada = await _Repo.AmazonPendingClasificationInvoiceGet();
return entrada;
}
[HttpGet]
[Route("InvoicePendingFromAmazonGet")]
public async Task<List<I2096Header>> InvoicePendingFromAmazonGet()
{
var entrada = await _Repo.InvoicePendingFromAmazonGet();
return entrada;
}
[HttpPut]
[Route("C2096FraccionDescripcionSET")]
public async Task<I2096Detail> C2096SetFraccionDescripcion(DTO2096FraccionDescripcion data)
{
var entrada = await _Repo.SetFraccionDescripcion(data);
return entrada;
}
[HttpPost]
[Route("C2096FraccionSet")]
public async Task<I2096Detail> C2096SetFraccion(DTO2096Fraccion data)
{
var entrada = await _Repo.FraccionSet(data);
return entrada;
}
[HttpPost]
[Route("C2096DescripcionSet")]
public async Task<I2096Detail> C2096SetDescripcion(DTO2096Descripcion data)
{
var entrada = await _Repo.DescripcionSet(data);
return entrada;
}
[HttpPut]
[Route("C2096CheckDetail")]
public async Task<I2096Detail> C2096CheckDetail(int id)
{
return await _Repo.CheckDetail(id);
}
[HttpGet]
[Route("SePuedeTerminardeClasificarFactura")]
public async Task<DTORespuesta> SePuedeTerminardeClasificarFactura(int id)
{
return await _Repo.SePuedeTerminardeClasificarFactura(id);
}
[HttpGet]
[Route("SePuedeTerminardeClasificarFacturaEsperandoRespuesta")]
public async Task<DTORespuesta> SePuedeTerminardeClasificarFacturaEsperandoRespuesta(int id)
{
return await _Repo.SePuedeTerminardeClasificarFacturaEsperandoRespuesta(id);
}
[HttpGet]
[Route("EnviaEsperaRespuestaAmazon")]
public async Task<Boolean> EnviaEsperaRespuestaAmazon(int id)
{
return await _Repo.EnviaEsperaRespuestaAmazon(id);
}
/*************************************** End Pending Clasification *************************************/
/*************************************** Finished Clasification *************************************/
[HttpGet]
[Route("AmazonFinishedClasificationInvoiceGet")]
public async Task<List<I2096Header>> AmazonFinishedClasificationInvoiceGet()
{
var entrada = await _Repo.AmazonFinishedClasificationInvoiceGet();
return entrada;
}
[HttpPut]
[Route("C2096AutorizaItemFactura")]
public async Task<I2096Detail> C2096AutorizaItemFactura(DTO2096FraccionDescripcion data)
{
return await _Repo.AutorizadoItemFactura(data);
}
[HttpGet]
[Route("TerminaClasificarFactura")]
public async Task<Boolean> TerminaClasificarFactura(int id)
{
return await _Repo.TerminaClasificarFactura(id);
}
/*************************************** End Finished Clasification *************************************/
/****************************************** Pending Traffic ******************************************/
[HttpGet]
[Route("AmazonPendingTraficInvoiceGet")]
public async Task<List<I2096Header>> AmazonPendingTraficInvoiceGet()
{
var entrada = await _Repo.AmazonPendingTraficInvoiceGet();
return entrada;
}
/**************************************** End Pending Traffic *****************************************/
/****************************************** Linking Traffic ******************************************/
[HttpGet]
[Route("AmazonLinkInvoice2TrafficGet")]
public async Task<List<I2096Header>> AmazonLinkInvoice2TrafficGet()
{
var entrada = await _Repo.AmazonLinkInvoice2TrafficGet();
return entrada;
}
[HttpPut]
[Route("AmazonSightLineSET")]
public async Task<DTO2096SightLine> AmazonSightLineSET(DTO2096SightLine data)
{
return await _Repo.SightLineSET(data);
}
[HttpGet]
[Route("SePuedeTerminarXTraficoFactura")]
public async Task<DTORespuesta> SePuedeTerminarXTraficoFactura(int id)
{
return await _Repo.SePuedeTerminarXTraficoFactura(id);
}
[HttpGet]
[Route("TerminaXTraficoFactura")]
public async Task<Boolean> TerminaXTraficoFactura(int id)
{
return await _Repo.TerminaXTraficoFactura(id);
}
/***************************************End Linking Traffic ******************************************/
/* [HttpPost]
[Route("C2096ItemAutorizado")]
public async Task<I2096Detail> C2096ItemAutorizado(DTO2096ItemAutorizado data)
{
return await _Repo.ItemAutorizadoSet(data);
} */
/*************************************** Procesos Auxiliares ******************************************/
[HttpGet]
[Route("NoPartesGet")]
public async Task<IEnumerable<I2096NoPartes>> NoPartesGet(string Search)
{
return await _Repo.NoPartesGet(Search);
}
[HttpGet]
[Route("PaisClavesGet")]
public async Task<IEnumerable<I2096PaisClaves>> PaisClavesGet()
{
return await _Repo.PaisClavesGet();
}
[Route("GetNoPartesAmazon2SIR")]
[HttpGet, DisableRequestSizeLimit]
public async Task<IActionResult> GetNoPartesAmazon2SIR(int id)
{
byte[] emptyFile = System.IO.File.ReadAllBytes("c:\\downs\\empty.png");
MemoryStream emptyms = new MemoryStream(emptyFile);
try
{
using (var client = GetHttpClient("http://localhost:9090/api/getNoPartesAmazon?id=" + id))
{
HttpResponseMessage response = await client.GetAsync("");
if (response.StatusCode == HttpStatusCode.OK)
{
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
MemoryStream ms = new MemoryStream(pdfBytes);
var resp = HttpContext.Response;
resp.ContentType = "application/vnd.ms-excel";
resp.Headers.Add("Content-Disposition", "attachment; filename=PlantillaPartesSIR.xlsx");
return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
return new FileStreamResult(emptyms, "image/png");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new FileStreamResult(emptyms, "image/png");
}
}
[Route("GetArchivoExcepcionesAmazon")]
[HttpGet, DisableRequestSizeLimit]
public async Task<IActionResult> GetArchivoExcepcionesAmazon(int id)
{
byte[] emptyFile = System.IO.File.ReadAllBytes("c:\\downs\\empty.png");
MemoryStream emptyms = new MemoryStream(emptyFile);
try
{
using (var client = GetHttpClient("http://localhost:9090/api/getExceptionsFile4Amazon?id=" + id))
{
HttpResponseMessage response = await client.GetAsync("");
if (response.StatusCode == HttpStatusCode.OK)
{
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
MemoryStream ms = new MemoryStream(pdfBytes);
var resp = HttpContext.Response;
resp.ContentType = "application/vnd.ms-excel";
resp.Headers.Add("Content-Disposition", "attachment; filename=ExceptionsFile.xlsx");
return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
return new FileStreamResult(emptyms, "image/png");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new FileStreamResult(emptyms, "image/png");
}
}
[HttpGet]
[Route("AmazonInvoiceGET")]
public async Task<List<I2096Header>> AmazonInvoiceGET(int id)
{
return await _Repo.AmazonInvoiceGet(id);
}
[HttpGet]
[Route("AmazonShippingInfoGET")]
public async Task<IEnumerable<I2096ShipFromAddress>> AmazonShippingInfoGET(int id)
{
return await _Repo.AmazonShippingInfo(id);
}
[HttpGet]
[Route("PDFAmazonInvoiceGET")]
public async Task<IActionResult> PDFAmazonInvoiceGET(int id)
{
byte[] emptyFile = System.IO.File.ReadAllBytes("c:\\downs\\empty.png");
MemoryStream emptyms = new MemoryStream(emptyFile);
try
{
using (var client = GetHttpClient("http://localhost:9091/getAmazonInvoicePDF?id=" + id))
{
HttpResponseMessage response = await client.GetAsync("");
if (response.StatusCode == HttpStatusCode.OK)
{
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
MemoryStream ms = new MemoryStream(pdfBytes);
var resp = HttpContext.Response;
resp.ContentType = "application/pdf";
resp.Headers.Add("Content-Disposition", "attachment; filename=AmazonInvoice.pdf");
return new FileStreamResult(ms, "application/pdf");
}
return new FileStreamResult(emptyms, "image/png");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Response.ContentType = "application/pdf";
Response.Headers.Add("content-disposition", $"attachment; filename=AmazonInvoice.pdf");
return new FileStreamResult(emptyms, "image/png");
}
}
private static HttpClient GetHttpClient(string url)
{
var client = new HttpClient { BaseAddress = new Uri(url) };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/csv"));
return client;
}
/*************************************** End Procesos Auxiliares ***************************************/
/******************************************** Dashboard ********************************************/
[HttpGet]
[Route("DashboardInvoices")]
public async Task<DashboardTotal> DashboardInvoices(Int16 Mode)
{
return await _Repo.DashboardInvoicesGet(Mode);
}
/****************************************** End Dashboard *******************************************/
}
}

@ -0,0 +1,202 @@
using Microsoft.AspNetCore.Mvc;
using AMAZONBackend.Contracts;
using AMAZONBackend.Contracts.Clientes.CasaCuervo;
using AMAZONBackend.Contracts.Utils;
using AMAZONBackend.DTO;
using AMAZONBackend.Models.Utils;
using AMAZONBackend.Services.Clientes.SCasaCuervo;
namespace AMAZONBackend.Controllers
{
// [Authorize]
[Route("api/[controller]")]
// [ApiController]
public class FileManagerController : Controller
{
private readonly IFileManagerRepository _Repo;
private readonly IUsuariosRepository _RepoUsuarios;
private readonly ICasaCuervoRepository _RepoCasaCuervo;
private readonly IFilePaths4ProcessRepository _RepoRelativePath;
private readonly IConfiguration _config;
private readonly string RootPathCorresponsales;
public FileManagerController(IFileManagerRepository Repo,
IFilePaths4ProcessRepository RepoRelativePath,
IConfiguration config,
IUsuariosRepository RepoUsuarios,
ICasaCuervoRepository RepoCasaCuervo)
{
_config = config;
_Repo = Repo;
_RepoUsuarios = RepoUsuarios;
_RepoCasaCuervo = RepoCasaCuervo;
_RepoRelativePath = RepoRelativePath;
RootPathCorresponsales = _config.GetValue<string>("AllFiles");
}
[Route("GetFileInfoByProcess")]
[HttpGet]
public async Task<FileManager> GetFileInfoByProcess([FromQuery] int id, int Proceso)
{
FileManager data = new FileManager();
data = await _Repo.getFileByProcess(id, Proceso);
return data;
}
[Route("GetFileInfoById")]
[HttpGet]
public async Task<FileManager> GetFileInfoByProcess([FromQuery] int id)
{
FileManager data = new FileManager();
data = await _Repo.getFileById(id);
return data;
}
[Route("AppendFileByProcess")]
[HttpPost]
public async Task<FileManager> 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;
}
// El aifuiente procaso se tiene que validar de todo a todo, ya que sera facilitado el acceso a usuarios externos a GEMCO: Clientes, Corresponsales, etc
[Route("AppendFileUpdatesCasaCuervo")]
[HttpPost]
public async Task<IActionResult> AppendFileUpdatesCasaCuervo(IFormFile file, string Usuario, string Contrasenia)
{
int Proceso = 6;
string Tags = "-1";
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;
DTOLogin authUser = new DTOLogin();
authUser.Usuario = Usuario;
authUser.Contrasena = Contrasenia;
var ExternalUser = await _RepoUsuarios.GetUsuario(authUser);
FileManager data = new FileManager();
data.id = 0;
data.IdUsuario = ExternalUser.Id;
data.NombreArchivo = newFileName;
data.Proceso = Proceso;
data.FechaRegistro = "";
data.Tags = Tags;
data.Activo = 1;
long fileLength = 0;
string filePath = "";
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)
{
SCasaCuervo proc = new SCasaCuervo(_RepoCasaCuervo, filePath);
var result = await proc.UpdateInfoFromCorresponsal();
if (result) return new OkObjectResult(new { respuesta = "El archivo se agrego exitosamente" });
else return new OkObjectResult(new { respuesta = "Ocurrio un error, el archivo no se guardo, verifique que el formato de fecha sea MM/dd/yyyy" });
}
return new OkObjectResult(new { respuesta = "Ocurrio un error el archivo no se guardo" });
}
[Route("getFile")]
[HttpGet, DisableRequestSizeLimit]
public async Task<IActionResult> 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<IActionResult> 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" });
}
}
}

@ -0,0 +1,175 @@
using Microsoft.AspNetCore.Mvc;
using AMAZONBackend.Contracts;
using AMAZONBackend.DTO;
using AMAZONBackend.DTO.Usuario;
using AMAZONBackend.Models;
using AMAZONBackend.Services;
namespace AMAZONBackend.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsuariosController : ControllerBase
{
private readonly IUsuariosRepository _usuariosRepo;
private readonly IConfiguration _config;
public UsuariosController(IUsuariosRepository usuariosRepo, IConfiguration config) { _usuariosRepo = usuariosRepo; _config = config; }
[Route("getUsuarioById")]
[HttpGet]
public async Task<IActionResult> 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("getAllUsuarios")]
[HttpGet]
public async Task<IActionResult> getAllUsuarios()
{
try
{
var usuarios = await _usuariosRepo.getAllUsuarios();
return Ok(usuarios);
}
catch (Exception ex) { return StatusCode(500, ex.Message); }
}
[Route("getAllUsuariosShort")]
[HttpGet]
public async Task<IActionResult> getAllUsuariosShort()
{
try
{
var usuarios = await _usuariosRepo.getAllUsuariosShort();
return Ok(usuarios);
}
catch (Exception ex) { return StatusCode(500, ex.Message); }
}
[Route("Auth")]
[HttpPost]
public async Task<IActionResult> Auth(DTOLogin user)
{
try
{
var usuarios = await _usuariosRepo.GetUsuario(user);
return Ok(usuarios);
}
catch (Exception ex) { return StatusCode(500, ex.Message); }
}
[Route("resetPassword")]
[HttpPost]
public async Task<IActionResult> resetPassword(DTOLogin user)
{
try
{
var result = await _usuariosRepo.resetPassword(user);
if (result == null)
{
return StatusCode(400, "Cuenta de usuario no existe");
}
return Ok(result);
}
catch (Exception ex)
{
return StatusCode(500, ex);
}
}
[Route("searchUsuario")]
[HttpPost]
public async Task<IActionResult> 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("createUser")]
[HttpPost]
public async Task<IActionResult> POST(Usuarios user)
{
try
{
var usuario = await _usuariosRepo.createUsuario(user);
if (user.Id == 0)
{
Utilerias email = new Utilerias(_config);
Boolean sendOk = email.SendEmail("", usuario);
}
return Ok(usuario);
}
catch (Exception ex) { return StatusCode(500, ex.Message); }
}
[Route("clonarUsuario")]
[HttpPost]
public async Task<IActionResult> POST(DTOClonarUsuario user)
{
try
{
var usuarios = await _usuariosRepo.clonarUsuario(user);
return Ok(usuarios);
}
catch (Exception ex) { return StatusCode(500, ex.Message); }
}
[Route("Catalogo/Roles/GET")]
[HttpGet]
public async Task<IActionResult> CatalogoRolesGET()
{
try
{
var Roles = await _usuariosRepo.CatalogoRolesGET();
return Ok(Roles);
}
catch (Exception ex) { return StatusCode(500, ex.Message); }
}
[Route("Catalogo/Roles/AsignadosGET")]
[HttpGet]
public async Task<IActionResult> RolesAsignadosGET(int id)
{
try
{
var Roles = await _usuariosRepo.RolesAsignadosGET(id);
return Ok(Roles);
}
catch (Exception ex) { return StatusCode(500, ex.Message); }
}
[Route("Catalogo/Usuarios/PerfilesParecidos")]
[HttpGet]
public async Task<IActionResult> GETPerfilesParecidos(string Perfil)
{
try
{
var perfiles = await _usuariosRepo.GETPerfilesParecidos(Perfil);
return Ok(perfiles);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
}
}

@ -0,0 +1,63 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using AMAZONBackend.Contracts.Utils;
using AMAZONBackend.Models.Utils;
using AMAZONBackend.Services.MFileManager;
namespace AMAZONBackend.Controllers.Utils
{
[Authorize]
[ApiController]
[Route("api/Utils/[controller]")]
public class MFileManagerController : ControllerBase
{
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<string>("AllFiles");
}
[HttpGet]
[Route("GetFilesFromLog")]
public async Task<List<FileManager>> 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<IActionResult> 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<List<FileManager>> Append(List<IFormFile> FileList, int Tags, int Proceso, int Usuario)
{
List<string> data = new List<string>();
FilePaths4Process RelativePath = await _RepoRelativePath.getPaths4ProcessById(Proceso);
SvcMFileManager FM = new SvcMFileManager(_config, _Repo, RootPath + RelativePath.Path);
List<string> filePaths = await FM.SaveFile2DiskList(FileList);
var fileData = await FM.SaveFileLog(filePaths, Tags, Proceso, Usuario);
return fileData;
}
}
}

@ -0,0 +1,55 @@
using System.Security.Cryptography;
using System.Text;
namespace AMAZONBackend.Crypto
{
public class CryptDecrypt
{
private readonly static string key = "G3mc0H42hk3y2!0$2*2#n4813dc2h47p";
public static string Encrypt(string text)
{
byte[] iv = new byte[16];
byte[] array;
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
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(key);
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();
}
}
}
}
}
}
}

@ -0,0 +1,8 @@
namespace AMAZONBackend.DTO.Clientes.CasaCuervo
{
public class DTO325AduanasPedidos
{
public string id { set; get; } = string.Empty;
public string value { set; get; } = string.Empty;
}
}

@ -0,0 +1,16 @@
namespace AMAZONBackend.DTO.Clientes.CasaCuervo
{
public class DTO325ComplementaPedido
{
public string Pedido { set; get; } = string.Empty;
public string Factura { set; get; } = string.Empty;
public string UUID { set; get; } = string.Empty;
public string Trafico { set; get; } = string.Empty;
public string Pedimento { set; get; } = string.Empty;
public string Aduana { set; get; } = string.Empty;
public string Patente { set; get; } = string.Empty;
public string Modulacion { set; get; } = string.Empty;
public string? FechaCompromiso { set; get; } = string.Empty;
public string? Comentario { set; get; } = string.Empty;
}
}

@ -0,0 +1,18 @@
namespace AMAZONBackend.DTO.Clientes.CasaCuervo
{
public class DTO325UpdateFromWeb
{
public int id { get; set; } = 0!;
public string ComentarioGEMCO { get; set; } = string.Empty;
public string FechaCompromiso { get; set; } = string.Empty;
public string FechaCruce { get; set; } = string.Empty;
public string Factura { get; set; } = string.Empty;
public string MedidaCaja { get; set; } = string.Empty;
public string Sello1 { get; set; } = string.Empty;
public string Sello2 { get; set; } = string.Empty;
public string UUID { get; set; } = string.Empty;
public string Trafico { get; set; } = string.Empty;
public string Pedimento { get; set; } = string.Empty;
public string Patente { get; set; } = string.Empty;
}
}

@ -0,0 +1,10 @@
namespace AMAZONBackend.DTO
{
public class DTOItemMenuPerfil
{
public int IdPerfil { get; set; } = 0;
public int itemMenu { get; set; } = 0;
public bool asignado { get; set; } = false;
}
}

@ -0,0 +1,8 @@
namespace AMAZONBackend.DTO
{
public class DTOLogin
{
public string Usuario { get; set; } = null!;
public string Contrasena { get; set; } = null!;
}
}

@ -0,0 +1,8 @@
namespace AMAZONBackend.DTO
{
public class DTORespuesta
{
public int code { get; set; } = 0!;
public string respuesta { get; set; } = null!;
}
}

@ -0,0 +1,10 @@
namespace AMAZONBackend.DTO
{
public class DTORolesAsignados
{
public int Id { get; set; } = 0;
public int Usuario { get; set; } = 0;
public int Rol { get; set; } = 0;
public Boolean Activo { get; set; } = false;
}
}

@ -0,0 +1,8 @@
namespace AMAZONBackend.DTO.Usuario
{
public class DTOClonarUsuario
{
public int IDUsuarioOrigen { get; set; } = 0!;
public int IdUsuarioDestino { get; set; } = 0!;
}
}

@ -0,0 +1,8 @@
namespace AMAZONBackend.DTO.Usuario
{
public class DTOPerfilCreate
{
public string Perfil { get; set; } = null!;
public int IdPerfilClonado { get; set; } = 0!;
}
}

@ -0,0 +1,9 @@
namespace AMAZONBackend.DTO.Usuario
{
public class DTOUsuariosPerfilParecido
{
public int IdUsuario { get; set; } = 0;
public string Nombre { get; set; } = null!;
public string Perfil { get; set; } = null!;
}
}

@ -0,0 +1,8 @@
namespace AMAZONBackend.DTO.Usuario
{
public class DTOUsuariosShort
{
public int id { get; set; } = 0!;
public string Usuario { get; set; } = null!;
}
}

@ -0,0 +1,89 @@
using System.Data;
using ExcelDataReader;
namespace AMAZONBackend.Interface
{
public interface IExcelDataReader : IDataReader, IDataRecord, IDisposable
{
//
// Summary:
// Gets the sheet name.
string Name { get; }
//
// Summary:
// Gets the sheet VBA code name.
string CodeName { get; }
//
// Summary:
// Gets the sheet visible state.
string VisibleState { get; }
//
// Summary:
// Gets the sheet header and footer -or- null if none set.
HeaderFooter HeaderFooter { get; }
//
// Summary:
// Gets the list of merged cell ranges.
CellRange[] MergeCells { get; }
//
// Summary:
// Gets the number of results (workbooks).
int ResultsCount { get; }
//
// Summary:
// Gets the number of rows in the current result.
int RowCount { get; }
//
// Summary:
// Gets the height of the current row in points.
double RowHeight { get; }
//
// Summary:
// Seeks to the first result.
void Reset();
//
// Summary:
// Gets the number format for the specified field -or- null if there is no value.
//
// Parameters:
// i:
// The index of the field to find.
//
// Returns:
// The number format string of the specified field.
string GetNumberFormatString(int i);
//
// Summary:
// Gets the number format index for the specified field -or- -1 if there is no value.
//
// Parameters:
// i:
// The index of the field to find.
//
// Returns:
// The number format index of the specified field.
int GetNumberFormatIndex(int i);
//
// Summary:
// Gets the width the specified column.
//
// Parameters:
// i:
// The index of the column to find.
//
// Returns:
// The width of the specified column.
double GetColumnWidth(int i);
}
}

@ -0,0 +1,9 @@
namespace AMAZONBackend.Models
{
public class CatRoles
{
public int Id { set; get; }
public string Rol { set; get; } = null!;
public byte Activo { set; get; }
}
}

@ -0,0 +1,31 @@
namespace AMAZONBackend.Models.Clientes.CasaCuervo
{
public class I325Pedidos
{
public int id { set; get; } = 0;
public string PO { set; get; } = string.Empty;
public string Aduana { set; get; } = string.Empty;
public string Destination { set; get; } = string.Empty;
public string TruckNumber { set; get; } = string.Empty;
public string Forwarder { set; get; } = string.Empty;
public string Carrier { set; get; } = string.Empty;
public string LoadDate { set; get; } = string.Empty;
public string Prioridad { set; get; } = string.Empty;
public string? Estatus { set; get; } = string.Empty;
public string? ComentarioGEMCO { set; get; } = string.Empty;
public string? FechaCompromiso { set; get; } = string.Empty;
public string? FechaCruce { set; get; } = string.Empty;
public string? Factura { set; get; } = string.Empty;
public string? UUID { set; get; } = string.Empty;
public string? Trafico { set; get; } = string.Empty;
public string? Pedimento { set; get; } = string.Empty;
public string? Patente { set; get; } = string.Empty;
public string? Modulacion { set; get; } = string.Empty;
public string? Actualizacion { set; get; } = string.Empty;
// public string? NoFactura { set; get; } = string.Empty;
public string? MedidaCaja { set; get; } = string.Empty;
public string? Sello1 { set; get; } = string.Empty;
public string? Sello2 { set; get; } = string.Empty;
public int? Activo { set; get; } = 0;
}
}

@ -0,0 +1,11 @@
namespace AMAZONBackend.Models
{
public class Menu
{
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!;
}
}

@ -0,0 +1,8 @@
namespace AMAZONBackend.Models
{
public class Perfiles
{
public int id { get; set; }
public string Perfil { get; set; } = string.Empty;
}
}

@ -0,0 +1,16 @@
namespace AMAZONBackend.Models
{
public class PerfilesMenu
{
public int id { set; get; }
public int IdPerfil { set; get; }
public int itemMenu { set; get; }
public string Perfil { set; get; } = null!;
public string Descripcion { set; get; } = null!;
public int PadreId { set; get; }
public int Posicion { set; get; }
public string Url { set; get; } = null!;
public int Habilitado { set; get; }
public int Agrupado { set; get; }
}
}

@ -0,0 +1,12 @@
namespace AMAZONBackend.Models
{
public class Proveedores
{
public int IdUsuario { get; set; }
public string sClaveCliente { get; set; } = null!;
public string sClave { set; get; } = null!;
public string sRazonSocial { set; get; } = null!;
public string Direccion { set; get; } = null!;
public byte Asignado { set; get; } = 0;
}
}

@ -0,0 +1,11 @@
namespace AMAZONBackend.Models
{
public class Transportistas
{
public int id { get; set; }
public int IdUsuario { get; set; }
public string sClave { set; get; } = null!;
public string sRazonSocial { set; get; } = null!;
public byte Asignado { set; get; } = 0;
}
}

@ -0,0 +1,37 @@
namespace AMAZONBackend.Models
{
public class Usuarios
{
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 string Correo { get; set; } = null!;
public byte TipoUsuario { get; set; } = 2;
public byte Activo { get; set; } = 1;
public string FechaAlta { get; set; } = null!;
public int UsuarioAlta { get; set; } = 0!;
public string FechaModifico { get; set; } = null!;
public int UsuarioModifico { get; set; } = 0!;
public string FechaElimino { get; set; } = null!;
public int UsuarioElimino { get; set; } = 0!;
public string MotivoElimino { get; set; } = null!;
public int IdModulo { get; set; } = 0!;
public int Dept { get; set; } = 0!;
public string? sDept { get; set; } = null!;
public int Tmercancia { get; set; } = 0!;
public string FechaUltimaVisita { get; set; } = null!;
public int Visitas { get; set; } = 0!;
public int Internos { get; set; } = 0!;
public int PermisoEspecial { get; set; } = 0!;
public int EstadoConfiguracion { get; set; } = 0!;
public string FechaValidacionConf { get; set; } = null!;
public string RealizoEncuesta { get; set; } = null!;
public int EncuestaActiva { get; set; } = 0!;
public string FechaLimiteEncuesta { get; set; } = null!;
public string CodigoAccesoM { get; set; } = null!;
public string TokenAccesoM { set; get; } = null!;
public string DeviceToken { get; set; } = null!;
public int IdPerfil { get; set; } = 0!;
}
}

@ -0,0 +1,14 @@
namespace AMAZONBackend.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!;
}
}

@ -0,0 +1,7 @@
namespace AMAZONBackend.Models.Utils
{
public class FilePaths4Process
{
public string Path { set; get; } = string.Empty;
}
}

@ -0,0 +1,73 @@
using AMAZONBackend.Repositorio.Clientes;
using AMAZONBackend.Repositorio.Utils;
using AMAZONBackend.Repositorio;
using AMAZONBackend.Services.PDFGenerator.cs;
using AMAZONBackend.Clientes.Amazon.Contracts;
using AMAZONBackend.Context;
using AMAZONBackend.Contracts.Clientes.CasaCuervo;
using AMAZONBackend.Contracts.Utils;
using AMAZONBackend.Contracts;
using AMAZONBackend.Services.ValidarFraccion;
using DinkToPdf;
using DinkToPdf.Contracts;
using AMAZONBackend.Clientes.Amazon.Repository;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<DapperContext>();
builder.Services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
builder.Services.AddScoped<IUsuariosRepository, UsuariosRepository>();
builder.Services.AddScoped<IMenuRepository, MenuRepository>();
builder.Services.AddScoped<IPerfilesRepository, PerfilesRepository>();
//Clientes
builder.Services.AddScoped<IAmazonRepository, AmazonRepository>();
builder.Services.AddScoped<ICasaCuervoRepository, CasaCuervoRepository>();
//Utilerias
builder.Services.AddScoped<IFileManagerRepository, FileManagerRepository>();
builder.Services.AddScoped<IFilePaths4ProcessRepository, FilePaths4ProcessRepository>();
builder.Services.AddScoped<IPDFGenerator, PDFGenerator>();
builder.Services.AddScoped<IValidaFraccion, SrvValidaFraccion>();
//services cors
builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
{
//builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
builder.WithOrigins("http://localhost:3000",
"http://localhost:5000",
"https://localhost:5001",
"http://localhost",
"http://192.168.100.242:3000",
"http://74.208.65.168",
"http://reportes.gemcousa.com",
"http://www.gemcousa.mx",
"https://www.gemcousa.mx",
"http://www.gemcousa.mx:443",
"https://localhost:3001",
"https://www.gemcousa.mx:443").AllowAnyMethod().AllowAnyHeader();
}));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseCors("corsapp");
app.UseAuthorization();
app.MapControllers();
app.Run();

@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:43381",
"sslPort": 44300
}
},
"profiles": {
"AMAZONBackend": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

@ -0,0 +1,148 @@
using System.Data;
using Dapper;
using AMAZONBackend.Context;
using AMAZONBackend.Contracts.Clientes.CasaCuervo;
using AMAZONBackend.DTO.Clientes.CasaCuervo;
using AMAZONBackend.Models.Clientes.CasaCuervo;
namespace AMAZONBackend.Repositorio.Clientes
{
public class CasaCuervoRepository : ICasaCuervoRepository
{
private readonly DapperContext _context;
public CasaCuervoRepository(DapperContext context) { _context = context; }
public async Task<Boolean> Append(List<I325Pedidos> data)
{
var query = "[Clientes.CasaCuervo.Pedidos.Append]";
using var connection = _context.CreateConnection();
foreach (var row in data)
{
var entrada = await connection.QueryAsync<I325Pedidos>(query, new
{
@id = row.id,
@PO = row.PO,
@Aduana = row.Aduana,
@Destination = row.Destination,
@TruckNumber = row.TruckNumber,
@Forwarder = row.Forwarder,
@Carrier = row.Carrier,
@LoadDate = row.LoadDate,
@Prioridad = row.Prioridad,
@Estatus = row.Estatus,
@ComentarioGEMCO = row.ComentarioGEMCO,
@FechaCompromiso = row.FechaCompromiso,
@FechaCruce = row.FechaCruce,
@Activo = 1
},
commandType: CommandType.StoredProcedure);
}
return true;
}
public async Task<Boolean> UpdateInfoFromCorresponsal(List<DTO325ComplementaPedido> data)
{
var query = "[Clientes.CasaCuervo.Corresponsal.Pedidos.Update]";
using var connection = _context.CreateConnection();
try
{
foreach (var row in data)
{
var entrada = await connection.QueryAsync<DTO325ComplementaPedido>(query, new
{
@Pedido = row.Pedido,
@Factura = row.Factura,
@UUID = row.UUID,
@Trafico = row.Trafico,
@Pedimento = row.Pedimento,
@Patente = row.Patente,
@Modulacion = row.Modulacion,
@FechaCompromiso = row.FechaCompromiso,
@Comentarios = row.Comentario
},
commandType: CommandType.StoredProcedure);
}
}
catch (InvalidCastException e)
{
Console.Write(e.ToString());
return false;
}
return true;
}
public async Task<IEnumerable<I325Pedidos>> getAll(string Inicio, string Fin, string Aduana)
{
var query = "[Reportes.Web.Clientes.CasaCuervo.Pedidos.Get]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I325Pedidos>(query, new
{
@Inicio = Inicio,
@Fin = Fin,
@Aduana = Aduana
},
commandType: CommandType.StoredProcedure);
return entrada;
}
public async Task<I325Pedidos> GetById(int Id)
{
var query = "[Reportes.Web.Clientes.CasaCuervo.Pedidos.GetById]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I325Pedidos>(query, new
{
@Id = Id,
},
commandType: CommandType.StoredProcedure);
return entrada.First();
}
/* public async Task<I325Pedidos> Update(int id, string Campo, string Valor)
{
var query = "[Clientes.CasaCuervo.Pedidos.Update]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I325Pedidos>(query, new
{
@id = id,
@Campo = Campo,
@Valor = Valor
},
commandType: CommandType.StoredProcedure);
return entrada.First();
} */
public async Task<I325Pedidos> UpdateInfoFromWeb(DTO325UpdateFromWeb data)
{
var query = "[Clientes.CasaCuervo.Pedidos.UpdateFromWeb]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<I325Pedidos>(query, new
{
@id = data.id,
@ComentarioGEMCO = data.ComentarioGEMCO,
@FechaCruce = data.FechaCruce,
@FechaCompromiso = data.FechaCompromiso,
@Factura = data.Factura,
@MedidaCaja = data.MedidaCaja,
@Sello1 = data.Sello1,
@Sello2 = data.Sello2,
@UUID = data.UUID,
@Trafico = data.Trafico,
@Pedimento = data.Pedimento,
@Patente = data.Patente
},
commandType: CommandType.StoredProcedure);
return entrada.First();
}
public async Task<IEnumerable<DTO325AduanasPedidos>> getAduanas(int Usuario, int TipoUsuario)
{
var query = "[Clientes.CasaCuervo.Pedidos.Aduana.Get]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<DTO325AduanasPedidos>(query, new
{
@Usuario = Usuario,
@TipoUsuario = TipoUsuario
}, commandType: CommandType.StoredProcedure);
return entrada;
}
}
}

@ -0,0 +1,24 @@
using System.Data;
using Dapper;
using AMAZONBackend.Context;
using AMAZONBackend.Contracts;
using AMAZONBackend.Models;
namespace AMAZONBackend.Repositorio
{
public class MenuRepository : IMenuRepository
{
private readonly DapperContext _context;
public MenuRepository(DapperContext context) { _context = context; }
public async Task<IEnumerable<Menu>> GetItemsMenu(Usuarios user)
{
var query = "getMenu";
using (var connection = _context.CreateConnection())
{
var menu = await connection.QueryAsync<Menu>(query, new { @id = user.Id }, commandType: CommandType.StoredProcedure);
return menu.ToList();
}
}
}
}

@ -0,0 +1,107 @@
using System.Data;
using Dapper;
using AMAZONBackend.Context;
using AMAZONBackend.Contracts;
using AMAZONBackend.DTO;
using AMAZONBackend.DTO.Usuario;
using AMAZONBackend.Models;
namespace AMAZONBackend.Repositorio
{
public class PerfilesRepository : IPerfilesRepository
{
private readonly DapperContext _context;
public PerfilesRepository(DapperContext context) { _context = context; }
public async Task<IEnumerable<Perfiles>> getPerfiles()
{
var query = "getPerfiles";
using (var connection = _context.CreateConnection())
{
var perfiles = await connection.QueryAsync<Perfiles>(query, new { @id = 0 }, commandType: CommandType.StoredProcedure);
return perfiles.ToList();
}
}
public async Task<Perfiles> PerfilGetById(int id)
{
var query = "[Perfil.GetById]";
using (var connection = _context.CreateConnection())
{
var perfiles = await connection.QueryAsync<Perfiles>(query, new { @id }, commandType: CommandType.StoredProcedure);
return perfiles.FirstOrDefault(new Perfiles());
}
}
public async Task<IEnumerable<Menu>> getMenu()
{
var query = "SELECT * FROM Menu";
using (var connection = _context.CreateConnection())
{
var result = await connection.QueryAsync<Menu>(query);
return result.ToList();
}
}
public async Task<IEnumerable<PerfilesMenu>> getPerfilMenuById(int id)
{
var query = "getPerfilMenuById";
using (var connection = _context.CreateConnection())
{
var perfiles = await connection.QueryAsync<PerfilesMenu>(query, new { @id = id }, commandType: CommandType.StoredProcedure);
return perfiles.ToList();
}
}
public async Task<IEnumerable<PerfilesMenu>> getAllPerfilesMenu()
{
var query = "getAllPerfilesMenu";
using (var connection = _context.CreateConnection())
{
var perfiles = await connection.QueryAsync<PerfilesMenu>(query, new { }, commandType: CommandType.StoredProcedure);
return perfiles.ToList();
}
}
public async Task<IEnumerable<DTOPerfilCreate>> createPerfil(DTOPerfilCreate data)
{
var query = "[Perfil.Append]";
using (var connection = _context.CreateConnection())
{
var perfiles = await connection.QueryAsync<DTOPerfilCreate>(query, new { @Perfil = data.Perfil, @IdPerfilClonado = data.IdPerfilClonado }, commandType: CommandType.StoredProcedure);
return perfiles.ToList();
}
}
public async Task<IEnumerable<Menu>> createItemMenu(Menu data)
{
var query = "createItemMenu";
using (var connection = _context.CreateConnection())
{
var result = await connection.QueryAsync<Menu>(query, new { @Descripcion = data.Descripcion, @PadreId = data.PadreId, @Posicion = data.Posicion, @URL = data.Url }, commandType: CommandType.StoredProcedure);
return result.ToList();
}
}
public async Task<IEnumerable<DTOItemMenuPerfil>> asignaItemMenuPerfil(DTOItemMenuPerfil data)
{
var query = "asignaItemMenuPerfil";
using (var connection = _context.CreateConnection())
{
var perfiles = await connection.QueryAsync<DTOItemMenuPerfil>(query, new { @IdPerfil = data.IdPerfil, @itemMenu = data.itemMenu, @asignado = data.asignado }, commandType: CommandType.StoredProcedure);
return perfiles.ToList();
}
}
public async Task<IEnumerable<Transportistas>> getAllTransportistas(int id)
{
//var query = "SELECT sClave, CONCAT(sClave,' | ',sRazonSocial) as sRazonSocial FROM SIR.Admin.ADMINC_42_PROVEEDORES ORDER BY 2";
var query = "getAllTransportistas";
using (var connection = _context.CreateConnection())
{
var transportistas = await connection.QueryAsync<Transportistas>(query, new { @IdUsuario = id }, commandType: CommandType.StoredProcedure);
return transportistas.ToList();
}
}
public async Task<IEnumerable<Proveedores>> getAllProveedores(int id)
{
var query = "getAllProveedores";
using (var connection = _context.CreateConnection())
{
var proveedores = await connection.QueryAsync<Proveedores>(query, new { @IdUsuario = id }, commandType: CommandType.StoredProcedure);
return proveedores.ToList();
}
}
}
}

@ -0,0 +1,174 @@
using System.Data;
using AMAZONBackend.Crypto;
using Dapper;
using AMAZONBackend.Context;
using AMAZONBackend.Contracts;
using AMAZONBackend.DTO;
using AMAZONBackend.DTO.Usuario;
using AMAZONBackend.Models;
namespace AMAZONBackend.Repositorio
{
public class UsuariosRepository : IUsuariosRepository
{
private readonly DapperContext _context;
private readonly IConfiguration _config;
public UsuariosRepository(DapperContext context, IConfiguration config)
{
_context = context;
_config = config;
}
public async Task<IEnumerable<DTOUsuariosShort>> getAllUsuariosShort()
{
var query = "SELECT id, Usuario FROM Usuario WHERE Usuario<>'Admin'";
using (var connection = _context.CreateConnection())
{
var usuarios = await connection.QueryAsync<DTOUsuariosShort>(query);
return usuarios.ToList();
}
}
public async Task<IEnumerable<Usuarios>> getAllUsuarios()
{
var query = "SELECT * FROM Usuario";
using (var connection = _context.CreateConnection())
{
var usuarios = await connection.QueryAsync<Usuarios>(query);
return usuarios.ToList();
}
}
public async Task<Usuarios> GetUsuarioById(int id)
{
var query = "SELECT * FROM Usuario WHERE id=@id";
using (var connection = _context.CreateConnection())
{
var usuario = await connection.QueryAsync<Usuarios>(query, new { id = id });
var usr = usuario.First();
return usr;
}
}
public async Task<Usuarios> GetUsuario(DTOLogin user)
{
var query = "getUsuario";
using (var connection = _context.CreateConnection())
{
var usuarios = await connection.QueryAsync<Usuarios>(query,
new
{
Usuario = user.Usuario,
Contrasena = user.Contrasena,
@HashContrasena = CryptDecrypt.Encrypt(user.Contrasena),
}, commandType: CommandType.StoredProcedure);
Usuarios userFound = usuarios.First();
if (userFound == null) return null!;
var hashed = CryptDecrypt.Decrypt(userFound.Contrasena);
if (hashed != user.Contrasena) return null!;
return userFound;
}
}
public async Task<Usuarios> searchUsuario(DTOLogin user)
{
var query = "SELECT * FROM Usuario WHERE Usuario=@Usuario";
using (var connection = _context.CreateConnection())
{
var usuario = await connection.QueryAsync<Usuarios>(query, new { @Usuario = user.Usuario });
var usr = usuario.First();
return usr;
}
}
public async Task<DTOLogin> resetPassword(DTOLogin user)
{
var query = "[Password.Reset]";
using (var connection = _context.CreateConnection())
{
var usuarios = await connection.QueryAsync<DTOLogin>(query, new
{
@Usuario = user.Usuario,
@Contrasena = user.Contrasena,
@HashContrasena = CryptDecrypt.Encrypt(user.Contrasena),
}, commandType: CommandType.StoredProcedure);
if (usuarios.Count() == 0) return null!;
var userFound = usuarios.First();
return userFound;
}
}
public async Task<Usuarios> createUsuario(Usuarios user)
{
var query = "[Usuario.Append]";
using (var connection = _context.CreateConnection())
{
if (user.Id == 0) user.Contrasena = _config.GetValue<string>("DefaultUser:Password");
var usuario = await connection.QueryAsync<Usuarios>(query, new
{
@id = user.Id,
@Usuario = user.Usuario,
@Nombre = user.Nombre,
@Contrasena = CryptDecrypt.Encrypt(user.Contrasena),
@Correo = user.Correo,
@TipoUsuario = user.TipoUsuario,
@Activo = user.Activo,
@UsuarioAlta = user.UsuarioAlta,
@IdPerfil = user.IdPerfil
}, commandType: CommandType.StoredProcedure);
return usuario.First();
}
}
public async Task<IEnumerable<DTOClonarUsuario>> clonarUsuario(DTOClonarUsuario user)
{
var query = "Usuario.Clonar";
using (var connection = _context.CreateConnection())
{
var usuario = await connection.QueryAsync<DTOClonarUsuario>(query, new
{
@IdUsuarioOrigen = user.IDUsuarioOrigen,
@IdUsuarioDestino = user.IdUsuarioDestino
}, commandType: CommandType.StoredProcedure);
return usuario.ToList();
}
}
// Catalogo de Roles
public async Task<IEnumerable<CatRoles>> CatalogoRolesGET()
{
var query = "[CatRoles.GET]";
using (var connection = _context.CreateConnection())
{
var result = await connection.QueryAsync<CatRoles>(query, new
{
}, commandType: CommandType.StoredProcedure);
return result.ToList();
}
}
public async Task<IEnumerable<DTORolesAsignados>> RolesAsignadosGET(int id)
{
var query = "[RolesAsignados.GET]";
using (var connection = _context.CreateConnection())
{
var result = await connection.QueryAsync<DTORolesAsignados>(query, new
{
@id
}, commandType: CommandType.StoredProcedure);
return result.ToList();
}
}
public async Task<IEnumerable<DTOUsuariosPerfilParecido>> GETPerfilesParecidos(string Perfil)
{
var query = "[Usuarios.Perfiles.Parecidos.Get]";
using (var connection = _context.CreateConnection())
{
var usuarios = await connection.QueryAsync<DTOUsuariosPerfilParecido>(query, new { @Perfil }, commandType: CommandType.StoredProcedure);
return usuarios.ToList();
}
}
}
}

@ -0,0 +1,88 @@
using System.Data;
using Dapper;
using AMAZONBackend.Context;
using AMAZONBackend.Contracts.Utils;
using AMAZONBackend.Models.Utils;
namespace AMAZONBackend.Repositorio.Utils
{
public class FileManagerRepository : IFileManagerRepository
{
private readonly DapperContext _context;
public FileManagerRepository(DapperContext context) { _context = context; }
public async Task<FileManager> FileManager(FileManager data)
{
var query = "[Utils.FileManager.Append]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<FileManager>(query, new
{
@id = 0,
@IdUsuario = data.IdUsuario,
@Proceso = data.Proceso,
@NombreArchivo = data.NombreArchivo,
@Tags = data.Tags,
@Size = data.Size
},
commandType: CommandType.StoredProcedure);
return entrada.First();
}
public async Task<FileManager> getFileByProcess(long id, int Proceso)
{
var query = "[Utils.FileManager.Get]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<FileManager>(query, new
{
@id = 0,
@Proceso = Proceso,
@NombreArchivo = "",
@Tags = id,
},
commandType: CommandType.StoredProcedure);
return entrada.FirstOrDefault(new FileManager { id = id, Proceso = Proceso, NombreArchivo = "", Tags = "", Size = 0 });
}
public async Task<FileManager> getFileById(long id)
{
var query = "[Utils.FileManager.Get]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<FileManager>(query, new
{
@id = id,
@Proceso = 0,
@NombreArchivo = "",
@Tags = id,
},
commandType: CommandType.StoredProcedure);
return entrada.FirstOrDefault(new FileManager { id = id, Proceso = 0, NombreArchivo = "", Tags = "", Size = 0 });
}
public async Task<List<FileManager>> getAllFilesByProcess(long Tags, int Proceso)
{
var query = "[Utils.FileManager.Get]";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<FileManager>(query, new
{
@id = 0,
@Proceso = Proceso,
@NombreArchivo = "",
@Tags = 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<FileManager>(query, new
{
@id = id,
@Proceso = Proceso,
},
commandType: CommandType.StoredProcedure);
}
}
}

@ -0,0 +1,26 @@
using System.Data;
using Dapper;
using AMAZONBackend.Context;
using AMAZONBackend.Contracts.Utils;
using AMAZONBackend.Models.Utils;
namespace AMAZONBackend.Repositorio.Utils
{
public class FilePaths4ProcessRepository : IFilePaths4ProcessRepository
{
private readonly DapperContext _context;
public FilePaths4ProcessRepository(DapperContext context) { _context = context; }
public async Task<FilePaths4Process> getPaths4ProcessById(long id)
{
var query = "getPath4ProcessById";
using var connection = _context.CreateConnection();
var entrada = await connection.QueryAsync<FilePaths4Process>(query, new
{
@id = id,
},
commandType: CommandType.StoredProcedure);
return entrada.First();
}
}
}

@ -0,0 +1,160 @@
using System.Data;
using ExcelDataReader;
using AMAZONBackend.Contracts.Clientes.CasaCuervo;
using AMAZONBackend.DTO.Clientes.CasaCuervo;
using AMAZONBackend.Models.Clientes.CasaCuervo;
namespace AMAZONBackend.Services.Clientes.SCasaCuervo
{
public class SCasaCuervo
{
public DataSet mExcelInfo = null!;
private readonly ICasaCuervoRepository _Repo;
private readonly string rutaArchivo;
public SCasaCuervo(ICasaCuervoRepository Repo, String Archivo)
{
_Repo = Repo;
rutaArchivo = Archivo;
}
public async Task<Boolean> ReadExcel()
{
DataTable dt = new DataTable();
List<I325Pedidos> Data = new List<I325Pedidos>();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = File.Open(rutaArchivo, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
mExcelInfo = reader.AsDataSet();
if (mExcelInfo != null)
{
int lastTable = mExcelInfo!.Tables.Count - 1;
dt = mExcelInfo.Tables[lastTable];
for (int r = 1; r < mExcelInfo!.Tables[mExcelInfo.Tables.Count - 1].Rows.Count; r++)
{
if (mExcelInfo != null)
{
/* I325Pedidos data = new I325Pedidos();
data.PO = mExcelInfo.Tables[lastTable].Rows[r][0].ToString() ?? "";
data.Aduana = (string)mExcelInfo!.Tables[lastTable].Rows[r][1];
data.Destination = (string)mExcelInfo!.Tables[lastTable].Rows[r][2];
data.TruckNumber = mExcelInfo.Tables[lastTable].Rows[r][3].ToString() ?? "";
data.Forwarder = (string)mExcelInfo.Tables[lastTable].Rows[r][4];
data.Carrier = (string)mExcelInfo.Tables[lastTable].Rows[r][5];
data.LoadDate = changeDateFormat(mExcelInfo.Tables[lastTable].Rows[r][6].ToString() ?? "");
data.Prioridad = mExcelInfo.Tables[lastTable].Rows[r][7].ToString() ?? "";
data.Estatus = mExcelInfo.Tables[lastTable].Rows[r][8].ToString();
Data.Add(data); */
I325Pedidos data = new I325Pedidos();
data.PO = mExcelInfo.Tables[lastTable].Rows[r][0].ToString() ?? "";
data.Aduana = mExcelInfo!.Tables[lastTable].Rows[r][1].ToString() ?? "";
data.Destination = mExcelInfo!.Tables[lastTable].Rows[r][2].ToString() ?? "";
data.TruckNumber = mExcelInfo.Tables[lastTable].Rows[r][3].ToString() ?? "";
data.Forwarder = mExcelInfo.Tables[lastTable].Rows[r][4].ToString() ?? "";
data.Carrier = mExcelInfo.Tables[lastTable].Rows[r][5].ToString() ?? "";
data.LoadDate = changeDateFormat(mExcelInfo.Tables[lastTable].Rows[r][6].ToString() ?? "");
data.Prioridad = mExcelInfo.Tables[lastTable].Rows[r][7].ToString() ?? "";
data.Estatus = mExcelInfo.Tables[lastTable].Rows[r][8].ToString() ?? "";
Data.Add(data);
}
}
stream.Close();
await _Repo.Append(Data);
}
}
}
return true;
}
public async Task<Boolean> UpdateInfoFromCorresponsal()
{
DataTable dt = new DataTable();
List<DTO325ComplementaPedido> Data = new List<DTO325ComplementaPedido>();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = File.Open(rutaArchivo, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
mExcelInfo = reader.AsDataSet();
if (mExcelInfo != null)
{
int lastTable = mExcelInfo.Tables.Count - 1;
dt = mExcelInfo.Tables[lastTable];
for (int r = 1; r < mExcelInfo!.Tables[mExcelInfo.Tables.Count - 1].Rows.Count; r++)
{
if (mExcelInfo != null)
{
DTO325ComplementaPedido data = new DTO325ComplementaPedido();
if (mExcelInfo.Tables[lastTable].Columns.Count >= 1)
{
data.Pedido = mExcelInfo.Tables[lastTable].Rows[r][0].ToString() ?? "";
}
if (mExcelInfo.Tables[lastTable].Columns.Count >= 2)
{
data.Factura = mExcelInfo.Tables[lastTable].Rows[r][1].ToString() ?? "";
}
if (mExcelInfo.Tables[lastTable].Columns.Count >= 3)
{
data.UUID = mExcelInfo.Tables[lastTable].Rows[r][2].ToString() ?? "";
}
if (mExcelInfo.Tables[lastTable].Columns.Count >= 4)
{
data.Trafico = mExcelInfo.Tables[lastTable].Rows[r][3].ToString() ?? "";
}
if (mExcelInfo.Tables[lastTable].Columns.Count >= 5)
{
data.Pedimento = mExcelInfo.Tables[lastTable].Rows[r][4].ToString() ?? "";
}
if (mExcelInfo.Tables[lastTable].Columns.Count >= 7)
{
data.Patente = mExcelInfo.Tables[lastTable].Rows[r][6].ToString() ?? "";
}
if (mExcelInfo?.Tables[lastTable].Columns.Count >= 8)
{
data.Modulacion = mExcelInfo.Tables[lastTable].Rows[r][7].ToString() ?? "";
}
if (mExcelInfo?.Tables[lastTable].Columns.Count >= 9)
{
string? fecha = mExcelInfo.Tables[lastTable].Rows[r][8].ToString();
if (IsDateTime(fecha!))
{
data.FechaCompromiso = fecha;
var temp = Convert.ToDateTime(fecha);
data.FechaCompromiso = temp.ToString("MM/dd/yyyy");
}
else return false;
}
if (mExcelInfo?.Tables[mExcelInfo.Tables.Count - 1].Columns.Count >= 10)
{
data.Comentario = mExcelInfo?.Tables[lastTable].Rows[r][9].ToString();
}
Data.Add(data);
}
}
stream.Close();
await _Repo.UpdateInfoFromCorresponsal(Data);
}
}
}
return true;
}
public static bool IsDateTime(string txtDate)
{
DateTime tempDate;
return DateTime.TryParse(txtDate, out tempDate);
}
private string changeDateFormat(String data)
{
if (data.Length == 0) return "";
var datePart = data.Split(' ');
String[] arr = datePart[0].Split('/');
return arr[2].Substring(0, 4) + "-" + arr[0].PadLeft(2, '0') + "-" + arr[1].PadLeft(2, '0');
}
}
}

@ -0,0 +1,107 @@
using Microsoft.AspNetCore.Mvc;
using AMAZONBackend.Contracts.Utils;
using AMAZONBackend.Models.Utils;
namespace AMAZONBackend.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<List<FileManager>> GetFilesFromLog(int Tags, int Proceso)
{
return await _Repo.getAllFilesByProcess(Tags, Proceso);
}
public async Task<IActionResult> getFileContentById(long id)
{
Boolean ExisteEnDisco = false;
byte[] emptyFile = System.IO.File.ReadAllBytes("c:\\downs\\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)
{
Console.Write(ex.ToString());
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<List<string>> SaveFile2DiskList(List<IFormFile> FileList)
{
DateTime time = DateTime.Now;
var filePaths = new List<string>();
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<List<FileManager>> SaveFileLog(List<string> files, int Tags, int Proceso, int Usuario)
{
List<FileManager> resultados = new List<FileManager>();
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);
}
}
}

@ -0,0 +1,54 @@

using DinkToPdf;
using DinkToPdf.Contracts;
using AMAZONBackend.Contracts.Utils;
namespace AMAZONBackend.Services.PDFGenerator.cs
{
public class PDFGenerator : IPDFGenerator
{
private readonly IConverter _converter;
public PDFGenerator(IConverter converter)
{
_converter = converter;
}
private async Task<byte[]> GeneratePdf(string htmlContent)
{
var globalSettings = new GlobalSettings
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4,
Margins = new MarginSettings { Top = 18, Bottom = 18, Left = 18, Right = 18 },
};
var objectSettings = new ObjectSettings
{
PagesCount = true,
HtmlContent = htmlContent,
WebSettings = { DefaultEncoding = "utf-8" },
/* HeaderSettings = { FontSize = 10, Right = "Page [page] of [toPage]", Line = true },*/
FooterSettings = { FontSize = 8, Right = "[page] DE [toPage]", Line = true },
};
var htmlToPdfDocument = new HtmlToPdfDocument()
{
GlobalSettings = globalSettings,
Objects = { objectSettings },
};
return await Task.FromResult(_converter.Convert(htmlToPdfDocument));
}
public async Task<byte[]> GeneratePdfFromString(string htmlContent)
{
return await GeneratePdf(htmlContent);
}
}
}

@ -0,0 +1,59 @@
using System.Net;
using System.Net.Mail;
using AMAZONBackend.Models;
namespace AMAZONBackend.Services
{
public class Utilerias
{
private IConfiguration _config;
public Utilerias(IConfiguration config)
{
_config = config;
}
public Boolean SendEmail(string htmlContent, Usuarios user)
{
string defaultPassword = _config.GetValue<string>("DefaultUser:Password");
string emailServer = _config.GetValue<string>("EmailServer");
int emailPort = _config.GetValue<int>("EmailPort");
htmlContent = (htmlContent.Length > 0) ? htmlContent : $@"<html>
<body>
<table style='font-size:14px; border: 1px solid #225EDD; padding: 5px; width: 1500px; height: 150px;'>
<tr style='background-color: #225EDD; color: #FFFFFF;'><td>Hola: {user.Nombre}, mediante el siguiente correo electronico, se le notifica que se le ha creado un nuevo acceso</td></tr>
<tr><td>Para acceder a su cuenta, favor de entrar a: http://reportes.gemcousa.com/</td></tr>
<tr><td>Nombre de usuario: <b>{user.Usuario}</b></td></tr>
<tr><td>Contraseña: <b>{defaultPassword}</b></td></tr>
<tr><td>Su contraseña inicial sera: {defaultPassword}, pero es necesario que la cambie antes de poder ingresar</td></tr>
<tr><td>Para cambiar la contraseña, puede ir al menu Reset, proporcione su nombre de usuario y su nueva contraseña</td></tr>
<tr><td>Si por alguna razon, no recuerda su contrasena, repita este proceso de resetear su contraseña</td></tr>
<tr><td>No es necesario responder a este correo, ya que fue generado en automatico por el sistema.</td></tr>
<tr style='background-color: #F7192A; font-weight: bold; color: #FFFFFF'><td>Nota: Las credenciales de acceso son responsabilidad personal, nadie solo usted debe conocerlas</td></tr>
<tr><td>Que tenga un excelente dia!</td></tr>
</table>
</body>
</html> ";
try
{
using (var smtp = new SmtpClient(emailServer, emailPort))
{
smtp.Credentials = new NetworkCredential("noreply@gemcousa.com", "N#16rm87");
smtp.EnableSsl = false;
var correo = new MailMessage();
correo.From = new MailAddress("noreply@gemcousa.com", "noreply");
correo.To.Add(user.Correo);
correo.Subject = "Notification - Se le ha creado un nuevo acceso en http://reportes.gemcousa.com";
correo.Body = htmlContent;
correo.IsBodyHtml = true;
smtp.Send(correo);
return true;
}
}
catch (Exception ex)
{
Console.Write(ex.ToString());
return false;
}
}
}
}

@ -0,0 +1,102 @@
using System.Net;
using System.Xml;
using System.Xml.Linq;
using AMAZONBackend.Contracts.Utils;
namespace AMAZONBackend.Services.ValidarFraccion
{
public class SrvValidaFraccion : IValidaFraccion
{
public Boolean ValidaFraccion(string Fraccion)
{
if (Fraccion.Length != 10) { return false; }
int inicio = 0, fin = 0;
string Nico = Fraccion.Substring(8, 2);
Fraccion = Fraccion.Substring(0, 8);
List<string> NicosAutorizados = new List<string>();
DateTime now = DateTime.Now;
int year = now.Year;
int month = now.Month;
int day = now.Day;
string Fecha = String.Format("{0:00}/{1:00}/{2:0000}", day, month, year);
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:tel=""http://tel.reco/"">
<soap:Header/>
<soap:Body>
<tel:TEL>
<!--Optional:-->
<tel:palabra></tel:palabra>
<!--Optional:-->
<tel:fraccion>" + Fraccion + @"</tel:fraccion>
<!--Optional:-->
<tel:fecha>" + Fecha + @"</tel:fecha>
<!--Optional:-->
<tel:operacion>I</tel:operacion>
<!--Optional:-->
<tel:pais_origen>MEX</tel:pais_origen>
<!--Optional:-->
<tel:adusecc>240</tel:adusecc>
<!--Optional:-->
<tel:patente>3636</tel:patente>
<!--Optional:-->
<tel:Fpago>" + Fecha + @"</tel:Fpago>
</tel:TEL>
</soap:Body>
</soap:Envelope>");
using (Stream stream = request.GetRequestStream()) { soapEnvelopeXml.Save(stream); }
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
string resultado = soapResult.ToString();
try
{
inicio = resultado.IndexOf("&lt;desc_nicos&gt;");
}
catch (FormatException)
{
return false;
}
try
{
fin = resultado.IndexOf("&lt;/desc_nicos&gt;");
}
catch (FormatException)
{
return false;
}
if (inicio < 0 || fin < 0) return false;
resultado = resultado.Substring(inicio, resultado.Length - fin);
inicio = resultado.IndexOf("&lt;desc_nicos&gt;");
fin = resultado.IndexOf("&lt;/desc_nicos&gt;");
resultado = resultado.Substring(inicio, fin);
resultado = resultado.Replace("&lt;", "<").Replace("&gt;", ">") + "</desc_nicos>";
XElement contacts = XElement.Parse(
resultado);
List<XElement> Nicos = contacts.Elements("numero").ToList();
foreach (var nico in Nicos)
{
NicosAutorizados.Add(nico.ToString().Replace("<numero>", "").Replace("</numero>", ""));
}
}
}
return (NicosAutorizados.Any(Nico.Contains));
}
public static HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"https://tarifaweb.griver.com.mx/wstel/tel.asmx?op=TEL");
webRequest.Headers.Add(@"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
}
}

@ -0,0 +1,13 @@
namespace AMAZONBackend
{
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; }
}
}

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

@ -0,0 +1,22 @@
{
"ConnectionStrings": {
"SqlConnection": "server=.; database=GEMCO; Integrated Security=true;TrustServerCertificate=True;"
//initial catalog = sa;user=code; password=Chispa10
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Jwt": {
"Key": "GFE1j5KLolZHDK9iKw5xK17Rz4ty7BlbXgnjPL6dNwVCCNQWU8uRGVyZmAZPWZMs4XX0phFMS849p25Lrwsn31Bi4J7GT2HQ9xeWlJLarJPDyoRZZvChpovwgrquQ9Pd",
"Issuer": "JWTAuthenticationServer",
"Audience": "JWTServicePostmanClient",
"Subject": "JWTServiceAccessToken",
"ExpirationHours": 4
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,19 @@
{
"runtimeOptions": {
"tfm": "net6.0",
"frameworks": [
{
"name": "Microsoft.NETCore.App",
"version": "6.0.0"
},
{
"name": "Microsoft.AspNetCore.App",
"version": "6.0.0"
}
],
"configProperties": {
"System.GC.Server": true,
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save