From e329b369338c71cf2dfe64e86521ae9e43a2f2c5 Mon Sep 17 00:00:00 2001 From: Alvar San Martin Date: Tue, 24 Feb 2026 11:27:47 +0100 Subject: [PATCH] Orders para test y flujo de migraciones mas simple --- deployment/database/base/01-ordenes-sim.sql | 0 deployment/database/base/03-versions.sql | 16 - deployment/database/esquema_final_v2.0.0.sql | 292 ---------------- deployment/database/init.sql | 322 +++--------------- .../database/migrations/0.1.0_objenious.sql | 48 +++ .../migrations/1.1.0_webhook-order.sql | 10 + deployment/local/docker/docker-compose.yaml | 3 + package.json | 1 + .../aplication/Sim.controller.ts | 15 +- .../aplication/Sim.usecases.ts | 54 ++- packages/sim-shared/domain/DomainEvent.ts | 6 +- packages/sim-shared/domain/EventBus.port.ts | 2 +- .../infrastructure/RabbitMQEventBus.ts | 33 +- run.local.sh | 4 +- yarn.lock | 10 + 15 files changed, 201 insertions(+), 615 deletions(-) delete mode 100644 deployment/database/base/01-ordenes-sim.sql delete mode 100644 deployment/database/base/03-versions.sql delete mode 100644 deployment/database/esquema_final_v2.0.0.sql create mode 100644 deployment/database/migrations/0.1.0_objenious.sql create mode 100644 deployment/database/migrations/1.1.0_webhook-order.sql diff --git a/deployment/database/base/01-ordenes-sim.sql b/deployment/database/base/01-ordenes-sim.sql deleted file mode 100644 index e69de29..0000000 diff --git a/deployment/database/base/03-versions.sql b/deployment/database/base/03-versions.sql deleted file mode 100644 index 978f021..0000000 --- a/deployment/database/base/03-versions.sql +++ /dev/null @@ -1,16 +0,0 @@ -CREATE TABLE IF NOT EXISTS db_versions ( - id BIGINT BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, - version TEXT, -- version semantica x.x.x - notes TEXT, - creation_date TIMESTAMP NOT NULL DEFAULT (now() at time zone 'utc'), - stable BOOLEAN DEFAULT FALSE -- Si la version ha sido testada y se puede desplegar -); - -INSERT INTO db_versions ( - version, - notes -) -VALUES ( - '0.1.0', - 'Versión base' -); diff --git a/deployment/database/esquema_final_v2.0.0.sql b/deployment/database/esquema_final_v2.0.0.sql deleted file mode 100644 index 2f441bc..0000000 --- a/deployment/database/esquema_final_v2.0.0.sql +++ /dev/null @@ -1,292 +0,0 @@ --- --- PostgreSQL database dump --- - -\restrict 8rNdhulAsfz5yOkZrPZ5f3riDYVBHnFPTcb2MraxKbPVyPsdTm81R2jsJppwk7u - --- Dumped from database version 16.11 (Ubuntu 16.11-0ubuntu0.24.04.1) --- Dumped by pg_dump version 16.11 (Ubuntu 16.11-0ubuntu0.24.04.1) - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- Name: order_status; Type: TYPE; Schema: public; Owner: - --- - -CREATE TYPE public.order_status AS ENUM ( - 'pending', - 'running', - 'finished', - 'failed', - 'dlx' -); - - --- --- Name: order_types; Type: TYPE; Schema: public; Owner: - --- - -CREATE TYPE public.order_types AS ENUM ( - 'activate', - 'preactivate', - 'cancel', - 'pause', - 'reactivate', - 'unknown' -); - - --- --- Name: status_enum; Type: TYPE; Schema: public; Owner: - --- - -CREATE TYPE public.status_enum AS ENUM ( - 'noRequestID', - 'noMassID', - 'running', - 'finished', - 'error', - 'other' -); - - -SET default_tablespace = ''; - -SET default_table_access_method = heap; - --- --- Name: objenious_operation; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.objenious_operation ( - id bigint NOT NULL, - retry_count integer DEFAULT 0, - max_retry integer DEFAULT 5, - max_date_retry timestamp without time zone, - iccids text, - request_id text, - mass_action_id text, - operation text NOT NULL, - start_date timestamp with time zone DEFAULT now() NOT NULL, - last_change_date timestamp with time zone DEFAULT now() NOT NULL, - end_date timestamp with time zone, - error text, - status public.status_enum, - objenious_status text -); - - --- --- Name: objenious_operation_change; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.objenious_operation_change ( - id bigint NOT NULL, - operation_id bigint, - creation_date timestamp with time zone DEFAULT now() NOT NULL, - error text, - new_status public.status_enum, - previous_status public.status_enum, - new_objenious_status text, - previous_objenious_status text, - new_request_id text, - new_mass_action_id text -); - - --- --- Name: objenious_operation_change_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.objenious_operation_change ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( - SEQUENCE NAME public.objenious_operation_change_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: objenious_operation_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.objenious_operation ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( - SEQUENCE NAME public.objenious_operation_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: order_history; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.order_history ( - id bigint NOT NULL, - order_id bigint NOT NULL, - previous_status public.order_status NOT NULL, - new_status public.order_status NOT NULL, - change_reason text, - change_date timestamp with time zone DEFAULT now() NOT NULL -); - - --- --- Name: order_history_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.order_history ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( - SEQUENCE NAME public.order_history_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: order_tracking; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.order_tracking ( - id bigint NOT NULL, - correlation_id character varying(255) NOT NULL, - exchange character varying(100), - routing_key character varying(100), - order_type public.order_types DEFAULT 'unknown'::public.order_types NOT NULL, - payload jsonb, - status public.order_status DEFAULT 'pending'::public.order_status NOT NULL, - retry_count integer DEFAULT 0, - error_message text, - error_stacktrace text, - start_date timestamp with time zone DEFAULT now() NOT NULL, - update_date timestamp with time zone DEFAULT now() NOT NULL, - finish_date timestamp with time zone -); - - --- --- Name: order_tracking_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.order_tracking ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( - SEQUENCE NAME public.order_tracking_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: objenious_operation_change objenious_operation_change_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.objenious_operation_change - ADD CONSTRAINT objenious_operation_change_pkey PRIMARY KEY (id); - - --- --- Name: objenious_operation objenious_operation_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.objenious_operation - ADD CONSTRAINT objenious_operation_pkey PRIMARY KEY (id); - - --- --- Name: order_history order_history_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.order_history - ADD CONSTRAINT order_history_pkey PRIMARY KEY (id); - - --- --- Name: order_tracking order_tracking_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.order_tracking - ADD CONSTRAINT order_tracking_pkey PRIMARY KEY (id); - - --- --- Name: idx_order_change_date; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX idx_order_change_date ON public.order_history USING btree (change_date); - - --- --- Name: idx_order_correlation; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX idx_order_correlation ON public.order_tracking USING btree (correlation_id); - - --- --- Name: idx_order_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX idx_order_id ON public.order_history USING btree (order_id); - - --- --- Name: operation_change; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX operation_change ON public.objenious_operation_change USING btree (operation_id); - - --- --- Name: pending_operations; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX pending_operations ON public.objenious_operation USING btree (start_date) WHERE (end_date IS NULL); - - --- --- Name: pending_orders; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX pending_orders ON public.order_tracking USING btree (start_date) WHERE (finish_date IS NULL); - - --- --- Name: objenious_operation_change fk_operation_id; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.objenious_operation_change - ADD CONSTRAINT fk_operation_id FOREIGN KEY (operation_id) REFERENCES public.objenious_operation(id); - - --- --- Name: order_history fk_order_id; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.order_history - ADD CONSTRAINT fk_order_id FOREIGN KEY (order_id) REFERENCES public.order_tracking(id) ON DELETE CASCADE; - - --- --- PostgreSQL database dump complete --- - -\unrestrict 8rNdhulAsfz5yOkZrPZ5f3riDYVBHnFPTcb2MraxKbPVyPsdTm81R2jsJppwk7u - diff --git a/deployment/database/init.sql b/deployment/database/init.sql index 6cc0e67..99c95dd 100644 --- a/deployment/database/init.sql +++ b/deployment/database/init.sql @@ -1,290 +1,48 @@ --- --- PostgreSQL database dump --- +CREATE TYPE status_enum AS ENUM ('noRequestID','noMassID','running','finished','error','other'); --- Dumped from database version 16.11 (Ubuntu 16.11-0ubuntu0.24.04.1) --- Dumped by pg_dump version 16.11 (Ubuntu 16.11-0ubuntu0.24.04.1) - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- Name: order_status; Type: TYPE; Schema: public; Owner: - --- - -CREATE TYPE public.order_status AS ENUM ( - 'pending', - 'running', - 'finished', - 'failed', - 'dlx' +-- Tabla para gestionar las peticiones de cambio de objenious. +-- Para una o mas lineas se pueden lanzar operacione que no sabemos +-- con certeza cuando van a terminar. +-- Estas tablas está fuertemente ligadas al sistema que usa la plataforma +-- de objenioius y no debe unsarse para otra compañia. +CREATE TABLE if not exists objenious_operation ( + id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + retry_count INT DEFAULT 0, -- No implementado en codigo + max_retry INT DEFAULT 5, -- No implementado en codigo + max_date_retry TIMESTAMP DEFAULT NULL, -- No implementado en codigo + iccids TEXT, + request_id TEXT, + mass_action_id TEXT, + operation TEXT NOT NULL, + start_date TIMESTAMP NOT NULL DEFAULT now(), + last_change_date TIMESTAMP NOT NULL DEFAULT now(), + end_date TIMESTAMP, + error TEXT, + status status_enum, + objenious_status TEXT ); +-- operaciones pendientes para revisar +CREATE INDEX IF NOT EXISTS pending_operations + ON objenious_operation(start_date) +WHERE end_date IS NULL; --- --- Name: order_types; Type: TYPE; Schema: public; Owner: - --- +CREATE TABLE if not exists objenious_operation_change ( + id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + operation_id BIGINT, + creation_date TIMESTAMP NOT NULL DEFAULT now(), + error TEXT, + new_status status_enum, + previous_status status_enum, + new_objenious_status TEXT, + previous_objenious_status TEXT, + new_request_id TEXT, + new_mass_action_id TEXT, -CREATE TYPE public.order_types AS ENUM ( - 'activate', - 'preactivate', - 'cancel', - 'pause', - 'reactivate', - 'unknown' + CONSTRAINT fk_operation_id + FOREIGN KEY(operation_id) REFERENCES objenious_operation(id) ); - --- --- Name: status_enum; Type: TYPE; Schema: public; Owner: - --- - -CREATE TYPE public.status_enum AS ENUM ( - 'noRequestID', - 'noMassID', - 'running', - 'finished', - 'error', - 'other' -); - - -SET default_tablespace = ''; - -SET default_table_access_method = heap; - --- --- Name: objenious_operation; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.objenious_operation ( - id bigint NOT NULL, - retry_count integer DEFAULT 0, - max_retry integer DEFAULT 5, - max_date_retry timestamp without time zone, - iccids text, - request_id text, - mass_action_id text, - operation text NOT NULL, - start_date timestamp with time zone DEFAULT now() NOT NULL, - last_change_date timestamp with time zone DEFAULT now() NOT NULL, - end_date timestamp with time zone, - error text, - status public.status_enum, - objenious_status text -); - - --- --- Name: objenious_operation_change; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.objenious_operation_change ( - id bigint NOT NULL, - operation_id bigint, - creation_date timestamp with time zone DEFAULT now() NOT NULL, - error text, - new_status public.status_enum, - previous_status public.status_enum, - new_objenious_status text, - previous_objenious_status text, - new_request_id text, - new_mass_action_id text -); - - --- --- Name: objenious_operation_change_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.objenious_operation_change ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( - SEQUENCE NAME public.objenious_operation_change_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: objenious_operation_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.objenious_operation ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( - SEQUENCE NAME public.objenious_operation_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: order_history; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.order_history ( - id bigint NOT NULL, - order_id bigint NOT NULL, - previous_status public.order_status NOT NULL, - new_status public.order_status NOT NULL, - change_reason text, - change_date timestamp with time zone DEFAULT now() NOT NULL -); - - --- --- Name: order_history_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.order_history ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( - SEQUENCE NAME public.order_history_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: order_tracking; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.order_tracking ( - id bigint NOT NULL, - correlation_id character varying(255) NOT NULL, - exchange character varying(100), - routing_key character varying(100), - order_type public.order_types DEFAULT 'unknown'::public.order_types NOT NULL, - payload jsonb, - status public.order_status DEFAULT 'pending'::public.order_status NOT NULL, - retry_count integer DEFAULT 0, - error_message text, - error_stacktrace text, - start_date timestamp with time zone DEFAULT now() NOT NULL, - update_date timestamp with time zone DEFAULT now() NOT NULL, - finish_date timestamp with time zone -); - - --- --- Name: order_tracking_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.order_tracking ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( - SEQUENCE NAME public.order_tracking_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: objenious_operation_change objenious_operation_change_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.objenious_operation_change - ADD CONSTRAINT objenious_operation_change_pkey PRIMARY KEY (id); - - --- --- Name: objenious_operation objenious_operation_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.objenious_operation - ADD CONSTRAINT objenious_operation_pkey PRIMARY KEY (id); - - --- --- Name: order_history order_history_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.order_history - ADD CONSTRAINT order_history_pkey PRIMARY KEY (id); - - --- --- Name: order_tracking order_tracking_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.order_tracking - ADD CONSTRAINT order_tracking_pkey PRIMARY KEY (id); - - --- --- Name: idx_order_change_date; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX idx_order_change_date ON public.order_history USING btree (change_date); - - --- --- Name: idx_order_correlation; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX idx_order_correlation ON public.order_tracking USING btree (correlation_id); - - --- --- Name: idx_order_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX idx_order_id ON public.order_history USING btree (order_id); - - --- --- Name: operation_change; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX operation_change ON public.objenious_operation_change USING btree (operation_id); - - --- --- Name: pending_operations; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX pending_operations ON public.objenious_operation USING btree (start_date) WHERE (end_date IS NULL); - - --- --- Name: pending_orders; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX pending_orders ON public.order_tracking USING btree (start_date) WHERE (finish_date IS NULL); - - --- --- Name: objenious_operation_change fk_operation_id; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.objenious_operation_change - ADD CONSTRAINT fk_operation_id FOREIGN KEY (operation_id) REFERENCES public.objenious_operation(id); - - --- --- Name: order_history fk_order_id; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.order_history - ADD CONSTRAINT fk_order_id FOREIGN KEY (order_id) REFERENCES public.order_tracking(id) ON DELETE CASCADE; - - --- --- PostgreSQL database dump complete --- - - +CREATE INDEX operation_change + ON objenious_operation_change(operation_id); diff --git a/deployment/database/migrations/0.1.0_objenious.sql b/deployment/database/migrations/0.1.0_objenious.sql new file mode 100644 index 0000000..99c95dd --- /dev/null +++ b/deployment/database/migrations/0.1.0_objenious.sql @@ -0,0 +1,48 @@ + +CREATE TYPE status_enum AS ENUM ('noRequestID','noMassID','running','finished','error','other'); + +-- Tabla para gestionar las peticiones de cambio de objenious. +-- Para una o mas lineas se pueden lanzar operacione que no sabemos +-- con certeza cuando van a terminar. +-- Estas tablas está fuertemente ligadas al sistema que usa la plataforma +-- de objenioius y no debe unsarse para otra compañia. +CREATE TABLE if not exists objenious_operation ( + id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + retry_count INT DEFAULT 0, -- No implementado en codigo + max_retry INT DEFAULT 5, -- No implementado en codigo + max_date_retry TIMESTAMP DEFAULT NULL, -- No implementado en codigo + iccids TEXT, + request_id TEXT, + mass_action_id TEXT, + operation TEXT NOT NULL, + start_date TIMESTAMP NOT NULL DEFAULT now(), + last_change_date TIMESTAMP NOT NULL DEFAULT now(), + end_date TIMESTAMP, + error TEXT, + status status_enum, + objenious_status TEXT +); + +-- operaciones pendientes para revisar +CREATE INDEX IF NOT EXISTS pending_operations + ON objenious_operation(start_date) +WHERE end_date IS NULL; + +CREATE TABLE if not exists objenious_operation_change ( + id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + operation_id BIGINT, + creation_date TIMESTAMP NOT NULL DEFAULT now(), + error TEXT, + new_status status_enum, + previous_status status_enum, + new_objenious_status TEXT, + previous_objenious_status TEXT, + new_request_id TEXT, + new_mass_action_id TEXT, + + CONSTRAINT fk_operation_id + FOREIGN KEY(operation_id) REFERENCES objenious_operation(id) +); + +CREATE INDEX operation_change + ON objenious_operation_change(operation_id); diff --git a/deployment/database/migrations/1.1.0_webhook-order.sql b/deployment/database/migrations/1.1.0_webhook-order.sql new file mode 100644 index 0000000..c925fe5 --- /dev/null +++ b/deployment/database/migrations/1.1.0_webhook-order.sql @@ -0,0 +1,10 @@ +/** +* A que endpoint actualizar el estado de los order, si se especificase. +* Se asume que siempre se usa POST. +* Se separa host de enpoint para dejar host como default el origen de la +* peticion anterior y poder hacer filtrados +*/ + +ALTER TABLE order_tracking + ADD COLUMN webhook_host TEXT, + ADD COLUMN webhook_endpoint TEXT; diff --git a/deployment/local/docker/docker-compose.yaml b/deployment/local/docker/docker-compose.yaml index 8293017..114b9d3 100644 --- a/deployment/local/docker/docker-compose.yaml +++ b/deployment/local/docker/docker-compose.yaml @@ -60,8 +60,11 @@ services: depends_on: rabbitmq-sim-broker: condition: service_healthy + postgresql-sim: + condition: service_healthy postgresql-sim: + container_name: postgresql-sim image: postgres:16.1 env_file: - .env diff --git a/package.json b/package.json index 06ddda1..539fa1c 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "express": "^5.2.1", "pg": "^8.18.0", "typescript": "^5.9.3", + "uuidv7": "^1.1.0", "vite": "^7.3.1", "vite-tsconfig-paths": "^6.0.5" }, diff --git a/packages/sim-entrada-eventos/aplication/Sim.controller.ts b/packages/sim-entrada-eventos/aplication/Sim.controller.ts index 5030db6..d93e903 100644 --- a/packages/sim-entrada-eventos/aplication/Sim.controller.ts +++ b/packages/sim-entrada-eventos/aplication/Sim.controller.ts @@ -3,13 +3,14 @@ import { SimUsecases } from "./Sim.usecases.js" import { activationValidator, iccidValidator } from "./httpValidators.js" import { companyFromIccid } from "#domain/companies.js" import { BodyValidator } from "sim-shared/aplication/BodyValidator.js" +import { error } from "node:console" export class SimController { private simUseCases: SimUsecases constructor(args: { - simUseCases: SimUsecases + simUseCases: SimUsecases, }) { this.simUseCases = args.simUseCases @@ -79,6 +80,18 @@ export class SimController { } } + public preactivationTest() { + return this.controllerGenerator({ + validator: iccidValidator, + useCase: this.simUseCases.test, + onError: (data, error) => console.error(error), + onSuccess: (data) => { + console.log("OK", data) + } + }) + + } + public preactivation() { return async (req: Request, res: Response) => { console.warn("[!] Se deberia de usar la peticion /sim/activate directamente") diff --git a/packages/sim-entrada-eventos/aplication/Sim.usecases.ts b/packages/sim-entrada-eventos/aplication/Sim.usecases.ts index 573b73d..67427b2 100644 --- a/packages/sim-entrada-eventos/aplication/Sim.usecases.ts +++ b/packages/sim-entrada-eventos/aplication/Sim.usecases.ts @@ -1,23 +1,65 @@ +import { OrderRepository } from "sim-shared/infrastructure/OrderRepository.js"; +import assert from "node:assert"; import { EventBus } from "sim-shared/domain/EventBus.port"; import { SimEvents } from "sim-shared/domain/SimEvents"; +import { uuidv7 } from "uuidv7"; +import { CreateOrderDTO, OrderType } from "sim-shared/domain/Order.js"; /** - * TODO: - * - Conexion con la BDD - * - Conexion con RabbitMQ - * - Pasar a clase cuando existan las conexiones + * Casos de uso de tarjetas sim. Garantiza que todos los metodos usan el mismo bus de mensajes + * y repositorio de registro de las ordenes. */ export class SimUsecases { - private eventBus: EventBus + private eventBus: EventBus; + private orderRepository: OrderRepository; constructor(args: { - eventBus: EventBus + eventBus: EventBus, + orderRepository: OrderRepository } ) { this.eventBus = args.eventBus + this.orderRepository = args.orderRepository + } + + + async test(args: { iccid: string }) { + assert(args.iccid != undefined) + const uuid = uuidv7() + const event = { + key: `sim.test.test`, + payload: { + iccid: args.iccid + }, + headers: { + message_id: uuid + } + } + + const publish = await this.eventBus.publish([event]) + + /** + * TODO: + * De momento solo para mensajes publicados de 1 en 1 y si se les ha añadido cabecera + * Si se ha saltado el proceso de añadir un ID no se + */ + if (publish.success.length == 1) { + if (event.headers?.message_id != undefined) { + const orderType = (event.key.split(".")[2] as OrderType ?? "unknown") + assert(orderType) + const order: CreateOrderDTO = { + correlation_id: event.headers.message_id, + order_type: orderType, + routing_key: event.key, + payload: event + } + this.orderRepository.createOrder(order) + } + } } /** + * WIP * Crea una nueva sim de la que no se tenia registro anteriormente * Si ya existia se modifican los campos pero no se hace un cambio * de estado. diff --git a/packages/sim-shared/domain/DomainEvent.ts b/packages/sim-shared/domain/DomainEvent.ts index 00d3cac..22f28ae 100644 --- a/packages/sim-shared/domain/DomainEvent.ts +++ b/packages/sim-shared/domain/DomainEvent.ts @@ -8,8 +8,10 @@ export type DomainEventType = string export type DomainEvent = { key: string, payload: Object, - options: Object, - occurredOn: Date, + headers?: Object & { + message_id?: string + }, + occurredOn?: Date, } export interface DomainEventSubscriber { diff --git a/packages/sim-shared/domain/EventBus.port.ts b/packages/sim-shared/domain/EventBus.port.ts index a80cc7c..6883abd 100644 --- a/packages/sim-shared/domain/EventBus.port.ts +++ b/packages/sim-shared/domain/EventBus.port.ts @@ -2,7 +2,7 @@ import { ConsumeMessage } from "amqplib"; import { DomainEvent, DomainEventSubscriber } from "./DomainEvent.js"; export interface EventBus { - publish(events: Array): Promise; + publish(events: Array): Promise<{ success: DomainEvent[], error: DomainEvent[] }>; // Sacado de NEKI, posiblemente no haga falta addSubscribers(subscribers: Array>): void; diff --git a/packages/sim-shared/infrastructure/RabbitMQEventBus.ts b/packages/sim-shared/infrastructure/RabbitMQEventBus.ts index 2489f90..f3c97c9 100644 --- a/packages/sim-shared/infrastructure/RabbitMQEventBus.ts +++ b/packages/sim-shared/infrastructure/RabbitMQEventBus.ts @@ -17,6 +17,11 @@ export class RabbitMQEventBus implements EventBus { private buildStructure?: (chan: Channel) => Promise private maxRetry: number = 0 + connection?: AmqpConnectionManager + channel?: ChannelWrapper + connected: Boolean = false + + private connectionOptions: RMQConnectionParams constructor(args: { connectionParams: RMQConnectionParams, buildStructure?: (chan: Channel) => Promise, @@ -73,11 +78,6 @@ export class RabbitMQEventBus implements EventBus { //return this.channel.nack(msg, false, requeue) } - connection?: AmqpConnectionManager - channel?: ChannelWrapper - connected: Boolean = false - - private connectionOptions: RMQConnectionParams public async connect() { @@ -96,28 +96,35 @@ export class RabbitMQEventBus implements EventBus { } catch (e) { console.error("[RMQ] Error estableciendo la conexion con el servidor", e) } - - - } - publish(events: DomainEvent[]): Promise { - - return new Promise((res, rej) => { + publish(events: DomainEvent[]): Promise<{ success: DomainEvent[], error: DomainEvent[] }> { + return new Promise(async (res, rej) => { + const successEvents: DomainEvent[] = [] + const errorEvents: DomainEvent[] = [] try { for (const event of events) { const exchange = "sim.exchange" const routingKey = event.key const content = Buffer.from(JSON.stringify(event)) - this.channel?.publish(exchange, routingKey, content, {}, (err, ok) => { + await this.channel?.publish(exchange, routingKey, content, { + headers: { + ...event.headers + } + }, (err, ok) => { if (err == undefined) { console.log("Evento publicado ", event) + successEvents.push(event) } else { console.error("Error publicando", event) + errorEvents.push(event) } }) } - return res() + return res({ + success: successEvents, + error: errorEvents + }) } catch (err) { return rej(err) } diff --git a/run.local.sh b/run.local.sh index dc141a5..2dbd2a5 100755 --- a/run.local.sh +++ b/run.local.sh @@ -2,8 +2,8 @@ rm deployment/database/init.sql # init sql debe juntar todos los scripts de "base" (sin contar migraciones) -# cat deployment/database/base/*.sql >deployment/database/init.sql -cp deployment/database/esquema_final* deployment/database/init.sql +cat deployment/database/base/*.sql >deployment/database/init.sql +#cp deployment/database/esquema_final* deployment/database/init.sql # compatibilidad con postgresql < 17 sed -i '/\\restrict/d' deployment/database/init.sql diff --git a/yarn.lock b/yarn.lock index 32d2d65..55426ac 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2893,6 +2893,7 @@ __metadata: tsc-alias: "npm:^1.8.16" tsx: "npm:^4.21.0" typescript: "npm:^5.9.3" + uuidv7: "npm:^1.1.0" vite: "npm:^7.3.1" vite-tsconfig-paths: "npm:^6.0.5" vitest: "npm:^4.0.16" @@ -3328,6 +3329,15 @@ __metadata: languageName: node linkType: hard +"uuidv7@npm:^1.1.0": + version: 1.1.0 + resolution: "uuidv7@npm:1.1.0" + bin: + uuidv7: cli.js + checksum: 10/a611c4918b1662ec8f4f927b96ccc975ca050d3b221e2943ade6796c956117719a94a9edcc3f26ec8597c2ab270fed074ef5ab9fcc3b46f42c26cb4caafa4ac2 + languageName: node + linkType: hard + "vary@npm:^1, vary@npm:^1.1.2": version: 1.1.2 resolution: "vary@npm:1.1.2"