Commit 80ed77d5 authored by Jose Hugo Torres's avatar Jose Hugo Torres
Browse files

Maneja mensaje terminar

parent 5f1abf15
...@@ -9,12 +9,33 @@ public class CHECPrueba ...@@ -9,12 +9,33 @@ public class CHECPrueba
private const string GatewayServer = "127.0.0.1"; private const string GatewayServer = "127.0.0.1";
private const int GatewayPort = 6690; private const int GatewayPort = 6690;
static string mensaje1 = @"soeps~Message-Type=REQ|Session-Id=400|~<?xml version=""1.0"" encoding=""UTF-8""?><scsns:Initialize xmlns:scsns=""http://bc.si.retail.ibm.com/POSBCSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://bc.si.retail.ibm.com/POSBCSchema C:\\PosBc\\POSBCSchema_main.xsd"" >
<InitializeRequest>
<OperatorID>NO_DEFAULT</OperatorID
<TerminalNumber>400</TerminalNumber>
<Recovery>false</Recovery>
</InitializeRequest>
</scsns:Initialize>";
static string mensaje2 = @"soeps~Message-Type=REQ|Session-Id=400|~<?xml version=""1.0"" encoding=""UTF-8""?><scsns:QueryStatus xmlns:scsns=""http://bc.si.retail.ibm.com/POSBCSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://bc.si.retail.ibm.com/POSBCSchema C:\\PosBc\\POSBCSchema_main.xsd"" >
<QueryStatusRequest/>
</scsns:QueryStatus>";
static string mensaje3 = @"soeps~Message-Type=REQ|Session-Id=400|~<?xml version=""1.0"" encoding=""UTF-8""?><scsns:ReportStatusEvents xmlns:scsns=""http://bc.si.retail.ibm.com/POSBCSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://bc.si.retail.ibm.com/POSBCSchema C:\\PosBc\\POSBCSchema_main.xsd"" >
<ReportStatusEventsRequest>
<RequestID>101</RequestID></ReportStatusEventsRequest>
</scsns:ReportStatusEvents>";
public static async Task Main(string[] args) public static async Task Main(string[] args)
{ {
Log.Logger = new LoggerConfiguration() Log.Logger = new LoggerConfiguration()
.WriteTo.Console() .WriteTo.Console()
.CreateLogger(); .CreateLogger();
string[] mensajes = [CHECPrueba.mensaje1, CHECPrueba.mensaje2, CHECPrueba.mensaje3];
int i = 0;
try try
{ {
using TcpClient client = new TcpClient(); using TcpClient client = new TcpClient();
...@@ -22,12 +43,14 @@ public class CHECPrueba ...@@ -22,12 +43,14 @@ public class CHECPrueba
Log.Information("Conectado al Gateway."); Log.Information("Conectado al Gateway.");
using NetworkStream stream = client.GetStream(); using NetworkStream stream = client.GetStream();
int messageNumber = 1; int messageNumber = 1;
while (true) while (true)
{ {
// Remitir un mensaje numerado al Gateway // Remitir un mensaje numerado al Gateway
string message = $"Mensaje {messageNumber} desde CHEC"; string message = mensajes[i++];
if (i == mensajes.Length - 1) i = 0;
byte[] messageBytes = Encoding.UTF8.GetBytes(message); byte[] messageBytes = Encoding.UTF8.GetBytes(message);
byte[] lengthBytes = BitConverter.GetBytes(messageBytes.Length); byte[] lengthBytes = BitConverter.GetBytes(messageBytes.Length);
...@@ -38,8 +61,6 @@ public class CHECPrueba ...@@ -38,8 +61,6 @@ public class CHECPrueba
byte[] bytesMsj = Util.ConcatenaArreglosBytes(lengthBytes, messageBytes); byte[] bytesMsj = Util.ConcatenaArreglosBytes(lengthBytes, messageBytes);
// await stream.WriteAsync(lengthBytes, 0, 4);
// await stream.WriteAsync(messageBytes, 0, messageBytes.Length);
await stream.WriteAsync(bytesMsj, 0, bytesMsj.Length); await stream.WriteAsync(bytesMsj, 0, bytesMsj.Length);
Log.Information($"Mensaje {messageNumber} enviado al Gateway: {message}"); Log.Information($"Mensaje {messageNumber} enviado al Gateway: {message}");
...@@ -47,7 +68,7 @@ public class CHECPrueba ...@@ -47,7 +68,7 @@ public class CHECPrueba
await ReceiveResponsesAsync(stream); await ReceiveResponsesAsync(stream);
messageNumber++; messageNumber++;
await Task.Delay(5000); // Esperar 5 segundos antes de enviar el siguiente mensaje await Task.Delay(8000); // Esperar 5 segundos antes de enviar el siguiente mensaje
} }
} }
catch (Exception ex) catch (Exception ex)
......
...@@ -9,6 +9,23 @@ public class PosbcServer ...@@ -9,6 +9,23 @@ public class PosbcServer
private const int Port = 6697; private const int Port = 6697;
private static int messageCounter = 1; private static int messageCounter = 1;
static string mensaje1 = @"soeps~Session-Id=400|Message-Type=EVENT|~<?xml version=""1.0"" encoding=""UTF-8""?>
<schema:POSBCStatusEvent xmlns:schema=""http://bc.si.retail.ibm.com/POSBCSchema"">
<POSStatus>
<Severity>INFO</Severity>
<Status>CONNECTING_TO_POS</Status>
<StatusMessage>Connecting to POS system</StatusMessage>
</POSStatus>
</schema:POSBCStatusEvent>";
static string mensajeTerminar = @"soeps~Session-Id=400|Message-Type=RESP|~<?xml version=""1.0"" encoding=""UTF-8""?>
<schema:TerminateResponse xmlns:schema=""http://bc.si.retail.ibm.com/POSBCSchema"">
<TerminateResult>
<RequestID>110</RequestID>
</TerminateResult>
</schema:TerminateResponse>";
public static async Task Main() public static async Task Main()
{ {
Log.Logger = new LoggerConfiguration() Log.Logger = new LoggerConfiguration()
...@@ -62,14 +79,19 @@ public class PosbcServer ...@@ -62,14 +79,19 @@ public class PosbcServer
Log.Information($"Mensaje recibido del Gateway: {message}"); Log.Information($"Mensaje recibido del Gateway: {message}");
// Esperar 2 segundos antes de enviar la primera respuesta // Esperar 2 segundos antes de enviar la primera respuesta
await Task.Delay(2000); await Task.Delay(1000);
await EnviarMensaje(stream, $"Respuesta {messageCounter++} desde POSBC"); //await EnviarMensaje(stream, $"Respuesta {messageCounter++} desde POSBC");
await EnviarMensaje(stream, mensaje1);
// Esperar 2 segundos y enviar dos mensajes adicionales // Esperar 2 segundos y enviar dos mensajes adicionales
await Task.Delay(2000); await Task.Delay(1000);
await EnviarMensaje(stream, $"Mensaje adicional {messageCounter++} desde POSBC"); //await EnviarMensaje(stream, $"Mensaje adicional {messageCounter++} desde POSBC");
await Task.Delay(2000); await EnviarMensaje(stream, mensaje1);
await EnviarMensaje(stream, $"Mensaje adicional {messageCounter++} desde POSBC"); await Task.Delay(1000);
//await EnviarMensaje(stream, $"Mensaje adicional {messageCounter++} desde POSBC");
await EnviarMensaje(stream, mensajeTerminar);
await Task.Delay(1000);
break;
} }
} }
} }
......
using EvaPOS_API_FRAME.DTO.Intercambio;
using EvaPOS_API_FRAME.RespuestasXML;
using EvaPOS_API_FRAME.RespuestasXML.Printer;
using EvaPosSrvDTO;
using EvaPosSrvResp;
using Serilog;
namespace Gateway.Comandos.POSBC
{
/// <summary>
/// Procesa solicitudes de InitializeRequest.
/// </summary>
public class InitializeRequestCmd : IComando
{
public string Referencia { get; set; } = "scsns:Initialize";
/// <summary>
/// DTO con solicitud.
/// </summary>
public InitializeRequestDTO Request { get; private set; }
/// <summary>
/// Procesa y responde InitializeRequest.
/// </summary>
public Respuestas Ejecutar()
{
int terminalNumber = Request.TerminalNumber;
Log.Debug("Cmd InitializeRequestCmd ejecutado. Request id: {id}, terminal: {terminal}, recovery: {recovery}", Request.OperatorID, Request.TerminalNumber, Request.Recovery);
// --- NO EJECUTA ACCIÓN, NO RETORNA RESPUESTAS.
return [];
}
public IComando CreaCopia()
{
return (InitializeRequestCmd)this.MemberwiseClone();
}
public void CargaDTO(DTOBase initializeRequestDTO)
{
Request = (InitializeRequestDTO)initializeRequestDTO;
}
}
}
using EvaPOS_API_FRAME.DTO.Intercambio;
using EvaPOS_API_FRAME.RespuestasXML;
using EvaPOS_API_FRAME.RespuestasXML.Printer;
using EvaPosSrvDTO;
using EvaPosSrvResp;
using Serilog;
namespace Gateway.Comandos.POSBCTest
{
/// <summary>
/// Procesa solicitudes de InitializeRequest.
/// </summary>
public class InitializeRequestCmd : IComando
{
public string Referencia { get; set; } = "scsns:Initialize";
/// <summary>
/// DTO con solicitud.
/// </summary>
public InitializeRequestDTO Request { get; private set; }
/// <summary>
/// Procesa y responde InitializeRequest.
/// </summary>
public Respuestas Ejecutar()
{
int terminalNumber = Request.TerminalNumber;
Log.Debug("Cmd InitializeRequestCmd ejecutado. Request id: {id}, terminal: {terminal}, recovery: {recovery}", Request.OperatorID, Request.TerminalNumber, Request.Recovery);
var posbcStatus1 = new POSBCStatusEvent(1, TipoMensaje.Event, "INFO", "CONNECTING_TO_POS", "Procesador por el Geteway");
return [posbcStatus1];
}
public IComando CreaCopia()
{
return (InitializeRequestCmd)this.MemberwiseClone();
}
public void CargaDTO(DTOBase initializeRequestDTO)
{
Request = (InitializeRequestDTO)initializeRequestDTO;
}
}
}
...@@ -210,7 +210,7 @@ namespace gatewayGK.ComandosGk ...@@ -210,7 +210,7 @@ namespace gatewayGK.ComandosGk
var regularUnitPriceTrans = regularUnitPrice.ToString(); var regularUnitPriceTrans = regularUnitPrice.ToString();
Log.Debug($"Transaction ID: {transactionId} "); Log.Debug($"Transaction ID: {transactionId} ");
Entorno<EntornoGK>.Instancia.get().TransactionID = transactionId; Entorno<EntornoGK>.Instancia.Get().TransactionID = transactionId;
string tomarNombreCorto = ""; string tomarNombreCorto = "";
//Valores que se mandan en chec //Valores que se mandan en chec
......
...@@ -29,7 +29,7 @@ namespace gatewayGK.ComandosGk ...@@ -29,7 +29,7 @@ namespace gatewayGK.ComandosGk
/// <summary> /// <summary>
/// Url servicio autenticación Gk. /// Url servicio autenticación Gk.
/// </summary> /// </summary>
private string _urlRegisterItem = Entorno<EntornoGK>.Instancia.get().UrlBase private string _urlRegisterItem = Entorno<EntornoGK>.Instancia.Get().UrlBase
+ "/com.gk_software.pos.api.service.transaction.LineItemService/registerLineItem"; + "/com.gk_software.pos.api.service.transaction.LineItemService/registerLineItem";
/// <summary> /// <summary>
...@@ -70,7 +70,7 @@ namespace gatewayGK.ComandosGk ...@@ -70,7 +70,7 @@ namespace gatewayGK.ComandosGk
MaxTimeout = -1, MaxTimeout = -1,
RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
}; };
string sessionId = Entorno<EntornoGK>.Instancia.get().posSessionId; string sessionId = Entorno<EntornoGK>.Instancia.Get().posSessionId;
string cookieValue = $"sessionid={sessionId}"; string cookieValue = $"sessionid={sessionId}";
var client = new RestClient(options); var client = new RestClient(options);
...@@ -201,7 +201,7 @@ namespace gatewayGK.ComandosGk ...@@ -201,7 +201,7 @@ namespace gatewayGK.ComandosGk
units, units,
textName textName
); );
Entorno<EntornoGK>.Instancia.get().TransactionID = transactionId; Entorno<EntornoGK>.Instancia.Get().TransactionID = transactionId;
string tomarNombreCorto = ""; string tomarNombreCorto = "";
//Valores que se mandan en chec //Valores que se mandan en chec
......
...@@ -31,7 +31,7 @@ namespace gatewayGK.ComandosGk ...@@ -31,7 +31,7 @@ namespace gatewayGK.ComandosGk
/// <summary> /// <summary>
/// Url servicio autenticación Gk. /// Url servicio autenticación Gk.
/// </summary> /// </summary>
private string _urlRegisterItem = Entorno<EntornoGK>.Instancia.get().UrlBase private string _urlRegisterItem = Entorno<EntornoGK>.Instancia.Get().UrlBase
+ "/com.gk_software.pos.api.service.transaction.LineItemService/registerLineItem"; + "/com.gk_software.pos.api.service.transaction.LineItemService/registerLineItem";
/// <summary> /// <summary>
...@@ -72,7 +72,7 @@ namespace gatewayGK.ComandosGk ...@@ -72,7 +72,7 @@ namespace gatewayGK.ComandosGk
MaxTimeout = -1, MaxTimeout = -1,
RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
}; };
string sessionId = Entorno<EntornoGK>.Instancia.get().posSessionId; string sessionId = Entorno<EntornoGK>.Instancia.Get().posSessionId;
string cookieValue = $"sessionid={sessionId}"; string cookieValue = $"sessionid={sessionId}";
var client = new RestClient(options); var client = new RestClient(options);
...@@ -201,9 +201,9 @@ namespace gatewayGK.ComandosGk ...@@ -201,9 +201,9 @@ namespace gatewayGK.ComandosGk
} }
} }
Entorno<EntornoGK>.Instancia.get().TransactionID = transactionId; Entorno<EntornoGK>.Instancia.Get().TransactionID = transactionId;
Entorno<EntornoGK>.Instancia.get().BusinessUnitGroupID = businessUnitGroupID; Entorno<EntornoGK>.Instancia.Get().BusinessUnitGroupID = businessUnitGroupID;
Entorno<EntornoGK>.Instancia.get().SequenceNumber = sequenceNumber ?? 0; Entorno<EntornoGK>.Instancia.Get().SequenceNumber = sequenceNumber ?? 0;
//Pasarlo a string //Pasarlo a string
var regularUnitPriceTrans = regularUnitPrice.ToString(); var regularUnitPriceTrans = regularUnitPrice.ToString();
...@@ -216,7 +216,7 @@ namespace gatewayGK.ComandosGk ...@@ -216,7 +216,7 @@ namespace gatewayGK.ComandosGk
units, units,
receiptText, receiptText,
sequenceNumber, sequenceNumber,
Entorno<EntornoGK>.Instancia.get().SuspendNumber Entorno<EntornoGK>.Instancia.Get().SuspendNumber
); );
Log.Information(String.Format("{0,3} | {1,13} | {2,-20} | {3,3}| {4,-5:N2} | {5,12:N2} | {6,12:N2} | {7,12:N2} | {8,12:N2} | {9,3}", Log.Information(String.Format("{0,3} | {1,13} | {2,-20} | {3,3}| {4,-5:N2} | {5,12:N2} | {6,12:N2} | {7,12:N2} | {8,12:N2} | {9,3}",
addedOrModifiedLineItems.Key.RetailTransactionLineItemSequenceNumber, addedOrModifiedLineItems.Key.RetailTransactionLineItemSequenceNumber,
......
...@@ -30,7 +30,7 @@ namespace gatewayGK.ComandosGk ...@@ -30,7 +30,7 @@ namespace gatewayGK.ComandosGk
/// <summary> /// <summary>
/// Url servicio autenticación Gk. /// Url servicio autenticación Gk.
/// </summary> /// </summary>
private string _urlRegisterItem = Entorno<EntornoGK>.Instancia.get().UrlBase private string _urlRegisterItem = Entorno<EntornoGK>.Instancia.Get().UrlBase
+ "services/com.gk_software.pos.api.service.taxengine.TaxEngineService/calculateTax"; + "services/com.gk_software.pos.api.service.taxengine.TaxEngineService/calculateTax";
/// <summary> /// <summary>
...@@ -55,7 +55,7 @@ namespace gatewayGK.ComandosGk ...@@ -55,7 +55,7 @@ namespace gatewayGK.ComandosGk
{ {
Key = new() Key = new()
{ {
BusinessUnitGroupID = Entorno<EntornoGK>.Instancia.get().BusinessUnitGroupID, BusinessUnitGroupID = Entorno<EntornoGK>.Instancia.Get().BusinessUnitGroupID,
TransactionID = "" TransactionID = ""
}, },
OperatorID = "", OperatorID = "",
...@@ -88,7 +88,7 @@ namespace gatewayGK.ComandosGk ...@@ -88,7 +88,7 @@ namespace gatewayGK.ComandosGk
MaxTimeout = -1, MaxTimeout = -1,
RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
}; };
string sessionId = Entorno<EntornoGK>.Instancia.get().posSessionId; string sessionId = Entorno<EntornoGK>.Instancia.Get().posSessionId;
string cookieValue = $"sessionid={sessionId}"; string cookieValue = $"sessionid={sessionId}";
var client = new RestClient(options); var client = new RestClient(options);
...@@ -198,7 +198,7 @@ namespace gatewayGK.ComandosGk ...@@ -198,7 +198,7 @@ namespace gatewayGK.ComandosGk
)); ));
Log.Information(String.Format("SUBTOTAL: {0,12:N2} // SUBTOTAL_DISCOUNT: {1,12:N2} // TOTAL: {2,12:N2}", Log.Information(String.Format("SUBTOTAL: {0,12:N2} // SUBTOTAL_DISCOUNT: {1,12:N2} // TOTAL: {2,12:N2}",
subtotal, subtotalDcto, total)); subtotal, subtotalDcto, total));
Entorno<EntornoGK>.Instancia.get().TransactionID = transactionId; Entorno<EntornoGK>.Instancia.Get().TransactionID = transactionId;
string tomarNombreCorto = ""; string tomarNombreCorto = "";
//Valores que se mandan en chec //Valores que se mandan en chec
......
...@@ -22,7 +22,7 @@ namespace gatewayGK.ComandosGk ...@@ -22,7 +22,7 @@ namespace gatewayGK.ComandosGk
/// <summary> /// <summary>
/// Url servicio autenticación Gk. /// Url servicio autenticación Gk.
/// </summary> /// </summary>
private string _urlLogin = Entorno<EntornoGK>.Instancia.get().UrlBase private string _urlLogin = Entorno<EntornoGK>.Instancia.Get().UrlBase
+ "/com.gk_software.pos.api.service.session.PosSessionService/login"; + "/com.gk_software.pos.api.service.session.PosSessionService/login";
/// <summary> /// <summary>
...@@ -69,12 +69,12 @@ namespace gatewayGK.ComandosGk ...@@ -69,12 +69,12 @@ namespace gatewayGK.ComandosGk
var datosAutenticacion = new AutenticationReq var datosAutenticacion = new AutenticationReq
{ {
RetailStoreId = Entorno<EntornoGK>.Instancia.get().ConfigGk.RetailStoreId, RetailStoreId = Entorno<EntornoGK>.Instancia.Get().ConfigGk.RetailStoreId,
WorkstationId = Entorno<EntornoGK>.Instancia.get().ConfigGk.WorkstationId, WorkstationId = Entorno<EntornoGK>.Instancia.Get().ConfigGk.WorkstationId,
WorkstationAddress = Entorno<EntornoGK>.Instancia.get().ConfigGk.WorkstationAddress, WorkstationAddress = Entorno<EntornoGK>.Instancia.Get().ConfigGk.WorkstationAddress,
WorkstationTypeCode = Entorno<EntornoGK>.Instancia.get().ConfigGk.WorkstationTypeCode, WorkstationTypeCode = Entorno<EntornoGK>.Instancia.Get().ConfigGk.WorkstationTypeCode,
LoginName = Entorno<EntornoGK>.Instancia.get().ConfigGk.LoginName, LoginName = Entorno<EntornoGK>.Instancia.Get().ConfigGk.LoginName,
Password = Entorno<EntornoGK>.Instancia.get().ConfigGk.Password, Password = Entorno<EntornoGK>.Instancia.Get().ConfigGk.Password,
TrainingMode = false, TrainingMode = false,
FinalizeControlTransactionFlag = false, FinalizeControlTransactionFlag = false,
UseLoginTypeTechnicalForLoginManager = false, UseLoginTypeTechnicalForLoginManager = false,
...@@ -82,8 +82,8 @@ namespace gatewayGK.ComandosGk ...@@ -82,8 +82,8 @@ namespace gatewayGK.ComandosGk
{ {
TillDoKey = new TillDoKey TillDoKey = new TillDoKey
{ {
BusinessUnitGroupID = Entorno<EntornoGK>.Instancia.get().ConfigGk.BusinessUnitGroupID, BusinessUnitGroupID = Entorno<EntornoGK>.Instancia.Get().ConfigGk.BusinessUnitGroupID,
TillID = Entorno<EntornoGK>.Instancia.get().ConfigGk.TillID TillID = Entorno<EntornoGK>.Instancia.Get().ConfigGk.TillID
} }
} }
}; };
...@@ -120,9 +120,9 @@ namespace gatewayGK.ComandosGk ...@@ -120,9 +120,9 @@ namespace gatewayGK.ComandosGk
var operatorID = autenticacionResp.primaryEntry.transaction.operatorID; var operatorID = autenticacionResp.primaryEntry.transaction.operatorID;
var posSessionId = autenticacionResp.posSessionId.id; var posSessionId = autenticacionResp.posSessionId.id;
// Salvar Transaccion y id de la session. // Salvar Transaccion y id de la session.
Entorno<EntornoGK>.Instancia.get().posSessionId = posSessionId; Entorno<EntornoGK>.Instancia.Get().posSessionId = posSessionId;
Log.Information("<< GK login:operatorID {operatorID}, transactionId {transactionId}, posSessionId {posSessionId}", Log.Information("<< GK login:operatorID {operatorID}, transactionId {transactionId}, posSessionId {posSessionId}",
operatorID, transactionId, Entorno<EntornoGK>.Instancia.get().posSessionId); operatorID, transactionId, Entorno<EntornoGK>.Instancia.Get().posSessionId);
// Respuestas a SCO. // Respuestas a SCO.
var posbcStatus1 = new POSBCStatusEvent(1, TipoMensaje.Event, "INFO", "CONNECTING_TO_POS", "Connecting to POS system"); var posbcStatus1 = new POSBCStatusEvent(1, TipoMensaje.Event, "INFO", "CONNECTING_TO_POS", "Connecting to POS system");
......
...@@ -30,7 +30,7 @@ namespace gatewayGK.ComandosGk ...@@ -30,7 +30,7 @@ namespace gatewayGK.ComandosGk
/// <summary> /// <summary>
/// Url servicio autenticación Gk. /// Url servicio autenticación Gk.
/// </summary> /// </summary>
private readonly string _urlRequest = Entorno<EntornoGK>.Instancia.get().UrlBase private readonly string _urlRequest = Entorno<EntornoGK>.Instancia.Get().UrlBase
+ "/com.gk_software.pos.api.service.subtotal.SubtotalService/processSubtotalCalculation"; + "/com.gk_software.pos.api.service.subtotal.SubtotalService/processSubtotalCalculation";
/// <summary> /// <summary>
...@@ -96,7 +96,7 @@ namespace gatewayGK.ComandosGk ...@@ -96,7 +96,7 @@ namespace gatewayGK.ComandosGk
MaxTimeout = -1, MaxTimeout = -1,
RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
}; };
string sessionId = Entorno<EntornoGK>.Instancia.get().posSessionId; string sessionId = Entorno<EntornoGK>.Instancia.Get().posSessionId;
string cookieValue = $"sessionid={sessionId}"; string cookieValue = $"sessionid={sessionId}";
var client = new RestClient(options); var client = new RestClient(options);
...@@ -289,7 +289,7 @@ namespace gatewayGK.ComandosGk ...@@ -289,7 +289,7 @@ namespace gatewayGK.ComandosGk
} }
} }
Entorno<EntornoGK>.Instancia.get().TransactionID = transactionId; Entorno<EntornoGK>.Instancia.Get().TransactionID = transactionId;
Log.Information("-------------------------------------------------------------------------------------------------------------------------"); Log.Information("-------------------------------------------------------------------------------------------------------------------------");
Log.Information(String.Format("\t\tSUBTOTAL: {0,12:N2} -- SUBTOTAL_DISCOUNT: {1,12:N2} -- TOTAL: {2,12:N2}", Log.Information(String.Format("\t\tSUBTOTAL: {0,12:N2} -- SUBTOTAL_DISCOUNT: {1,12:N2} -- TOTAL: {2,12:N2}",
subtotal, subtotalDcto, total)); subtotal, subtotalDcto, total));
......
...@@ -20,7 +20,7 @@ namespace gatewayGK.ComandosGk ...@@ -20,7 +20,7 @@ namespace gatewayGK.ComandosGk
/// DTO con solicitud. /// DTO con solicitud.
/// </summary> /// </summary>
public TerminateRequestDTO Destroy { get; private set; } public TerminateRequestDTO Destroy { get; private set; }
private string _urlLogout = Entorno<EntornoGK>.Instancia.get().UrlBase private string _urlLogout = Entorno<EntornoGK>.Instancia.Get().UrlBase
+ "/com.gk_software.pos.api.service.session.PosSessionService/logout"; + "/com.gk_software.pos.api.service.session.PosSessionService/logout";
/// <summary> /// <summary>
...@@ -32,7 +32,7 @@ namespace gatewayGK.ComandosGk ...@@ -32,7 +32,7 @@ namespace gatewayGK.ComandosGk
var requestId = Destroy.DestroySession; var requestId = Destroy.DestroySession;
// --- cliente rest. // --- cliente rest.
string sessionId = Entorno<EntornoGK>.Instancia.get().posSessionId; string sessionId = Entorno<EntornoGK>.Instancia.Get().posSessionId;
var options = new RestClientOptions() var options = new RestClientOptions()
{ {
// TODO manejar el timeout como un parámetro de configuración. // TODO manejar el timeout como un parámetro de configuración.
...@@ -93,7 +93,7 @@ namespace gatewayGK.ComandosGk ...@@ -93,7 +93,7 @@ namespace gatewayGK.ComandosGk
.GetBoolean(); .GetBoolean();
if (success) if (success)
Entorno<EntornoGK>.Instancia.get().posSessionId = ""; Entorno<EntornoGK>.Instancia.Get().posSessionId = "";
Log.Information("<< GK logout - success {success}, transactionID {transactionID}", Log.Information("<< GK logout - success {success}, transactionID {transactionID}",
success, transactionID); success, transactionID);
......
...@@ -32,7 +32,7 @@ namespace gatewayGK.ComandosGk ...@@ -32,7 +32,7 @@ namespace gatewayGK.ComandosGk
/// <summary> /// <summary>
/// Url servicio autenticación Gk. /// Url servicio autenticación Gk.
/// </summary> /// </summary>
private readonly string _urlRequest = Entorno<EntornoGK>.Instancia.get().UrlBase private readonly string _urlRequest = Entorno<EntornoGK>.Instancia.Get().UrlBase
+ "/com.gk_software.pos.api.service.payment.PaymentService/updateTerminalTenderAuthorization"; + "/com.gk_software.pos.api.service.payment.PaymentService/updateTerminalTenderAuthorization";
/// <summary> /// <summary>
...@@ -181,7 +181,7 @@ namespace gatewayGK.ComandosGk ...@@ -181,7 +181,7 @@ namespace gatewayGK.ComandosGk
); );
ComGkSoftwareGkrApiServerMdCurrencyDtoDomCurrencyDOKey currencyKey = new( ComGkSoftwareGkrApiServerMdCurrencyDtoDomCurrencyDOKey currencyKey = new(
businessUnitGroupID: Entorno<EntornoGK>.Instancia.get().BusinessUnitGroupID, businessUnitGroupID: Entorno<EntornoGK>.Instancia.Get().BusinessUnitGroupID,
isocurrencyCode: "COP" isocurrencyCode: "COP"
); );
...@@ -191,7 +191,7 @@ namespace gatewayGK.ComandosGk ...@@ -191,7 +191,7 @@ namespace gatewayGK.ComandosGk
); );
ComGkSoftwareGkrApiServerMdTenderDtoDomTenderDOKey tenderKey = new( ComGkSoftwareGkrApiServerMdTenderDtoDomTenderDOKey tenderKey = new(
businessUnitGroupID: Entorno<EntornoGK>.Instancia.get().BusinessUnitGroupID, businessUnitGroupID: Entorno<EntornoGK>.Instancia.Get().BusinessUnitGroupID,
tenderTypeCode: "ZTTE" tenderTypeCode: "ZTTE"
); );
...@@ -204,7 +204,7 @@ namespace gatewayGK.ComandosGk ...@@ -204,7 +204,7 @@ namespace gatewayGK.ComandosGk
); );
ComGkSoftwarePosApiModelDomAppServicesTransactionTenderAuthorizationKey tenderAuthorizationKey = new( ComGkSoftwarePosApiModelDomAppServicesTransactionTenderAuthorizationKey tenderAuthorizationKey = new(
businessUnitGroupID: Entorno<EntornoGK>.Instancia.get().BusinessUnitGroupID, businessUnitGroupID: Entorno<EntornoGK>.Instancia.Get().BusinessUnitGroupID,
transactionID: "", // TODO - fijar el correcto. transactionID: "", // TODO - fijar el correcto.
tenderAuthorizationSequenceNumber: 0 tenderAuthorizationSequenceNumber: 0
); );
...@@ -234,7 +234,7 @@ namespace gatewayGK.ComandosGk ...@@ -234,7 +234,7 @@ namespace gatewayGK.ComandosGk
MaxTimeout = -1, MaxTimeout = -1,
RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
}; };
string sessionId = Entorno<EntornoGK>.Instancia.get().posSessionId; string sessionId = Entorno<EntornoGK>.Instancia.Get().posSessionId;
string cookieValue = $"sessionid={sessionId}"; string cookieValue = $"sessionid={sessionId}";
var client = new RestClient(options); var client = new RestClient(options);
...@@ -426,7 +426,7 @@ namespace gatewayGK.ComandosGk ...@@ -426,7 +426,7 @@ namespace gatewayGK.ComandosGk
} }
} }
Entorno<EntornoGK>.Instancia.get().TransactionID = transactionId; Entorno<EntornoGK>.Instancia.Get().TransactionID = transactionId;
Log.Information("-------------------------------------------------------------------------------------------------------------------------"); Log.Information("-------------------------------------------------------------------------------------------------------------------------");
Log.Information(String.Format("\t\tSUBTOTAL: {0,12:N2} -- SUBTOTAL_DISCOUNT: {1,12:N2} -- TOTAL: {2,12:N2}", Log.Information(String.Format("\t\tSUBTOTAL: {0,12:N2} -- SUBTOTAL_DISCOUNT: {1,12:N2} -- TOTAL: {2,12:N2}",
subtotal, subtotalDcto, total)); subtotal, subtotalDcto, total));
......
/// <summary>
/// Clase que representa los parámetros de configuración de la aplicación
/// registrados en el archivo appsettings.json asociados a POSBC.
/// </summary>
public sealed class ConfigPOSBCTest
{
public required string IpPOSBC { get; set; } = "127.0.0.1";
public required int PortPOSBC { get; set; } = 6698;
public override string ToString()
{
return base.ToString() + $" - IpPOSBC: '{IpPOSBC}', PortPOSBC: '{PortPOSBC}' ";
}
}
\ No newline at end of file
...@@ -11,13 +11,12 @@ public class DirectorioCmdsFactory ...@@ -11,13 +11,12 @@ public class DirectorioCmdsFactory
return tipoPOS switch return tipoPOS switch
{ {
"ECO" => DispensaDirectorioCmdsPruebas.Dispensa(), "ECO" => DispensaDirectorioCmdsPruebas.Dispensa(),
//"ECO_POSBC" => throw new NotImplementedException(), "POSBC" => DispensaDirectorioCmdsPOSBC.Dispensa(),
"ECO_POSBC" => DispensaDirectorioCmdsGKPruebas.Dispensa(), "POSBCTest" => DispensaDirectorioCmdsPOSBCTest.Dispensa(),
"POSBC" => throw new NotImplementedException(),
"evapos" => DispensaDirectorioCmdsEvaPOS.Dispensa(), "evapos" => DispensaDirectorioCmdsEvaPOS.Dispensa(),
"gk" => DispensaDirectorioCmdsGK.Dispensa(), "gk" => DispensaDirectorioCmdsGK.Dispensa(),
"gk_test" => DispensaDirectorioCmdsGKPruebas.Dispensa(), "gk_test" => DispensaDirectorioCmdsGKPruebas.Dispensa(),
_ => throw new ArgumentException("Valor no reconocido en archivo configuración, parámetro 'POS', valor encontrado {pos}.", tipoPOS), _ => throw new ArgumentException($"Valor no reconocido en archivo configuración, parámetro 'POS', con valor {tipoPOS}.", tipoPOS),
}; };
} }
} }
using Gateway.Comandos.POSBC;
using Serilog;
/// <summary>
/// Instancia directorio de comandos POSBCTest
/// CUIDADO: Distinge los comandos por namespace.
/// </summary>
public class DispensaDirectorioCmdsPOSBC: IDispensaDirectorioCmds
{
/// <summary>
/// Retorna directorio de comandos instanciado y poblado de
/// comandos.
/// </summary>
public static CreaDirectorioCmds Dispensa()
{
Log.Information("Instancia comandos POSBCTest.");
return new IniciaDirectorioCmds()
.AgregaCmd(new InitializeRequestCmd())
.DirectorioCmds;
}
}
\ No newline at end of file
using Gateway.Comandos.POSBCTest;
using Serilog;
/// <summary>
/// Instancia directorio de comandos POSBCTest
/// CUIDADO: Distinge los comandos por namespace.
/// </summary>
public class DispensaDirectorioCmdsPOSBCTest : IDispensaDirectorioCmds
{
/// <summary>
/// Retorna directorio de comandos instanciado y poblado de
/// comandos.
/// </summary>
public static CreaDirectorioCmds Dispensa()
{
Log.Information("Instancia comandos POSBCTest.");
return new IniciaDirectorioCmds()
.AgregaCmd(new InitializeRequestCmd())
.DirectorioCmds;
}
}
\ No newline at end of file
...@@ -32,7 +32,7 @@ namespace GatewaySCO ...@@ -32,7 +32,7 @@ namespace GatewaySCO
/// <summary> /// <summary>
/// Obtener datos de entorno. /// Obtener datos de entorno.
/// </summary> /// </summary>
public T get() public T Get()
{ {
if (_datos == null) if (_datos == null)
{ {
...@@ -44,7 +44,7 @@ namespace GatewaySCO ...@@ -44,7 +44,7 @@ namespace GatewaySCO
/// <summary> /// <summary>
/// Fijar datos de entorno. /// Fijar datos de entorno.
/// </summary> /// </summary>
public void set(T datos) public void Set(T datos)
{ {
_datos = datos; _datos = datos;
} }
......
...@@ -13,5 +13,5 @@ public class EntornoPOSBC ...@@ -13,5 +13,5 @@ public class EntornoPOSBC
/// <summary> /// <summary>
/// Socket en uso de conexión al POSBC. /// Socket en uso de conexión al POSBC.
/// </summary> /// </summary>
public ClienteServidorPOSBC ClientePOSBC { get; set; } public ClienteServidorPOSBC ClientePOSBC { get; set; } = null;
} }
\ No newline at end of file
...@@ -20,16 +20,37 @@ namespace GatewaySCO ...@@ -20,16 +20,37 @@ namespace GatewaySCO
{ {
public static async Task Main(string[] args) public static async Task Main(string[] args)
{ {
Console.WriteLine("*** Gateway SCO - Servidor: procesa peticiones de Toshiba CHEC ***"); Config(args);
ProgramGatewaySCO program = new(); TcpGateway gateway = null;
program.LeeActivaConfiguracion(args); switch (Entorno<Config>.Instancia.Get().POS)
{
TcpGateway gateway = new TcpGateway(); case "POSBC":
gateway = new(
Entorno<Config>.Instancia.Get().PortGateway,
Entorno<ConfigPOSBC>.Instancia.Get().IpPOSBC,
Entorno<ConfigPOSBC>.Instancia.Get().PortPOSBC);
break;
case "POSBCTest":
gateway = new(
Entorno<Config>.Instancia.Get().PortGateway,
Entorno<ConfigPOSBCTest>.Instancia.Get().IpPOSBC,
Entorno<ConfigPOSBCTest>.Instancia.Get().PortPOSBC);
break;
default:
throw new Exception("Tipo de POS en sección Config de archivo de configuración no reconocido.");
}
await gateway.Start(); await gateway.Start();
} }
public void LeeActivaConfiguracion(string[] args) /// <summary>
/// Lee configuración de archivo appsettings.json
/// La configuración se almacen en clase Entorno para consulta desde
/// cualquier parte del programa.
/// </summary>
/// <param name="args"></param>
/// <exception cref="ApplicationException"></exception>
public static void Config(string[] args)
{ {
// TODO - opción de incluir la activación en la cadena de configuración. // TODO - opción de incluir la activación en la cadena de configuración.
...@@ -52,7 +73,27 @@ namespace GatewaySCO ...@@ -52,7 +73,27 @@ namespace GatewaySCO
Config config = configBuilder.GetRequiredSection("GatewayConfig").Get<Config>() Config config = configBuilder.GetRequiredSection("GatewayConfig").Get<Config>()
?? throw new ApplicationException("Archivo de configuración sin sección 'GatewayConfig'."); ?? throw new ApplicationException("Archivo de configuración sin sección 'GatewayConfig'.");
Log.Information(config.ToString()); Log.Information(config.ToString());
} Entorno<Config>.Instancia.Set(config);
if (config.POS == "POSBC")
{
ConfigPOSBC configPOSBC = configBuilder.GetRequiredSection("POSBC").Get<ConfigPOSBC>()
?? throw new ApplicationException("Archivo de configuración sin sección 'POSBC'.");
Log.Information(configPOSBC.ToString());
Entorno<ConfigPOSBC>.Instancia.Set(configPOSBC);
Entorno<ConfigPOSBC>.Instancia.Get().IpPOSBC = configPOSBC.IpPOSBC;
Entorno<ConfigPOSBC>.Instancia.Get().PortPOSBC = configPOSBC.PortPOSBC;
}
if (config.POS == "POSBCTest")
{
ConfigPOSBCTest configPOSBCTest = configBuilder.GetRequiredSection("POSBCTest").Get<ConfigPOSBCTest>()
?? throw new ApplicationException("Archivo de configuración sin sección 'POSBCTest'.");
Log.Information(configPOSBCTest.ToString());
Entorno<ConfigPOSBCTest>.Instancia.Set(configPOSBCTest);
Entorno<ConfigPOSBCTest>.Instancia.Get().IpPOSBC = configPOSBCTest.IpPOSBC;
Entorno<ConfigPOSBCTest>.Instancia.Get().PortPOSBC = configPOSBCTest.PortPOSBC;
}
}
} }
} }
...@@ -286,7 +286,7 @@ namespace EvaPosSCOSrv ...@@ -286,7 +286,7 @@ namespace EvaPosSCOSrv
} }
Log.Information("Nuevo mensaje {bytes} bytes.", bytesLeidos); Log.Information("Nuevo mensaje {bytes} bytes.", bytesLeidos);
string tipoPOS = Entorno<Config>.Instancia.get().POS; string tipoPOS = Entorno<Config>.Instancia.Get().POS;
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
// Procesa mensajes desde CHEC según la modalida de configuración del Gateway // Procesa mensajes desde CHEC según la modalida de configuración del Gateway
...@@ -310,7 +310,7 @@ namespace EvaPosSCOSrv ...@@ -310,7 +310,7 @@ namespace EvaPosSCOSrv
continua = false; continua = false;
} }
byte[] mensajeSalida = Entorno<EntornoPOSBC>.Instancia.get().ClientePOSBC.EnviaRecibe(mensajeEntrada); byte[] mensajeSalida = Entorno<EntornoPOSBC>.Instancia.Get().ClientePOSBC.EnviaRecibe(mensajeEntrada);
// Remitir respuestas sin cambio a CHEC. // Remitir respuestas sin cambio a CHEC.
socket.Send(mensajeSalida, 0, mensajeSalida.Length, SocketFlags.None); socket.Send(mensajeSalida, 0, mensajeSalida.Length, SocketFlags.None);
...@@ -370,7 +370,7 @@ namespace EvaPosSCOSrv ...@@ -370,7 +370,7 @@ namespace EvaPosSCOSrv
/// Clase que controla el nivel básico de entrada y salida de mensajes. /// Clase que controla el nivel básico de entrada y salida de mensajes.
/// Extrae la información del mensaje, limpiando la información de control. /// Extrae la información del mensaje, limpiando la información de control.
/// </summary> /// </summary>
class Sesion public class Sesion
{ {
static ILogger log = Log.ForContext<Sesion>(); static ILogger log = Log.ForContext<Sesion>();
readonly static bool _isDebug = Log.IsEnabled(LogEventLevel.Debug); readonly static bool _isDebug = Log.IsEnabled(LogEventLevel.Debug);
...@@ -381,11 +381,6 @@ namespace EvaPosSCOSrv ...@@ -381,11 +381,6 @@ namespace EvaPosSCOSrv
/// </summary> /// </summary>
public static TramaSCO Entrada(byte[] buffer, int nroBytes) public static TramaSCO Entrada(byte[] buffer, int nroBytes)
{ {
if (_isDebug)
{
log.Debug("Buffer entrada: >>{subBuffer}<<", buffer);
}
TramaSCO trama = new() TramaSCO trama = new()
{ {
Longitud = Convert.ToUInt32(nroBytes) Longitud = Convert.ToUInt32(nroBytes)
...@@ -413,7 +408,7 @@ namespace EvaPosSCOSrv ...@@ -413,7 +408,7 @@ namespace EvaPosSCOSrv
// Extraer contenido. // Extraer contenido.
trama.TextoXML = datos.Substring(inicioXML); trama.TextoXML = datos.Substring(inicioXML);
log.Information("{contenido}", trama.TextoXML); log.Information("xml:\n{contenido}", trama.TextoXML);
return trama; return trama;
} }
...@@ -449,7 +444,7 @@ namespace EvaPosSCOSrv ...@@ -449,7 +444,7 @@ namespace EvaPosSCOSrv
/// <summary> /// <summary>
/// Clase que interpreta los mensajes y los transforma en objetos DTO. /// Clase que interpreta los mensajes y los transforma en objetos DTO.
/// </summary> /// </summary>
class Presentacion public class Presentacion
{ {
DirectorioAdaptadoresDTO _adaptadores; DirectorioAdaptadoresDTO _adaptadores;
CreaDirectorioCmds _comandos; CreaDirectorioCmds _comandos;
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment