Todos los test de orders pasan

This commit is contained in:
2026-02-23 13:35:36 +01:00
parent fc319372be
commit 5c64c84e2a
5 changed files with 63 additions and 31 deletions

8
.env
View File

@@ -5,8 +5,8 @@ RABBITMQ_PASSWORD=guest
ENVIORMENT=development ENVIORMENT=development
RABBITMQ_HOST=rabbitmq-sim-broker # RABBITMQ_HOST=rabbitmq-sim-broker
# RABBITMQ_HOST=localhost RABBITMQ_HOST=localhost
RABBITMQ_PORT=5672 RABBITMQ_PORT=5672
RABBITMQ_USER=guest RABBITMQ_USER=guest
RABBITMQ_PASSWORD=guest RABBITMQ_PASSWORD=guest
@@ -14,8 +14,8 @@ RABBITMQ_SECURE=false
RABBITMQ_VHOST=sim-vhost RABBITMQ_VHOST=sim-vhost
# Hay cosas que unificar de varios servicios # Hay cosas que unificar de varios servicios
#POSTGRES_HOST=localhost # POSTGRES_HOST=sim-eventos-postgresql-sim-1
POSTGRES_HOST=sim-eventos-postgresql-sim-1 POSTGRES_HOST=localhost
POSTGRES_DB=postgres POSTGRES_DB=postgres
POSTGRES_DATABASE=postgres POSTGRES_DATABASE=postgres
POSTGRES_PORT=5433 POSTGRES_PORT=5433

View File

