Proceso completo de solicitud de activacion

This commit is contained in:
2026-01-29 12:57:51 +01:00
parent 4acc04fb51
commit 68ae3aea57
14 changed files with 138 additions and 107 deletions

View File

@@ -118,11 +118,7 @@ export class JWTService {
return token
}
public async getAccessToken() {
if (this.authToken != undefined && !this.authToken.isExpired()) {
console.warn("Se está intentado conseguir un token sin expirar el anterior")
}
public async getNewTokens() {
const bodyWithtoken = {
...DEFAULT_BODY,
client_assertion: this.buildJwtBody()
@@ -151,6 +147,25 @@ export class JWTService {
}
}
public async getAccessToken() {
// Caso 1: El token actual es valido
if (this.authToken != undefined && !this.authToken.isExpired()) {
return this.authToken
}
// Caso 2: El token ha expirado pero se puede refrescar
if (this.authToken?.isExpired() && this.refreshToken != undefined && !this.refreshToken.isExpired()) {
await this.tryRefreshToken()
}
// Caso 3: Ningún token es valido
await this.getNewTokens()
if (this.authToken == undefined) throw new Error("Error obteniendo tokens de auth")
return this.authToken
}
public async tryRefreshToken() {
if (this.refreshToken == undefined) throw new Error("El refreshToken no está definido")
if (this.refreshToken.isExpired()) throw new Error("El refreshToken ha expirado")

View File

@@ -1,7 +1,14 @@
import { EventBus } from "#shared/domain/EventBus.port";
import { ConsumeMessage } from "amqplib";
import { SimUseCases } from "./Sim.usecases";
import { SimEvents } from "#shared/domain/SimEvents";
/**
* La clase usa generadores de funciones para mantener el contexto
* el proceso se hace en 2 partes:
* Controlador - handlers -> Router -> Ejecucion
*
*/
export class SimController {
private eventBus: EventBus;
private useCases: SimUseCases
@@ -15,33 +22,61 @@ export class SimController {
}
public async activateSim(msg: ConsumeMessage | null) {
return async () => {
if (!this.validateActivationMsg(msg)) {
throw new Error("Error consumiendo el mensaje no es valido")
}
const msgData = Buffer.from(JSON.parse(msg?.content.toString("utf-8") || "{}").data)
console.log("Mensaje procesado", String(msgData))
private decodeMsg(msg: ConsumeMessage): object | undefined {
if (msg.content == undefined) {
console.warn('[Sim.controller] Mensaje vacío');
return undefined;
}
// Caso de uso de activaciones
await this.useCases.activate({
dueDate: new Date().toString(),
identifier: {
identifierType: "ICCID",
identifiers: ["1234"]
}
})()
// TODO: comprobar el resultado de la opreacion
this.eventBus.ack(msg!)
try {
// Convertir el Buffer a String (UTF-8)
const contentJson = JSON.parse(Buffer.from(msg.content).toString('utf8'))
return contentJson;
} catch (error) {
console.error('Error al decodificar JSON:', error);
// Aquí podrías decidir devolver el string crudo o null
return undefined;
}
}
public async pauseSim(msg: ConsumeMessage | null) {
return async () => {
public activateSim() {
return async (msg: ConsumeMessage) => {
if (!this.validateActivationMsg(msg)) {
throw new Error("Error consumiendo el mensaje no es valido")
}
const msgData = Buffer.from(JSON.parse(msg?.content.toString("utf-8") || "{}").data)
const msgData = this.decodeMsg(msg) as SimEvents.activation
if (msgData == undefined || msgData.payload == undefined) Promise.reject("Mensaje invalido")
console.log("Mensaje procesado", msgData?.toString())
// TODO: Añadir un validador del mensaje
const iccid = msgData.payload.iccid
try {
// Caso de uso de activaciones
await this.useCases.activate({
dueDate: this.genDueDate(2 * 60).toISOString(),
identifier: {
identifierType: "ICCID",
identifiers: [iccid]
}
})()
this.eventBus.ack(msg)
} catch (e) {
this.eventBus.nack(msg)
}
}
}
public pauseSim() {
return async (msg: ConsumeMessage) => {
if (!this.validateActivationMsg(msg)) {
throw new Error("Error consumiendo el mensaje no es valido")
}
const msgData = this.decodeMsg(msg)
if (msgData == undefined) Promise.reject("Mensaje invalido")
console.log("Mensaje procesado", String(msgData))
}
}
@@ -54,4 +89,10 @@ export class SimController {
if (msg == undefined) return false;
return true;
}
private genDueDate(secondsDue: number) {
const now = Date.now() + secondsDue * 1000
const dueDate = new Date(now)
return dueDate
}
}

View File

@@ -1,48 +1,62 @@
/**
* Dirige cada mensaje dependiendo de el tipo de accion que contenga
* Dirige cada mensaje dependiendo de el tipo de acción que contenga
* Podría hacerse con varias colas, pero así se controla mejor que
* las operaciones se hagan de 1 en 1.
*/
import { ConsumeMessage } from "amqplib";
import { SimController } from "./Sim.controller";
export class SimRouter {
private simController: SimController
private readonly routes: Map<string, (m: ConsumeMessage) => Promise<any>>;
private routeMap: Map<string, (m: ConsumeMessage | null) => void> = new Map()
constructor(simController: SimController) {
this.simController = simController
// No me gusta que se defina en el constructor
this.routeMap = new Map([
["activate", this.simController.activateSim],
["pause", this.simController.pauseSim],
])
this.route = this.route.bind(this)
constructor(private readonly simController: SimController) {
this.routes = new Map([
["activate", this.simController.activateSim()],
["pause", this.simController.pauseSim()],
]);
}
public route(msg: ConsumeMessage | null) {
if (msg == undefined) {
console.error("Mensaje vacio")
/**
* Enruta el mensaje a la acción correspondiente basándose en la routing key
*/
public route = async (msg: ConsumeMessage | null): Promise<void> => {
if (!msg) {
console.error("[Router] Mensaje vacío");
return;
}
const routingKey = msg.fields.routingKey
const action = routingKey.split(".")[2]
const action = this.extractAction(msg);
if (action == undefined) {
console.error("La routing key no tiene una accion definida")
console.error(msg.fields)
if (!action) {
console.error("[Router] La routing key no tiene una acción definida", msg.fields.routingKey);
return;
}
const accionEjecutable = this.routeMap.get(action)
const handler = this.routes.get(action);
if (accionEjecutable == undefined) {
console.error("La accion del mensaje no tiene un controlador asociado")
} else {
console.log("Ejecutado operacion", action)
if (!handler) {
console.error(`[Router] La acción '${action}' no tiene un controlador asociado`);
return;
}
try {
console.log("[Router] Ejecutando operación:", action);
// El controlador devuelve una función (thunk) que debe ser ejecutada
const executeParams = await handler(msg);
if (typeof executeParams === "function") {
await executeParams();
}
} catch (error) {
console.error(`[Router] Error al ejecutar la operación '${action}':`, error);
}
};
private extractAction(msg: ConsumeMessage): string | undefined {
// Se asume que la acción está en la tercera posición: domain.compañia.accion
return msg.fields.routingKey.split(".")[2];
}
}

View File

@@ -15,7 +15,7 @@ export class SimUseCases {
}
public activate(activationData: ActivationData) {
const OPERATION_URL = "/actions/preactivate"
const OPERATION_URL = "/actions/preactivateLine"
return async () => {
const req = this.httpClient.client.post(OPERATION_URL, {
...activationData
@@ -23,7 +23,7 @@ export class SimUseCases {
try {
const e = await req
console.log("Activacion con exito", e.data)
console.log("Activacion con exito", e.data.response)
} catch (error) {
console.error("Error activando ", error)
}

View File

@@ -1,27 +0,0 @@
import { ActivationData } from "#domain/DTOs/objeniousapi"
import { HttpClient } from "#shared/infrastructure/HTTPClient"
export class SimActivationUseCase {
private httpClient: HttpClient
constructor(args: {
httpClient: HttpClient
}) {
this.httpClient = args.httpClient
}
public async run(activationData: ActivationData,) {
const req = this.httpClient.client.post("/actions/preactivate", {
...activationData
})
try {
const e = await req
console.log("Activacion con exito", e.data)
} catch (error) {
console.error("Error activando ", error)
}
}
}