@@ -37,7 +37,7 @@ body:form-urlencoded {
} }
vars:pre-request { vars:pre-request {
params.id: 14333 params.id: 14557
} }
settings { settings {

View File

@@ -2,7 +2,7 @@ import { IOperationsRepository, ObjeniousOperation, ObjeniousOperationChange } f
import { Result } from "sim-shared/domain/Result.js"; import { Result } from "sim-shared/domain/Result.js";
import { PgClient } from "sim-shared/infrastructure/PgClient.js"; import { PgClient } from "sim-shared/infrastructure/PgClient.js";
export class OperationsRepository implements IOperationsRepository { export class ObjeniousOperationsRepository implements IOperationsRepository {
constructor( constructor(
private readonly pgClient: PgClient private readonly pgClient: PgClient
@@ -12,7 +12,7 @@ export class OperationsRepository implements IOperationsRepository {
async createOperation(data: ObjeniousOperation): Promise<Result<string, ObjeniousOperation>> { async createOperation(data: ObjeniousOperation): Promise<Result<string, ObjeniousOperation>> {
const query = ` const query = `
INSERT INTO objenious_operation (operation, iccids, status, max_retry, request_id) INSERT INTO objenious_operation (operation, iccids, status, max_retry, request_id)
VALUES ($1, $2, $3, $4, $5) VALUES ($1, $2, $3, $4, $5)
RETURNING *`; RETURNING *`;
const values = [data.operation, data.iccids, data.status, data.max_retry, data.request_id]; const values = [data.operation, data.iccids, data.status, data.max_retry, data.request_id];
const { rows } = await this.pgClient.query(query, values); const { rows } = await this.pgClient.query(query, values);

View File

@@ -12,14 +12,28 @@ const order1 = <CreateOrderDTO>{
payload: { iccid: "1234", action: "activate" } payload: { iccid: "1234", action: "activate" }
} }
const order2 = <CreateOrderDTO>{
correlation_id: "fakeRMQid-5678",
exchange: "fake.ex",
routing_key: "test.order.idk",
order_type: "activate",
payload: { iccid: "5678", action: "activate" }
}
describe("Test OrderRepository", {}, () => {
describe("Test OrderRepository", {}, (ctx) => {
const orderRepo = new OrderRepository(postgresClient) const orderRepo = new OrderRepository(postgresClient)
let testId: number | undefined = undefined; let testIds: number[] = []
before(async () => { before(async () => {
const result = await orderRepo.createOrder(order1) // Order1
testId = result.data.id const result1 = await orderRepo.createOrder(order1)
assert(result1.data != undefined)
testIds.push(result1.data.id)
// Order2 -> Para el test de crearOrder
// const result2 = await orderRepo.createOrder(order2)
// assert(result2.data != undefined)
// testIds.push(result2.data.id)
}) })
it("Insert new Order", async () => { it("Insert new Order", async () => {
@@ -39,12 +53,13 @@ describe("Test OrderRepository", {}, () => {
}) })
it("Find by valid id should return the order", async () => { it("Find by valid id should return the order", async () => {
const result = await orderRepo.getOrderById({ id: testId! }) const result = await orderRepo.getOrderById({ id: testIds[0]! })
assert(result.error == undefined) assert(result.error == undefined)
assert(result.data != undefined) assert(result.data != undefined)
const order = result.data const order = result.data
assert(order.id == testId) assert(order.id == testIds[0])
assert(order.correlation_id == order1.correlation_id)
}) })
it("Find by correlation id should return a valid order", async () => { it("Find by correlation id should return a valid order", async () => {
@@ -66,6 +81,9 @@ describe("Test OrderRepository", {}, () => {
const resA = await orderRepo.createOrder(orderA) const resA = await orderRepo.createOrder(orderA)
const resB = await orderRepo.createOrder(orderB) const resB = await orderRepo.createOrder(orderB)
assert(resA.data != undefined)
assert(resB.data != undefined)
const idA = resA.data.id const idA = resA.data.id
const idB = resB.data.id const idB = resB.data.id
@@ -74,14 +92,14 @@ describe("Test OrderRepository", {}, () => {
assert(result.error == undefined) assert(result.error == undefined)
assert(Array.isArray(result.data)) assert(Array.isArray(result.data))
// The list should contain at least our 3 orders (testId, idA, idB)
const ids = result.data.map(o => o.id) const ids = result.data.map(o => o.id)
assert(ids.includes(testId!)) assert(ids.includes(testIds[0]!))
assert(ids.includes(idA)) assert(ids.includes(idA))
assert(ids.includes(idB)) assert(ids.includes(idB))
// Verify ordering (ASC by start_date, which maps to ID order in this sequential test) // Verify ordering (ASC by start_date, which maps to ID order in this sequential test)
const indexTest = result.data.findIndex(o => o.id === testId) const indexTest = result.data.findIndex(o => o.id === testIds[0])
const indexA = result.data.findIndex(o => o.id === idA) const indexA = result.data.findIndex(o => o.id === idA)
const indexB = result.data.findIndex(o => o.id === idB) const indexB = result.data.findIndex(o => o.id === idB)
@@ -92,7 +110,7 @@ describe("Test OrderRepository", {}, () => {
it("Update order status should change status and add history", async () => { it("Update order status should change status and add history", async () => {
const newStatus = "running" const newStatus = "running"
const reason = "Test update" const reason = "Test update"
const result = await orderRepo.updateOrder({ id: testId!, new_status: newStatus, reason: reason }) const result = await orderRepo.updateOrder({ id: testIds[0]!, new_status: newStatus, reason: reason })
assert(result.error == undefined) assert(result.error == undefined)
assert(result.data != undefined) assert(result.data != undefined)
@@ -100,7 +118,7 @@ describe("Test OrderRepository", {}, () => {
}) })
it("Finish order should set status to finished and set finish_date", async () => { it("Finish order should set status to finished and set finish_date", async () => {
const result = await orderRepo.finishOrder({ id: testId!, reason: "Test finish" }) const result = await orderRepo.finishOrder({ id: testIds[0]!, reason: "Test finish" })
assert(result.error == undefined) assert(result.error == undefined)
assert(result.data != undefined) assert(result.data != undefined)
@@ -112,6 +130,7 @@ describe("Test OrderRepository", {}, () => {
// Create another order for this test // Create another order for this test
const order2 = { ...order1, correlation_id: "fake-error-test" } const order2 = { ...order1, correlation_id: "fake-error-test" }
const createResult = await orderRepo.createOrder(order2) const createResult = await orderRepo.createOrder(order2)
assert(createResult.data != undefined)
const errTestId = createResult.data.id const errTestId = createResult.data.id
const result = await orderRepo.errorOrder({ const result = await orderRepo.errorOrder({
@@ -133,6 +152,7 @@ describe("Test OrderRepository", {}, () => {
// Create another order for this test // Create another order for this test
const order3 = { ...order1, correlation_id: "fake-dlx-test" } const order3 = { ...order1, correlation_id: "fake-dlx-test" }
const createResult = await orderRepo.createOrder(order3) const createResult = await orderRepo.createOrder(order3)
assert(createResult.data != undefined)
const dlxTestId = createResult.data.id const dlxTestId = createResult.data.id
const result = await orderRepo.errorOrder({ const result = await orderRepo.errorOrder({

View File

@@ -6,6 +6,15 @@ import { CreateOrderDTO, OrderTracking } from "../domain/Order.js";
import { Result } from "../domain/Result.js"; import { Result } from "../domain/Result.js";
import { PgClient } from "./PgClient.js"; import { PgClient } from "./PgClient.js";
/**
* Agrupa todas las operaciones de *Order*.
* Las *Order* son seguimientos de operaciones que han entrado correctamente a cualquier cola
* de mensajes independientemente del pais/empresa objetivo de la tarjeta.
*
* Todas las operaciones devuelven un tipo Result<Error,Data> para gestionar los errores
* de acceso a la BDD, para las operaciones correctas se devuleve Error = undefined, para
* las erroneas Data = undefined.
*/
export class OrderRepository { export class OrderRepository {
constructor( constructor(
private readonly pgClient: PgClient private readonly pgClient: PgClient
@@ -34,7 +43,6 @@ export class OrderRepository {
* Se asume que se va a devolver una lista del tipo T * Se asume que se va a devolver una lista del tipo T
*/ */
private async getAll<T extends QueryResultRow>(queryPromise: Promise<QueryResult<T>>) { private async getAll<T extends QueryResultRow>(queryPromise: Promise<QueryResult<T>>) {
try { try {
const queryResult = await queryPromise const queryResult = await queryPromise
return <Result<string, T[]>>{ return <Result<string, T[]>>{
@@ -48,15 +56,15 @@ export class OrderRepository {
} }
/** /**
* TODO: OrderTracking necestia un tipo para la estructura del mensaje almacenado * El tipo <T> representa el contenido del mensaje de los order
*/ */
public async getOrderById(data: { id: number }) { public async getOrderById<T>(data: { id: number }): Promise<Result<string, OrderTracking<T>>> {
const query = ` const query = `
SELECT * FROM order_tracking SELECT * FROM order_tracking
WHERE id = $1 WHERE id = $1
` `
const values = [data.id] const values = [data.id]
const queryPromise = this.pgClient.query<OrderTracking<any>>(query, values) const queryPromise = this.pgClient.query<OrderTracking<T>>(query, values)
const result = await this.getFirst(queryPromise); const result = await this.getFirst(queryPromise);
return result return result
} }
@@ -64,30 +72,33 @@ export class OrderRepository {
/** /**
* Busqueda según la id de RabbitMq * Busqueda según la id de RabbitMq
*/ */
public async getOrderByQueueId(data: { correlation_id: string }, pool?: PoolClient) { public async getOrderByQueueId<T>(data: { correlation_id: string }, pool?: PoolClient) {
const query = ` const query = `
SELECT * FROM order_tracking SELECT * FROM order_tracking
WHERE correlation_id = $1 WHERE correlation_id = $1
` `
const values = [data.correlation_id] const values = [data.correlation_id]
const queryPromise = this.pgClient.query<OrderTracking<any>>(query, values) const queryPromise = this.pgClient.query<OrderTracking<T>>(query, values)
const result = await this.getFirst(queryPromise); const result = await this.getFirst(queryPromise);
return result return result
} }
/** /**
* TODO:
* - variable para el limit
*/ */
public async getPendingOrders() { public async getPendingOrders<T>(options?: {
limit?: number
}) {
const client = await this.pgClient.connect(); const client = await this.pgClient.connect();
const query = ` const query = `
SELECT * FROM order_tracking SELECT * FROM order_tracking
WHERE finish_date IS NULL WHERE finish_date IS NULL
ORDER BY start_date ASC ORDER BY start_date ASC
` `
if (options?.limit != undefined) {
}
const values: string[] = [] const values: string[] = []
const queryPromise = client.query(query, values) const queryPromise = client.query<OrderTracking<T>>(query, values)
const result = await this.getAll(queryPromise) const result = await this.getAll(queryPromise)
client.release() client.release()
return result return result
@@ -116,7 +127,8 @@ export class OrderRepository {
RETURNING id, correlation_id, status, start_date; RETURNING id, correlation_id, status, start_date;
` `
const values = [data.correlation_id, data.exchange, data.routing_key, data.order_type, data.payload] const values = [data.correlation_id, data.exchange, data.routing_key, data.order_type, data.payload]
const queryPromise = client.query(query, values) const queryPromise = client.query<{ id: number, correlation_id: string, status: string, start_date: string }>(query, values)
// TODO comprobar si start_date convierte a Date por defecto, añadir enum de status
const result = await this.getFirst(queryPromise) const result = await this.getFirst(queryPromise)
if (result.error == undefined) { if (result.error == undefined) {