diff --git a/descriptors/ModuleDescriptor-template.json b/descriptors/ModuleDescriptor-template.json index 35e260e5..5df29739 100644 --- a/descriptors/ModuleDescriptor-template.json +++ b/descriptors/ModuleDescriptor-template.json @@ -151,6 +151,51 @@ } ] }, + { + "id": "acquisition-invoice-events", + "version": "1.0", + "handlers": [ + { + "methods": [ + "GET" + ], + "pathPattern": "/audit-data/acquisition/invoice/{id}", + "permissionsRequired": [ + "acquisition.invoice.events.get" + ] + } + ] + }, + { + "id": "acquisition-invoice-line-events", + "version": "1.0", + "handlers": [ + { + "methods": [ + "GET" + ], + "pathPattern": "/audit-data/acquisition/invoice-line/{id}", + "permissionsRequired": [ + "acquisition.invoice-line.events.get" + ] + } + ] + }, + { + "id": "acquisition-organization-events", + "version": "1.0", + "handlers": [ + { + "methods": [ + "GET" + ], + "pathPattern": "/audit-data/acquisition/organization/{id}", + "permissionsRequired": [ + "acquisition.organization.events.get" + ] + } + ] + }, { "id": "circulation-logs", "version": "1.2", @@ -264,6 +309,21 @@ "displayName": "Acquisition piece status change history events - get piece status change events", "description": "Get piece status change events" }, + { + "permissionName": "acquisition.invoice.events.get", + "displayName": "Acquisition invoice events - get invoice change events", + "description": "Get invoice change events" + }, + { + "permissionName": "acquisition.invoice-line.events.get", + "displayName": "Acquisition invoice-line events - get invoice-line change events", + "description": "Get invoice-line change events" + }, + { + "permissionName": "acquisition.organization.events.get", + "displayName": "Acquisition organization events - get organization change events", + "description": "Get organization change events" + }, { "permissionName": "audit.all", "displayName": "Audit - all permissions", @@ -278,7 +338,10 @@ "acquisition.order.events.get", "acquisition.order-line.events.get", "acquisition.piece.events.get", - "acquisition.piece.events.history.get" + "acquisition.piece.events.history.get", + "acquisition.invoice.events.get", + "acquisition.invoice-line.events.get", + "acquisition.organization.events.get" ] } ], diff --git a/mod-audit-server/pom.xml b/mod-audit-server/pom.xml index 3688ab5b..f1813522 100644 --- a/mod-audit-server/pom.xml +++ b/mod-audit-server/pom.xml @@ -2,13 +2,13 @@ 4.0.0 mod-audit-server - 2.10.2-SNAPSHOT + 3.0.0-SNAPSHOT jar mod-audit org.folio - 2.10.2-SNAPSHOT + 3.0.0-SNAPSHOT diff --git a/mod-audit-server/src/main/java/org/folio/dao/acquisition/InvoiceEventsDao.java b/mod-audit-server/src/main/java/org/folio/dao/acquisition/InvoiceEventsDao.java new file mode 100644 index 00000000..c8fcdece --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/dao/acquisition/InvoiceEventsDao.java @@ -0,0 +1,32 @@ +package org.folio.dao.acquisition; + +import io.vertx.core.Future; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import org.folio.rest.jaxrs.model.InvoiceAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceAuditEventCollection; + +public interface InvoiceEventsDao { + + /** + * Saves invoiceAuditEvent entity to DB + * + * @param invoiceAuditEvent InvoiceAuditEvent entity to save + * @param tenantId tenant id + * @return future with created row + */ + Future> save(InvoiceAuditEvent invoiceAuditEvent, String tenantId); + + /** + * Searches for invoice audit events by id + * + * @param invoiceId invoice id + * @param sortBy sort by + * @param sortOrder sort order + * @param limit limit + * @param offset offset + * @param tenantId tenant id + * @return future with InvoiceAuditEventCollection + */ + Future getAuditEventsByInvoiceId(String invoiceId, String sortBy, String sortOrder, int limit, int offset, String tenantId); +} diff --git a/mod-audit-server/src/main/java/org/folio/dao/acquisition/InvoiceLineEventsDao.java b/mod-audit-server/src/main/java/org/folio/dao/acquisition/InvoiceLineEventsDao.java new file mode 100644 index 00000000..066c8954 --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/dao/acquisition/InvoiceLineEventsDao.java @@ -0,0 +1,32 @@ +package org.folio.dao.acquisition; + +import io.vertx.core.Future; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEventCollection; + +public interface InvoiceLineEventsDao { + + /** + * Saves invoiceLineAuditEvent entity to DB + * + * @param invoiceLineAuditEvent InvoiceLineAuditEvent entity to save + * @param tenantId tenant id + * @return future with created row + */ + Future> save(InvoiceLineAuditEvent invoiceLineAuditEvent, String tenantId); + + /** + * Searches for invoice_line audit events by id + * + * @param invoiceLineId invoice_line id + * @param sortBy sort by + * @param sortOrder sort order + * @param limit limit + * @param offset offset + * @param tenantId tenant id + * @return future with InvoiceLineAuditEventCollection + */ + Future getAuditEventsByInvoiceLineId(String invoiceLineId, String sortBy, String sortOrder, int limit, int offset, String tenantId); +} diff --git a/mod-audit-server/src/main/java/org/folio/dao/acquisition/OrganizationEventsDao.java b/mod-audit-server/src/main/java/org/folio/dao/acquisition/OrganizationEventsDao.java new file mode 100644 index 00000000..94041d6c --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/dao/acquisition/OrganizationEventsDao.java @@ -0,0 +1,32 @@ +package org.folio.dao.acquisition; + +import io.vertx.core.Future; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import org.folio.rest.jaxrs.model.OrganizationAuditEvent; +import org.folio.rest.jaxrs.model.OrganizationAuditEventCollection; + +public interface OrganizationEventsDao { + + /** + * Saves organizationAuditEvent entity to DB + * + * @param organizationAuditEvent OrganizationAuditEvent entity to save + * @param tenantId tenant id + * @return future with created row + */ + Future> save(OrganizationAuditEvent organizationAuditEvent, String tenantId); + + /** + * Searches for organization audit events by id + * + * @param organizationId organization id + * @param sortBy sort by + * @param sortOrder sort order + * @param limit limit + * @param offset offset + * @param tenantId tenant id + * @return future with OrganizationAuditEventCollection + */ + Future getAuditEventsByOrganizationId(String organizationId, String sortBy, String sortOrder, int limit, int offset, String tenantId); +} diff --git a/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/InvoiceEventsDaoImpl.java b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/InvoiceEventsDaoImpl.java new file mode 100644 index 00000000..67924884 --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/InvoiceEventsDaoImpl.java @@ -0,0 +1,113 @@ +package org.folio.dao.acquisition.impl; + +import static java.lang.String.format; +import static org.folio.util.AuditEventDBConstants.ACTION_DATE_FIELD; +import static org.folio.util.AuditEventDBConstants.ACTION_FIELD; +import static org.folio.util.AuditEventDBConstants.EVENT_DATE_FIELD; +import static org.folio.util.AuditEventDBConstants.ID_FIELD; +import static org.folio.util.AuditEventDBConstants.INVOICE_ID_FIELD; +import static org.folio.util.AuditEventDBConstants.MODIFIED_CONTENT_FIELD; +import static org.folio.util.AuditEventDBConstants.ORDER_BY_PATTERN; +import static org.folio.util.AuditEventDBConstants.TOTAL_RECORDS_FIELD; +import static org.folio.util.AuditEventDBConstants.USER_ID_FIELD; +import static org.folio.util.DbUtils.formatDBTableName; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Date; +import java.util.UUID; + +import io.vertx.core.Future; +import io.vertx.core.json.JsonObject; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.Tuple; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.dao.acquisition.InvoiceEventsDao; +import org.folio.rest.jaxrs.model.InvoiceAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceAuditEventCollection; +import org.folio.util.PostgresClientFactory; +import org.springframework.stereotype.Repository; + +@Repository +public class InvoiceEventsDaoImpl implements InvoiceEventsDao { + + private static final Logger LOGGER = LogManager.getLogger(); + + public static final String TABLE_NAME = "acquisition_invoice_log"; + + public static final String GET_BY_INVOICE_ID_SQL = "SELECT id, action, invoice_id, user_id, event_date, action_date, modified_content_snapshot," + + " (SELECT count(*) AS total_records FROM %s WHERE invoice_id = $1) FROM %s WHERE invoice_id = $1 %s LIMIT $2 OFFSET $3"; + + public static final String INSERT_SQL = "INSERT INTO %s (id, action, invoice_id, user_id, event_date, action_date, modified_content_snapshot)" + + " VALUES ($1, $2, $3, $4, $5, $6, $7)"; + + private final PostgresClientFactory pgClientFactory; + + public InvoiceEventsDaoImpl(PostgresClientFactory pgClientFactory) { + this.pgClientFactory = pgClientFactory; + } + + @Override + public Future> save(InvoiceAuditEvent event, String tenantId) { + LOGGER.debug("save:: Saving Invoice AuditEvent with invoice id: {}", event.getInvoiceId()); + String logTable = formatDBTableName(tenantId, TABLE_NAME); + String query = format(INSERT_SQL, logTable); + return makeSaveCall(query, event, tenantId) + .onSuccess(rows -> LOGGER.info("save:: Saved Invoice AuditEvent with invoice id : {}", event.getInvoiceId())) + .onFailure(e -> LOGGER.error("Failed to save record with id: {} for invoice id: {} in to table {}", + event.getId(), event.getInvoiceId(), TABLE_NAME, e)); + } + + @Override + public Future getAuditEventsByInvoiceId(String invoiceId, String sortBy, String sortOrder, int limit, int offset, String tenantId) { + LOGGER.debug("getAuditEventsByInvoiceId:: Retrieving AuditEvent with invoice id : {}", invoiceId); + String logTable = formatDBTableName(tenantId, TABLE_NAME); + String query = format(GET_BY_INVOICE_ID_SQL, logTable, logTable, format(ORDER_BY_PATTERN, sortBy, sortOrder)); + return pgClientFactory.createInstance(tenantId).execute(query, Tuple.of(UUID.fromString(invoiceId), limit, offset)) + .map(this::mapRowToListOfInvoiceEvent); + } + + private Future> makeSaveCall(String query, InvoiceAuditEvent invoiceAuditEvent, String tenantId) { + LOGGER.debug("makeSaveCall:: Making save call with query : {} and tenant id : {}", query, tenantId); + try { + return pgClientFactory.createInstance(tenantId).execute(query, Tuple.of(invoiceAuditEvent.getId(), + invoiceAuditEvent.getAction(), + invoiceAuditEvent.getInvoiceId(), + invoiceAuditEvent.getUserId(), + LocalDateTime.ofInstant(invoiceAuditEvent.getEventDate().toInstant(), ZoneId.systemDefault()), + LocalDateTime.ofInstant(invoiceAuditEvent.getActionDate().toInstant(), ZoneId.systemDefault()), + JsonObject.mapFrom(invoiceAuditEvent.getInvoiceSnapshot()))); + } catch (Exception e) { + return Future.failedFuture(e); + } + } + + private InvoiceAuditEventCollection mapRowToListOfInvoiceEvent(RowSet rowSet) { + LOGGER.debug("mapRowToListOfInvoiceEvent:: Mapping row to List of Invoice Events"); + if (rowSet.rowCount() == 0) { + return new InvoiceAuditEventCollection().withTotalItems(0); + } + InvoiceAuditEventCollection invoiceAuditEventCollection = new InvoiceAuditEventCollection(); + rowSet.iterator().forEachRemaining(row -> { + invoiceAuditEventCollection.getInvoiceAuditEvents().add(mapRowToInvoiceEvent(row)); + invoiceAuditEventCollection.setTotalItems(row.getInteger(TOTAL_RECORDS_FIELD)); + }); + LOGGER.debug("mapRowToListOfInvoiceEvent:: Mapped row to List of Invoice Events"); + return invoiceAuditEventCollection; + } + + private InvoiceAuditEvent mapRowToInvoiceEvent(Row row) { + LOGGER.debug("mapRowToInvoiceEvent:: Mapping row to Invoice Event"); + return new InvoiceAuditEvent() + .withId(row.getValue(ID_FIELD).toString()) + .withAction(row.get(InvoiceAuditEvent.Action.class, ACTION_FIELD)) + .withInvoiceId(row.getValue(INVOICE_ID_FIELD).toString()) + .withUserId(row.getValue(USER_ID_FIELD).toString()) + .withEventDate(Date.from(row.getLocalDateTime(EVENT_DATE_FIELD).toInstant(ZoneOffset.UTC))) + .withActionDate(Date.from(row.getLocalDateTime(ACTION_DATE_FIELD).toInstant(ZoneOffset.UTC))) + .withInvoiceSnapshot(JsonObject.mapFrom(row.getValue(MODIFIED_CONTENT_FIELD))); + } +} diff --git a/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/InvoiceLineEventsDaoImpl.java b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/InvoiceLineEventsDaoImpl.java new file mode 100644 index 00000000..73a43a3e --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/InvoiceLineEventsDaoImpl.java @@ -0,0 +1,117 @@ +package org.folio.dao.acquisition.impl; + +import static java.lang.String.format; +import static org.folio.util.AuditEventDBConstants.ACTION_DATE_FIELD; +import static org.folio.util.AuditEventDBConstants.ACTION_FIELD; +import static org.folio.util.AuditEventDBConstants.EVENT_DATE_FIELD; +import static org.folio.util.AuditEventDBConstants.ID_FIELD; +import static org.folio.util.AuditEventDBConstants.INVOICE_ID_FIELD; +import static org.folio.util.AuditEventDBConstants.INVOICE_LINE_ID_FIELD; +import static org.folio.util.AuditEventDBConstants.MODIFIED_CONTENT_FIELD; +import static org.folio.util.AuditEventDBConstants.ORDER_BY_PATTERN; +import static org.folio.util.AuditEventDBConstants.TOTAL_RECORDS_FIELD; +import static org.folio.util.AuditEventDBConstants.USER_ID_FIELD; +import static org.folio.util.DbUtils.formatDBTableName; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Date; +import java.util.UUID; + +import io.vertx.core.Future; +import io.vertx.core.json.JsonObject; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.Tuple; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.dao.acquisition.InvoiceLineEventsDao; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEventCollection; +import org.folio.util.PostgresClientFactory; +import org.springframework.stereotype.Repository; + +@Repository +public class InvoiceLineEventsDaoImpl implements InvoiceLineEventsDao { + + private static final Logger LOGGER = LogManager.getLogger(); + + public static final String TABLE_NAME = "acquisition_invoice_line_log"; + + public static final String GET_BY_INVOICE_LINE_ID_SQL = "SELECT id, action, invoice_id, invoice_line_id, user_id, event_date, action_date, modified_content_snapshot," + + " (SELECT count(*) AS total_records FROM %s WHERE invoice_line_id = $1) " + + " FROM %s WHERE invoice_line_id = $1 %s LIMIT $2 OFFSET $3"; + + private static final String INSERT_SQL = "INSERT INTO %s (id, action, invoice_id, invoice_line_id, user_id, event_date, action_date, modified_content_snapshot) " + + "VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"; + + private final PostgresClientFactory pgClientFactory; + + public InvoiceLineEventsDaoImpl(PostgresClientFactory pgClientFactory) { + this.pgClientFactory = pgClientFactory; + } + + @Override + public Future> save(InvoiceLineAuditEvent event, String tenantId) { + LOGGER.debug("save:: Saving InvoiceLine AuditEvent with invoice line id: {}", event.getInvoiceLineId()); + String logTable = formatDBTableName(tenantId, TABLE_NAME); + String query = format(INSERT_SQL, logTable); + return makeSaveCall(query, event, tenantId) + .onSuccess(rows -> LOGGER.info("save:: Saved InvoiceLine AuditEvent with invoice line id : {}", event.getInvoiceLineId())) + .onFailure(e -> LOGGER.error("Failed to save record with id: {} for invoice line id: {} in to table {}", + event.getId(), event.getInvoiceLineId(), TABLE_NAME, e)); + } + + @Override + public Future getAuditEventsByInvoiceLineId(String invoiceLineId, String sortBy, String sortOrder, int limit, int offset, String tenantId) { + LOGGER.debug("getAuditEventsByInvoiceLineId:: Retrieving AuditEvent with invoice line id : {}", invoiceLineId); + String logTable = formatDBTableName(tenantId, TABLE_NAME); + String query = format(GET_BY_INVOICE_LINE_ID_SQL, logTable, logTable, format(ORDER_BY_PATTERN, sortBy, sortOrder)); + return pgClientFactory.createInstance(tenantId).execute(query, Tuple.of(UUID.fromString(invoiceLineId), limit, offset)) + .map(this::mapRowToListOfInvoiceLineEvent); + } + + private Future> makeSaveCall(String query, InvoiceLineAuditEvent invoiceLineAuditEvent, String tenantId) { + LOGGER.debug("makeSaveCall:: Making save call with query : {} and tenant id : {}", query, tenantId); + try { + return pgClientFactory.createInstance(tenantId).execute(query, Tuple.of(invoiceLineAuditEvent.getId(), + invoiceLineAuditEvent.getAction(), + invoiceLineAuditEvent.getInvoiceId(), + invoiceLineAuditEvent.getInvoiceLineId(), + invoiceLineAuditEvent.getUserId(), + LocalDateTime.ofInstant(invoiceLineAuditEvent.getEventDate().toInstant(), ZoneId.systemDefault()), + LocalDateTime.ofInstant(invoiceLineAuditEvent.getActionDate().toInstant(), ZoneId.systemDefault()), + JsonObject.mapFrom(invoiceLineAuditEvent.getInvoiceLineSnapshot()))); + } catch (Exception e) { + return Future.failedFuture(e); + } + } + + private InvoiceLineAuditEventCollection mapRowToListOfInvoiceLineEvent(RowSet rowSet) { + LOGGER.debug("mapRowToListOfInvoiceLineEvent:: Mapping row to List of Invoice Line Events"); + if (rowSet.rowCount() == 0) { + return new InvoiceLineAuditEventCollection().withTotalItems(0); + } + InvoiceLineAuditEventCollection invoiceLineAuditEventCollection = new InvoiceLineAuditEventCollection(); + rowSet.iterator().forEachRemaining(row -> { + invoiceLineAuditEventCollection.getInvoiceLineAuditEvents().add(mapRowToInvoiceLineEvent(row)); + invoiceLineAuditEventCollection.setTotalItems(row.getInteger(TOTAL_RECORDS_FIELD)); + }); + LOGGER.debug("mapRowToListOfInvoiceLineEvent:: Mapped row to List of Invoice Line Events"); + return invoiceLineAuditEventCollection; + } + + private InvoiceLineAuditEvent mapRowToInvoiceLineEvent(Row row) { + LOGGER.debug("mapRowToInvoiceLineEvent:: Mapping row to Invoice Line Event"); + return new InvoiceLineAuditEvent() + .withId(row.getValue(ID_FIELD).toString()) + .withAction(row.get(InvoiceLineAuditEvent.Action.class, ACTION_FIELD)) + .withInvoiceId(row.getValue(INVOICE_ID_FIELD).toString()) + .withInvoiceLineId(row.getValue(INVOICE_LINE_ID_FIELD).toString()) + .withUserId(row.getValue(USER_ID_FIELD).toString()) + .withEventDate(Date.from(row.getLocalDateTime(EVENT_DATE_FIELD).toInstant(ZoneOffset.UTC))) + .withActionDate(Date.from(row.getLocalDateTime(ACTION_DATE_FIELD).toInstant(ZoneOffset.UTC))) + .withInvoiceLineSnapshot(JsonObject.mapFrom(row.getValue(MODIFIED_CONTENT_FIELD))); + } +} diff --git a/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrderEventsDaoImpl.java b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrderEventsDaoImpl.java index d9ee92e4..c3c844af 100644 --- a/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrderEventsDaoImpl.java +++ b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrderEventsDaoImpl.java @@ -52,14 +52,13 @@ public OrderEventsDaoImpl(PostgresClientFactory pgClientFactory) { } @Override - public Future> save(OrderAuditEvent orderAuditEvent, String tenantId) { - LOGGER.debug("save:: Saving Order AuditEvent with tenant id : {}", tenantId); + public Future> save(OrderAuditEvent event, String tenantId) { + LOGGER.debug("save:: Saving Order AuditEvent with order id: {}", event.getOrderId()); Promise> promise = Promise.promise(); - LOGGER.debug("formatDBTableName:: Formatting DB Table Name with tenant id : {}", tenantId); String logTable = formatDBTableName(tenantId, TABLE_NAME); String query = format(INSERT_SQL, logTable); - makeSaveCall(promise, query, orderAuditEvent, tenantId); - LOGGER.info("save:: Saved Order AuditEvent with tenant id : {}", tenantId); + makeSaveCall(promise, query, event, tenantId); + LOGGER.info("save:: Saved Order AuditEvent with order id : {}", event.getOrderId()); return promise.future(); } @@ -78,8 +77,7 @@ public Future getAuditEventsByOrderId(String orderId, promise.fail(e); } LOGGER.info("getAuditEventsByOrderId:: Retrieved AuditEvent with order id : {}", orderId); - return promise.future().map(rowSet -> rowSet.rowCount() == 0 ? new OrderAuditEventCollection().withTotalItems(0) - : mapRowToListOfOrderEvent(rowSet)); + return promise.future().map(this::mapRowToListOfOrderEvent); } private void makeSaveCall(Promise> promise, String query, OrderAuditEvent orderAuditEvent, String tenantId) { @@ -102,6 +100,9 @@ private void makeSaveCall(Promise> promise, String query, OrderAudit private OrderAuditEventCollection mapRowToListOfOrderEvent(RowSet rowSet) { LOGGER.debug("mapRowToListOfOrderEvent:: Mapping row to List of Order Events"); + if (rowSet.rowCount() == 0) { + return new OrderAuditEventCollection().withTotalItems(0); + } OrderAuditEventCollection orderAuditEventCollection = new OrderAuditEventCollection(); rowSet.iterator().forEachRemaining(row -> { orderAuditEventCollection.getOrderAuditEvents().add(mapRowToOrderEvent(row)); @@ -123,5 +124,4 @@ private OrderAuditEvent mapRowToOrderEvent(Row row) { .withActionDate(Date.from(row.getLocalDateTime(ACTION_DATE_FIELD).toInstant(ZoneOffset.UTC))) .withOrderSnapshot(JsonObject.mapFrom(row.getValue(MODIFIED_CONTENT_FIELD))); } - } diff --git a/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrderLineEventsDaoImpl.java b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrderLineEventsDaoImpl.java index 8909874b..77c61fb2 100644 --- a/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrderLineEventsDaoImpl.java +++ b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrderLineEventsDaoImpl.java @@ -54,14 +54,13 @@ public OrderLineEventsDaoImpl(PostgresClientFactory pgClientFactory) { } @Override - public Future> save(OrderLineAuditEvent orderLineAuditEvent, String tenantId) { - LOGGER.debug("save:: Saving OrderLine AuditEvent with tenant id : {}", tenantId); + public Future> save(OrderLineAuditEvent event, String tenantId) { + LOGGER.debug("save:: Saving OrderLine AuditEvent with order line id : {}", event.getOrderLineId()); Promise> promise = Promise.promise(); - LOGGER.debug("formatDBTableName:: Formatting DB Table Name with tenant id : {}", tenantId); String logTable = formatDBTableName(tenantId, TABLE_NAME); String query = format(INSERT_SQL, logTable); - makeSaveCall(promise, query, orderLineAuditEvent, tenantId); - LOGGER.info("save:: Saved OrderLine AuditEvent with tenant id : {}", tenantId); + makeSaveCall(promise, query, event, tenantId); + LOGGER.info("save:: Saved OrderLine AuditEvent with order line id : {}", event.getOrderLineId()); return promise.future(); } @@ -81,8 +80,7 @@ public Future getAuditEventsByOrderLineId(String } LOGGER.info("getAuditEventsByOrderLineId:: Retrieved AuditEvent with order line id : {}", orderLineId); - return promise.future().map(rowSet -> rowSet.rowCount() == 0 ? new OrderLineAuditEventCollection().withTotalItems(0) - : mapRowToListOfOrderLineEvent(rowSet)); + return promise.future().map(this::mapRowToListOfOrderLineEvent); } private void makeSaveCall(Promise> promise, String query, OrderLineAuditEvent orderLineAuditEvent, String tenantId) { @@ -105,6 +103,9 @@ private void makeSaveCall(Promise> promise, String query, OrderLineA private OrderLineAuditEventCollection mapRowToListOfOrderLineEvent(RowSet rowSet) { LOGGER.debug("mapRowToListOfOrderLineEvent:: Mapping row to List of Order Line Events"); + if (rowSet.rowCount() == 0) { + return new OrderLineAuditEventCollection().withTotalItems(0); + } OrderLineAuditEventCollection orderLineAuditEventCollection = new OrderLineAuditEventCollection(); rowSet.iterator().forEachRemaining(row -> { orderLineAuditEventCollection.getOrderLineAuditEvents().add(mapRowToOrderLineEvent(row)); diff --git a/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrganizationEventsDaoImpl.java b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrganizationEventsDaoImpl.java new file mode 100644 index 00000000..1762ded4 --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/OrganizationEventsDaoImpl.java @@ -0,0 +1,113 @@ +package org.folio.dao.acquisition.impl; + +import io.vertx.core.Future; +import io.vertx.core.json.JsonObject; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.Tuple; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.dao.acquisition.OrganizationEventsDao; +import org.folio.rest.jaxrs.model.OrganizationAuditEvent; +import org.folio.rest.jaxrs.model.OrganizationAuditEventCollection; +import org.folio.util.PostgresClientFactory; +import org.springframework.stereotype.Repository; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Date; +import java.util.UUID; + +import static java.lang.String.format; +import static org.folio.util.AuditEventDBConstants.ACTION_DATE_FIELD; +import static org.folio.util.AuditEventDBConstants.ACTION_FIELD; +import static org.folio.util.AuditEventDBConstants.EVENT_DATE_FIELD; +import static org.folio.util.AuditEventDBConstants.ID_FIELD; +import static org.folio.util.AuditEventDBConstants.MODIFIED_CONTENT_FIELD; +import static org.folio.util.AuditEventDBConstants.ORDER_BY_PATTERN; +import static org.folio.util.AuditEventDBConstants.ORGANIZATION_ID_FIELD; +import static org.folio.util.AuditEventDBConstants.TOTAL_RECORDS_FIELD; +import static org.folio.util.AuditEventDBConstants.USER_ID_FIELD; +import static org.folio.util.DbUtils.formatDBTableName; + +@Repository +public class OrganizationEventsDaoImpl implements OrganizationEventsDao { + + private static final Logger LOGGER = LogManager.getLogger(); + + public static final String TABLE_NAME = "acquisition_organization_log"; + + public static final String GET_BY_INVOICE_ID_SQL = "SELECT id, action, organization_id, user_id, event_date, action_date, modified_content_snapshot," + + " (SELECT count(*) AS total_records FROM %s WHERE organization_id = $1) FROM %s WHERE organization_id = $1 %s LIMIT $2 OFFSET $3"; + + public static final String INSERT_SQL = "INSERT INTO %s (id, action, organization_id, user_id, event_date, action_date, modified_content_snapshot)" + + " VALUES ($1, $2, $3, $4, $5, $6, $7)"; + + private final PostgresClientFactory pgClientFactory; + + public OrganizationEventsDaoImpl(PostgresClientFactory pgClientFactory) { + this.pgClientFactory = pgClientFactory; + } + + @Override + public Future> save(OrganizationAuditEvent event, String tenantId) { + LOGGER.debug("save:: Saving Organization AuditEvent with organization id : {}", event.getOrganizationId()); + String logTable = formatDBTableName(tenantId, TABLE_NAME); + String query = format(INSERT_SQL, logTable); + return makeSaveCall(query, event, tenantId) + .onSuccess(rows -> LOGGER.info("save:: Saved Organization AuditEvent with organization id: {}", event.getOrganizationId())) + .onFailure(e -> LOGGER.error("Failed to save record with id: {} for organization id: {} in to table {}", + event.getId(), event.getOrganizationId(), TABLE_NAME, e)); + } + + @Override + public Future getAuditEventsByOrganizationId(String organizationId, String sortBy, String sortOrder, int limit, int offset, String tenantId) { + LOGGER.debug("getAuditEventsByOrganizationId:: Retrieving AuditEvent with organization id : {}", organizationId); + String logTable = formatDBTableName(tenantId, TABLE_NAME); + String query = format(GET_BY_INVOICE_ID_SQL, logTable, logTable, format(ORDER_BY_PATTERN, sortBy, sortOrder)); + return pgClientFactory.createInstance(tenantId).execute(query, Tuple.of(UUID.fromString(organizationId), limit, offset)) + .map(this::mapRowToListOfOrganizationEvent); + } + + private Future> makeSaveCall(String query, OrganizationAuditEvent organizationAuditEvent, String tenantId) { + LOGGER.debug("makeSaveCall:: Making save call with query : {} and tenant id : {}", query, tenantId); + try { + return pgClientFactory.createInstance(tenantId).execute(query, Tuple.of(organizationAuditEvent.getId(), + organizationAuditEvent.getAction(), + organizationAuditEvent.getOrganizationId(), + organizationAuditEvent.getUserId(), + LocalDateTime.ofInstant(organizationAuditEvent.getEventDate().toInstant(), ZoneId.systemDefault()), + LocalDateTime.ofInstant(organizationAuditEvent.getActionDate().toInstant(), ZoneId.systemDefault()), + JsonObject.mapFrom(organizationAuditEvent.getOrganizationSnapshot()))); + } catch (Exception e) { + return Future.failedFuture(e); + } + } + + private OrganizationAuditEventCollection mapRowToListOfOrganizationEvent(RowSet rowSet) { + LOGGER.debug("mapRowToListOfOrganizationEvent:: Mapping row to List of Organization Events"); + if (rowSet.rowCount() == 0) { + return new OrganizationAuditEventCollection().withTotalItems(0); + } + OrganizationAuditEventCollection organizationAuditEventCollection = new OrganizationAuditEventCollection(); + rowSet.iterator().forEachRemaining(row -> { + organizationAuditEventCollection.getOrganizationAuditEvents().add(mapRowToOrganizationEvent(row)); + organizationAuditEventCollection.setTotalItems(row.getInteger(TOTAL_RECORDS_FIELD)); + }); + LOGGER.debug("mapRowToListOfOrganizationEvent:: Mapped row to List of Organization Events"); + return organizationAuditEventCollection; + } + + private OrganizationAuditEvent mapRowToOrganizationEvent(Row row) { + LOGGER.debug("mapRowToOrganizationEvent:: Mapping row to Organization Event"); + return new OrganizationAuditEvent() + .withId(row.getValue(ID_FIELD).toString()) + .withAction(row.get(OrganizationAuditEvent.Action.class, ACTION_FIELD)) + .withOrganizationId(row.getValue(ORGANIZATION_ID_FIELD).toString()) + .withUserId(row.getValue(USER_ID_FIELD).toString()) + .withEventDate(Date.from(row.getLocalDateTime(EVENT_DATE_FIELD).toInstant(ZoneOffset.UTC))) + .withActionDate(Date.from(row.getLocalDateTime(ACTION_DATE_FIELD).toInstant(ZoneOffset.UTC))) + .withOrganizationSnapshot(JsonObject.mapFrom(row.getValue(MODIFIED_CONTENT_FIELD))); + } +} diff --git a/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/PieceEventsDaoImpl.java b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/PieceEventsDaoImpl.java index 946bfac6..c5117de8 100644 --- a/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/PieceEventsDaoImpl.java +++ b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/PieceEventsDaoImpl.java @@ -66,16 +66,13 @@ public PieceEventsDaoImpl(PostgresClientFactory pgClientFactory) { } @Override - public Future> save(PieceAuditEvent pieceAuditEvent, String tenantId) { - LOGGER.debug("save:: Trying to save Piece AuditEvent with tenant id : {}", tenantId); + public Future> save(PieceAuditEvent event, String tenantId) { + LOGGER.debug("save:: Trying to save Piece AuditEvent with piece id : {}", event.getPieceId()); Promise> promise = Promise.promise(); - - LOGGER.debug("formatDBTableName:: Formatting DB Table Name with tenant id : {}", tenantId); String logTable = formatDBTableName(tenantId, TABLE_NAME); String query = format(INSERT_SQL, logTable); - - makeSaveCall(promise, query, pieceAuditEvent, tenantId); - LOGGER.info("save:: Saved Piece AuditEvent for pieceId={} in tenant id={}", pieceAuditEvent.getPieceId(), tenantId); + makeSaveCall(promise, query, event, tenantId); + LOGGER.info("save:: Saved Piece AuditEvent for pieceId={} in tenant id={}", event.getPieceId(), tenantId); return promise.future(); } @@ -94,9 +91,7 @@ public Future getAuditEventsByPieceId(String pieceId, promise.fail(e); } LOGGER.info("getAuditEventsByOrderId:: Retrieved AuditEvent with piece id : {}", pieceId); - return promise.future().map(rowSet -> rowSet.rowCount() == 0 ? - new PieceAuditEventCollection().withTotalItems(0) : - mapRowToListOfPieceEvent(rowSet)); + return promise.future().map(this::mapRowToListOfPieceEvent); } @Override @@ -114,12 +109,14 @@ public Future getAuditEventsWithStatusChangesByPieceI promise.fail(e); } LOGGER.info("getAuditEventsByOrderId:: Retrieved AuditEvent with piece id: {}", pieceId); - return promise.future().map(rowSet -> rowSet.rowCount() == 0 ? new PieceAuditEventCollection().withTotalItems(0) - : mapRowToListOfPieceEvent(rowSet)); + return promise.future().map(this::mapRowToListOfPieceEvent); } private PieceAuditEventCollection mapRowToListOfPieceEvent(RowSet rowSet) { LOGGER.debug("mapRowToListOfOrderEvent:: Mapping row to List of Piece Events"); + if (rowSet.rowCount() == 0) { + return new PieceAuditEventCollection().withTotalItems(0); + } PieceAuditEventCollection pieceAuditEventCollection = new PieceAuditEventCollection(); rowSet.iterator().forEachRemaining(row -> { pieceAuditEventCollection.getPieceAuditEvents().add(mapRowToPieceEvent(row)); @@ -158,5 +155,4 @@ private void makeSaveCall(Promise> promise, String query, PieceAudit promise.fail(e); } } - } diff --git a/mod-audit-server/src/main/java/org/folio/rest/impl/AuditDataAcquisitionImpl.java b/mod-audit-server/src/main/java/org/folio/rest/impl/AuditDataAcquisitionImpl.java index f405be20..ce02a44f 100644 --- a/mod-audit-server/src/main/java/org/folio/rest/impl/AuditDataAcquisitionImpl.java +++ b/mod-audit-server/src/main/java/org/folio/rest/impl/AuditDataAcquisitionImpl.java @@ -7,14 +7,20 @@ import io.vertx.core.Future; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.folio.rest.jaxrs.model.AuditDataAcquisitionInvoiceIdGetSortOrder; +import org.folio.rest.jaxrs.model.AuditDataAcquisitionInvoiceLineIdGetSortOrder; import org.folio.rest.jaxrs.model.AuditDataAcquisitionOrderIdGetSortOrder; import org.folio.rest.jaxrs.model.AuditDataAcquisitionOrderLineIdGetSortOrder; +import org.folio.rest.jaxrs.model.AuditDataAcquisitionOrganizationIdGetSortOrder; import org.folio.rest.jaxrs.model.AuditDataAcquisitionPieceIdGetSortOrder; import org.folio.rest.jaxrs.model.AuditDataAcquisitionPieceIdStatusChangeHistoryGetSortOrder; import org.folio.rest.jaxrs.resource.AuditDataAcquisition; import org.folio.rest.tools.utils.TenantTool; +import org.folio.services.acquisition.InvoiceAuditEventsService; +import org.folio.services.acquisition.InvoiceLineAuditEventsService; import org.folio.services.acquisition.OrderAuditEventsService; import org.folio.services.acquisition.OrderLineAuditEventsService; +import org.folio.services.acquisition.OrganizationAuditEventsService; import org.folio.services.acquisition.PieceAuditEventsService; import org.folio.spring.SpringContextUtil; import org.folio.util.ErrorUtils; @@ -35,6 +41,12 @@ public class AuditDataAcquisitionImpl implements AuditDataAcquisition { private OrderLineAuditEventsService orderLineAuditEventsService; @Autowired private PieceAuditEventsService pieceAuditEventsService; + @Autowired + private InvoiceAuditEventsService invoiceAuditEventsService; + @Autowired + private InvoiceLineAuditEventsService invoiceLineAuditEventsService; + @Autowired + private OrganizationAuditEventsService organizationAuditEventsService; public AuditDataAcquisitionImpl() { SpringContextUtil.autowireDependencies(this, Vertx.currentContext()); @@ -110,6 +122,59 @@ public void getAuditDataAcquisitionPieceStatusChangeHistoryById(String pieceId, } } + @Override + public void getAuditDataAcquisitionInvoiceById(String invoiceId, String sortBy, + AuditDataAcquisitionInvoiceIdGetSortOrder sortOrder, + int limit, int offset, Map okapiHeaders, Handler> asyncResultHandler, Context vertxContext) { + LOGGER.debug("getAuditDataAcquisitionOrderLineById:: Retrieving Audit Data Acquisition Invoice By Id : {}", invoiceId); + String tenantId = TenantTool.tenantId(okapiHeaders); + try { + invoiceAuditEventsService.getAuditEventsByInvoiceId(invoiceId, sortBy, sortOrder.name(), limit, offset, tenantId) + .map(GetAuditDataAcquisitionInvoiceByIdResponse::respond200WithApplicationJson) + .map(Response.class::cast) + .otherwise(this::mapExceptionToResponse) + .onComplete(asyncResultHandler); + } catch (Exception e) { + LOGGER.error("Failed to get invoice audit events by invoice id: {}", invoiceId, e); + asyncResultHandler.handle(Future.succeededFuture(mapExceptionToResponse(e))); + } + } + + @Override + public void getAuditDataAcquisitionInvoiceLineById(String invoiceLineId, String sortBy, AuditDataAcquisitionInvoiceLineIdGetSortOrder sortOrder, + int limit, int offset, Map okapiHeaders, Handler> asyncResultHandler, Context vertxContext) { + LOGGER.debug("getAuditDataAcquisitionInvoiceLineById:: Retrieving Audit Data Acquisition Invoice Line By Id : {}", invoiceLineId); + String tenantId = TenantTool.tenantId(okapiHeaders); + try { + invoiceLineAuditEventsService.getAuditEventsByInvoiceLineId(invoiceLineId, sortBy, sortOrder.name(), limit, offset, tenantId) + .map(GetAuditDataAcquisitionInvoiceLineByIdResponse::respond200WithApplicationJson) + .map(Response.class::cast) + .otherwise(this::mapExceptionToResponse) + .onComplete(asyncResultHandler); + } catch (Exception e) { + LOGGER.error("Failed to get invoice line audit events by invoice line id: {}", invoiceLineId, e); + asyncResultHandler.handle(Future.succeededFuture(mapExceptionToResponse(e))); + } + } + + @Override + public void getAuditDataAcquisitionOrganizationById(String organizationId, String sortBy, + AuditDataAcquisitionOrganizationIdGetSortOrder sortOrder, + int limit, int offset, Map okapiHeaders, Handler> asyncResultHandler, Context vertxContext) { + LOGGER.debug("getAuditDataAcquisitionOrganizationById:: Retrieving Audit Data Acquisition Organization By Id : {}", organizationId); + String tenantId = TenantTool.tenantId(okapiHeaders); + try { + organizationAuditEventsService.getAuditEventsByOrganizationId(organizationId, sortBy, sortOrder.name(), limit, offset, tenantId) + .map(GetAuditDataAcquisitionOrganizationByIdResponse::respond200WithApplicationJson) + .map(Response.class::cast) + .otherwise(this::mapExceptionToResponse) + .onComplete(asyncResultHandler); + } catch (Exception e) { + LOGGER.error("Failed to get organization audit events by organization id: {}", organizationId, e); + asyncResultHandler.handle(Future.succeededFuture(mapExceptionToResponse(e))); + } + } + private Response mapExceptionToResponse(Throwable throwable) { LOGGER.debug("mapExceptionToResponse:: Mapping Exception :{} to Response", throwable.getMessage(), throwable); return GetAuditDataAcquisitionOrderByIdResponse diff --git a/mod-audit-server/src/main/java/org/folio/rest/impl/InitAPIs.java b/mod-audit-server/src/main/java/org/folio/rest/impl/InitAPIs.java index 7a5028d7..16d1099d 100644 --- a/mod-audit-server/src/main/java/org/folio/rest/impl/InitAPIs.java +++ b/mod-audit-server/src/main/java/org/folio/rest/impl/InitAPIs.java @@ -6,6 +6,7 @@ import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Promise; +import io.vertx.core.ThreadingModel; import io.vertx.core.Vertx; import io.vertx.core.spi.VerticleFactory; import org.apache.logging.log4j.LogManager; @@ -15,8 +16,11 @@ import org.folio.rest.resource.interfaces.InitAPI; import org.folio.spring.SpringContextUtil; import org.folio.verticle.SpringVerticleFactory; +import org.folio.verticle.acquisition.InvoiceEventConsumersVerticle; +import org.folio.verticle.acquisition.InvoiceLineEventConsumersVerticle; import org.folio.verticle.acquisition.OrderEventConsumersVerticle; import org.folio.verticle.acquisition.OrderLineEventConsumersVerticle; +import org.folio.verticle.acquisition.OrganizationEventConsumersVerticle; import org.folio.verticle.acquisition.PieceEventConsumersVerticle; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.support.AbstractApplicationContext; @@ -29,10 +33,33 @@ public class InitAPIs implements InitAPI { @Value("${acq.orders.kafka.consumer.instancesNumber:1}") private int acqOrderConsumerInstancesNumber; + @Value("${acq.orders.kafka.consumer.pool.size:5}") + private int acqOrderConsumerPoolSize; + @Value("${acq.order-lines.kafka.consumer.instancesNumber:1}") private int acqOrderLineConsumerInstancesNumber; + @Value("${acq.order-lines.kafka.consumer.pool.size:5}") + private int acqOrderLineConsumerPoolSize; + @Value("${acq.pieces.kafka.consumer.instancesNumber:1}") private int acqPieceConsumerInstancesNumber; + @Value("${acq.orders.kafka.consumer.pool.size:5}") + private int acqPieceConsumerPoolSize; + + @Value("${acq.invoices.kafka.consumer.instancesNumber:1}") + private int acqInvoiceConsumerInstancesNumber; + @Value("${acq.invoices.kafka.consumer.pool.size:5}") + private int acqInvoiceConsumerPoolSize; + + @Value("${acq.invoice-lines.kafka.consumer.instancesNumber:1}") + private int acqInvoiceLineConsumerInstancesNumber; + @Value("${acq.invoice-lines.kafka.consumer.pool.size:5}") + private int acqInvoiceLineConsumerPoolSize; + + @Value("${acq.organizations.kafka.consumer.instancesNumber:1}") + private int acqOrganizationConsumerInstancesNumber; + @Value("${acq.organizations.kafka.consumer.pool.size:5}") + private int acqOrganizationConsumerPoolSize; @Override public void init(Vertx vertx, Context context, Handler> handler) { @@ -64,27 +91,32 @@ private Future deployConsumersVerticles(Vertx vertx) { Promise orderEventsConsumer = Promise.promise(); Promise orderLineEventsConsumer = Promise.promise(); Promise pieceEventsConsumer = Promise.promise(); + Promise invoiceEventsConsumer = Promise.promise(); + Promise invoiceLineEventsConsumer = Promise.promise(); + Promise organizationsEventsConsumer = Promise.promise(); - vertx.deployVerticle(getVerticleName(verticleFactory, OrderEventConsumersVerticle.class), - new DeploymentOptions() - .setWorker(true) - .setInstances(acqOrderConsumerInstancesNumber), orderEventsConsumer); - - vertx.deployVerticle(getVerticleName(verticleFactory, OrderLineEventConsumersVerticle.class), - new DeploymentOptions() - .setWorker(true) - .setInstances(acqOrderLineConsumerInstancesNumber), orderLineEventsConsumer); - - vertx.deployVerticle(getVerticleName(verticleFactory, PieceEventConsumersVerticle.class), - new DeploymentOptions() - .setWorker(true) - .setInstances(acqPieceConsumerInstancesNumber), pieceEventsConsumer); + deployVerticle(vertx, verticleFactory, OrderEventConsumersVerticle.class, acqOrderConsumerInstancesNumber, acqOrderConsumerPoolSize, orderEventsConsumer); + deployVerticle(vertx, verticleFactory, OrderLineEventConsumersVerticle.class, acqOrderLineConsumerInstancesNumber, acqOrderLineConsumerPoolSize, orderLineEventsConsumer); + deployVerticle(vertx, verticleFactory, PieceEventConsumersVerticle.class, acqPieceConsumerInstancesNumber, acqPieceConsumerPoolSize, pieceEventsConsumer); + deployVerticle(vertx, verticleFactory, InvoiceEventConsumersVerticle.class, acqInvoiceConsumerInstancesNumber, acqInvoiceConsumerPoolSize, invoiceEventsConsumer); + deployVerticle(vertx, verticleFactory, InvoiceLineEventConsumersVerticle.class, acqInvoiceLineConsumerInstancesNumber, acqInvoiceLineConsumerPoolSize, invoiceLineEventsConsumer); + deployVerticle(vertx, verticleFactory, OrganizationEventConsumersVerticle.class, acqOrganizationConsumerInstancesNumber, acqOrganizationConsumerPoolSize, organizationsEventsConsumer); LOGGER.info("deployConsumersVerticles:: All consumer verticles were successfully deployed"); return GenericCompositeFuture.all(Arrays.asList( orderEventsConsumer.future(), orderLineEventsConsumer.future(), - pieceEventsConsumer.future())); + pieceEventsConsumer.future(), + invoiceEventsConsumer.future(), + invoiceLineEventsConsumer.future(), + organizationsEventsConsumer.future())); + } + + private void deployVerticle(Vertx vertx, VerticleFactory verticleFactory, Class consumerClass, + int acqOrderConsumerInstancesNumber, int acqOrderConsumerPoolSize, Promise orderEventsConsumer) { + DeploymentOptions deploymentOptions = new DeploymentOptions().setThreadingModel(ThreadingModel.WORKER) + .setInstances(acqOrderConsumerInstancesNumber).setWorkerPoolSize(acqOrderConsumerPoolSize); + vertx.deployVerticle(getVerticleName(verticleFactory, consumerClass), deploymentOptions, orderEventsConsumer); } private String getVerticleName(VerticleFactory verticleFactory, Class clazz) { diff --git a/mod-audit-server/src/main/java/org/folio/services/acquisition/InvoiceAuditEventsService.java b/mod-audit-server/src/main/java/org/folio/services/acquisition/InvoiceAuditEventsService.java new file mode 100644 index 00000000..e271de7d --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/services/acquisition/InvoiceAuditEventsService.java @@ -0,0 +1,31 @@ +package org.folio.services.acquisition; + +import io.vertx.core.Future; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import org.folio.rest.jaxrs.model.InvoiceAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceAuditEventCollection; + +public interface InvoiceAuditEventsService { + + /** + * Saves InvoiceAuditEvent + * + * @param invoiceAuditEvent + * @param tenantId id of tenant + * @return successful future if event has not been processed, or failed future otherwise + */ + Future> saveInvoiceAuditEvent(InvoiceAuditEvent invoiceAuditEvent, String tenantId); + + /** + * Searches for invoice audit events by invoice id + * + * @param invoiceId invoice id + * @param sortBy sort by + * @param sortOrder sort order + * @param limit limit + * @param offset offset + * @return future with InvoiceAuditEventCollection + */ + Future getAuditEventsByInvoiceId(String invoiceId, String sortBy, String sortOrder, int limit, int offset, String tenantId); +} diff --git a/mod-audit-server/src/main/java/org/folio/services/acquisition/InvoiceLineAuditEventsService.java b/mod-audit-server/src/main/java/org/folio/services/acquisition/InvoiceLineAuditEventsService.java new file mode 100644 index 00000000..f096c7dc --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/services/acquisition/InvoiceLineAuditEventsService.java @@ -0,0 +1,31 @@ +package org.folio.services.acquisition; + +import io.vertx.core.Future; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEventCollection; + +public interface InvoiceLineAuditEventsService { + + /** + * Saves InvoiceLineAuditEvent + * + * @param invoiceLineAuditEvent invoice line event to save + * @param tenantId id of tenant + * @return successful future if event has not been processed, or failed future otherwise + */ + Future> saveInvoiceLineAuditEvent(InvoiceLineAuditEvent invoiceLineAuditEvent, String tenantId); + + /** + * Searches for invoice line audit events by invoice line id + * + * @param invoiceLineId invoice line id + * @param sortBy sort by + * @param sortOrder sort order + * @param limit limit + * @param offset offset + * @return future with InvoiceLineAuditEventCollection + */ + Future getAuditEventsByInvoiceLineId(String invoiceLineId, String sortBy, String sortOrder, int limit, int offset, String tenantId); +} diff --git a/mod-audit-server/src/main/java/org/folio/services/acquisition/OrganizationAuditEventsService.java b/mod-audit-server/src/main/java/org/folio/services/acquisition/OrganizationAuditEventsService.java new file mode 100644 index 00000000..c6154ff4 --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/services/acquisition/OrganizationAuditEventsService.java @@ -0,0 +1,31 @@ +package org.folio.services.acquisition; + +import io.vertx.core.Future; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import org.folio.rest.jaxrs.model.OrganizationAuditEvent; +import org.folio.rest.jaxrs.model.OrganizationAuditEventCollection; + +public interface OrganizationAuditEventsService { + + /** + * Saves OrganizationAuditEvent + * + * @param organizationAuditEvent + * @param tenantId id of tenant + * @return successful future if event has not been processed, or failed future otherwise + */ + Future> saveOrganizationAuditEvent(OrganizationAuditEvent organizationAuditEvent, String tenantId); + + /** + * Searches for organization audit events by organization id + * + * @param organizationId organization id + * @param sortBy sort by + * @param sortOrder sort order + * @param limit limit + * @param offset offset + * @return future with OrganizationAuditEventCollection + */ + Future getAuditEventsByOrganizationId(String organizationId, String sortBy, String sortOrder, int limit, int offset, String tenantId); +} diff --git a/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/InvoiceAuditEventsServiceImpl.java b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/InvoiceAuditEventsServiceImpl.java new file mode 100644 index 00000000..d2e427c9 --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/InvoiceAuditEventsServiceImpl.java @@ -0,0 +1,42 @@ +package org.folio.services.acquisition.impl; + +import io.vertx.core.Future; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.dao.acquisition.InvoiceEventsDao; +import org.folio.rest.jaxrs.model.InvoiceAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceAuditEventCollection; +import org.folio.services.acquisition.InvoiceAuditEventsService; +import org.springframework.stereotype.Service; + +import static org.folio.util.ErrorUtils.handleFailures; + +@Service +public class InvoiceAuditEventsServiceImpl implements InvoiceAuditEventsService { + + private static final Logger LOGGER = LogManager.getLogger(); + + private final InvoiceEventsDao invoiceEventsDao; + + public InvoiceAuditEventsServiceImpl(InvoiceEventsDao invoiceEvenDao) { + this.invoiceEventsDao = invoiceEvenDao; + } + + @Override + public Future> saveInvoiceAuditEvent(InvoiceAuditEvent invoiceAuditEvent, String tenantId) { + LOGGER.debug("saveInvoiceAuditEvent:: Saving invoice audit event with invoiceId={} for tenantId={}", invoiceAuditEvent.getInvoiceId(), tenantId); + return invoiceEventsDao.save(invoiceAuditEvent, tenantId) + .recover(throwable -> { + LOGGER.error("handleFailures:: Could not save invoice audit event for Invoice id: {} in tenantId: {}", invoiceAuditEvent.getInvoiceId(), tenantId); + return handleFailures(throwable, invoiceAuditEvent.getId()); + }); + } + + @Override + public Future getAuditEventsByInvoiceId(String invoiceId, String sortBy, String sortOrder, int limit, int offset, String tenantId) { + LOGGER.debug("getAuditEventsByInvoiceId:: Retrieving audit events for invoiceId={} and tenantId={}", invoiceId, tenantId); + return invoiceEventsDao.getAuditEventsByInvoiceId(invoiceId, sortBy, sortOrder, limit, offset, tenantId); + } +} diff --git a/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/InvoiceLineAuditEventsServiceImpl.java b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/InvoiceLineAuditEventsServiceImpl.java new file mode 100644 index 00000000..9fc6c4d3 --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/InvoiceLineAuditEventsServiceImpl.java @@ -0,0 +1,42 @@ +package org.folio.services.acquisition.impl; + +import static org.folio.util.ErrorUtils.handleFailures; + +import io.vertx.core.Future; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.dao.acquisition.InvoiceLineEventsDao; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEventCollection; +import org.folio.services.acquisition.InvoiceLineAuditEventsService; +import org.springframework.stereotype.Service; + +@Service +public class InvoiceLineAuditEventsServiceImpl implements InvoiceLineAuditEventsService { + + private static final Logger LOGGER = LogManager.getLogger(); + + private final InvoiceLineEventsDao invoiceLineEventsDao; + + public InvoiceLineAuditEventsServiceImpl(InvoiceLineEventsDao invoiceLineEventsDao) { + this.invoiceLineEventsDao = invoiceLineEventsDao; + } + + @Override + public Future> saveInvoiceLineAuditEvent(InvoiceLineAuditEvent invoiceLineAuditEvent, String tenantId) { + LOGGER.debug("saveInvoiceLineAuditEvent:: Saving invoice line audit event with invoiceLineId={} in tenant Id={}", invoiceLineAuditEvent.getId(), tenantId); + return invoiceLineEventsDao.save(invoiceLineAuditEvent, tenantId) + .recover(throwable -> { + LOGGER.error("handleFailures:: Could not save invoice audit event for InvoiceLine id: {} in tenantId: {}", invoiceLineAuditEvent.getInvoiceLineId(), tenantId); + return handleFailures(throwable, invoiceLineAuditEvent.getId()); + }); + } + + @Override + public Future getAuditEventsByInvoiceLineId(String invoiceLineId, String sortBy, String sortOrder, int limit, int offset, String tenantId) { + LOGGER.debug("getAuditEventsByInvoiceLineId:: Retrieving audit events for invoiceLineId={} and tenantId={}", invoiceLineId, tenantId); + return invoiceLineEventsDao.getAuditEventsByInvoiceLineId(invoiceLineId, sortBy, sortOrder, limit, offset, tenantId); + } +} diff --git a/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrderAuditEventsServiceImpl.java b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrderAuditEventsServiceImpl.java index 5f254824..b14dcfe7 100644 --- a/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrderAuditEventsServiceImpl.java +++ b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrderAuditEventsServiceImpl.java @@ -39,5 +39,4 @@ public Future getAuditEventsByOrderId(String orderId, LOGGER.debug("getAuditEventsByOrderId:: Retrieving audit events for orderId={} and tenantId={}", orderId, tenantId); return orderEventsDao.getAuditEventsByOrderId(orderId, sortBy, sortOrder, limit, offset, tenantId); } - } diff --git a/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrderLineAuditEventsServiceImpl.java b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrderLineAuditEventsServiceImpl.java index 0e3d299d..c9f902e9 100644 --- a/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrderLineAuditEventsServiceImpl.java +++ b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrderLineAuditEventsServiceImpl.java @@ -39,5 +39,4 @@ public Future getAuditEventsByOrderLineId(String LOGGER.debug("getAuditEventsByOrderLineId:: Retrieving audit events for order line Id : {} and tenant Id : {}", orderLineId, tenantId); return orderLineEventsDao.getAuditEventsByOrderLineId(orderLineId, sortBy, sortOrder, limit, offset, tenantId); } - } diff --git a/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrganizationAuditEventsServiceImpl.java b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrganizationAuditEventsServiceImpl.java new file mode 100644 index 00000000..2404f6b0 --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/OrganizationAuditEventsServiceImpl.java @@ -0,0 +1,42 @@ +package org.folio.services.acquisition.impl; + +import io.vertx.core.Future; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.dao.acquisition.OrganizationEventsDao; +import org.folio.rest.jaxrs.model.OrganizationAuditEvent; +import org.folio.rest.jaxrs.model.OrganizationAuditEventCollection; +import org.folio.services.acquisition.OrganizationAuditEventsService; +import org.springframework.stereotype.Service; + +import static org.folio.util.ErrorUtils.handleFailures; + +@Service +public class OrganizationAuditEventsServiceImpl implements OrganizationAuditEventsService { + + private static final Logger LOGGER = LogManager.getLogger(); + + private final OrganizationEventsDao organizationEventsDao; + + public OrganizationAuditEventsServiceImpl(OrganizationEventsDao organizationEvenDao) { + this.organizationEventsDao = organizationEvenDao; + } + + @Override + public Future> saveOrganizationAuditEvent(OrganizationAuditEvent organizationAuditEvent, String tenantId) { + LOGGER.debug("saveOrganizationAuditEvent:: Saving organization audit event with organizationId={} for tenantId={}", organizationAuditEvent.getOrganizationId(), tenantId); + return organizationEventsDao.save(organizationAuditEvent, tenantId) + .recover(throwable -> { + LOGGER.error("handleFailures:: Could not save organization audit event for Organization id: {} in tenantId: {}", organizationAuditEvent.getOrganizationId(), tenantId); + return handleFailures(throwable, organizationAuditEvent.getId()); + }); + } + + @Override + public Future getAuditEventsByOrganizationId(String organizationId, String sortBy, String sortOrder, int limit, int offset, String tenantId) { + LOGGER.debug("getAuditEventsByOrganizationId:: Retrieving audit events for organizationId={} and tenantId={}", organizationId, tenantId); + return organizationEventsDao.getAuditEventsByOrganizationId(organizationId, sortBy, sortOrder, limit, offset, tenantId); + } +} diff --git a/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/PieceAuditEventsServiceImpl.java b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/PieceAuditEventsServiceImpl.java index 299b6e0a..5d9be4d0 100644 --- a/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/PieceAuditEventsServiceImpl.java +++ b/mod-audit-server/src/main/java/org/folio/services/acquisition/impl/PieceAuditEventsServiceImpl.java @@ -44,5 +44,4 @@ public Future getAuditEventsWithStatusChangesByPieceI LOGGER.debug("getAuditEventsByOrderId:: Retrieving audit events with unique status changes for pieceId={} and tenantId={}", pieceId, tenantId); return pieceEventsDao.getAuditEventsWithStatusChangesByPieceId(pieceId, sortBy, sortOrder, limit, offset, tenantId); } - } diff --git a/mod-audit-server/src/main/java/org/folio/util/AcquisitionEventType.java b/mod-audit-server/src/main/java/org/folio/util/AcquisitionEventType.java index 3ecb182e..d8150206 100644 --- a/mod-audit-server/src/main/java/org/folio/util/AcquisitionEventType.java +++ b/mod-audit-server/src/main/java/org/folio/util/AcquisitionEventType.java @@ -3,7 +3,10 @@ public enum AcquisitionEventType { ACQ_ORDER_CHANGED("ACQ_ORDER_CHANGED"), ACQ_ORDER_LINE_CHANGED("ACQ_ORDER_LINE_CHANGED"), - ACQ_PIECE_CHANGED("ACQ_PIECE_CHANGED"); + ACQ_PIECE_CHANGED("ACQ_PIECE_CHANGED"), + ACQ_INVOICE_CHANGED("ACQ_INVOICE_CHANGED"), + ACQ_INVOICE_LINE_CHANGED("ACQ_INVOICE_LINE_CHANGED"), + ACQ_ORGANIZATION_CHANGED("ACQ_ORGANIZATION_CHANGED"); private final String topicName; diff --git a/mod-audit-server/src/main/java/org/folio/util/AuditEventDBConstants.java b/mod-audit-server/src/main/java/org/folio/util/AuditEventDBConstants.java index 62d40cfc..7f3fc3d0 100644 --- a/mod-audit-server/src/main/java/org/folio/util/AuditEventDBConstants.java +++ b/mod-audit-server/src/main/java/org/folio/util/AuditEventDBConstants.java @@ -14,6 +14,12 @@ private AuditEventDBConstants() {} public static final String PIECE_ID_FIELD = "piece_id"; + public static final String INVOICE_ID_FIELD = "invoice_id"; + + public static final String INVOICE_LINE_ID_FIELD = "invoice_line_id"; + + public static final String ORGANIZATION_ID_FIELD = "organization_id"; + public static final String USER_ID_FIELD = "user_id"; public static final String EVENT_DATE_FIELD = "event_date"; diff --git a/mod-audit-server/src/main/java/org/folio/util/ErrorUtils.java b/mod-audit-server/src/main/java/org/folio/util/ErrorUtils.java index 4d7b8e74..df37cca0 100644 --- a/mod-audit-server/src/main/java/org/folio/util/ErrorUtils.java +++ b/mod-audit-server/src/main/java/org/folio/util/ErrorUtils.java @@ -12,6 +12,7 @@ import java.util.Collections; public class ErrorUtils { + private ErrorUtils(){ } @@ -26,7 +27,7 @@ public static Errors buildErrors(String statusCode, Throwable throwable) { } public static Future handleFailures(Throwable throwable, String id) { - return (throwable instanceof PgException pgException && pgException.getCode().equals(UNIQUE_CONSTRAINT_VIOLATION_CODE)) ? + return (throwable instanceof PgException pgException && pgException.getSqlState().equals(UNIQUE_CONSTRAINT_VIOLATION_CODE)) ? Future.failedFuture(new DuplicateEventException(String.format("Event with id=%s is already processed.", id))) : Future.failedFuture(throwable); } diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/InvoiceEventConsumersVerticle.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/InvoiceEventConsumersVerticle.java new file mode 100644 index 00000000..25afa5cd --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/InvoiceEventConsumersVerticle.java @@ -0,0 +1,26 @@ +package org.folio.verticle.acquisition; + +import org.folio.kafka.AsyncRecordHandler; +import org.folio.util.AcquisitionEventType; +import org.folio.verticle.AbstractConsumersVerticle; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class InvoiceEventConsumersVerticle extends AbstractConsumersVerticle { + + @Autowired + private AsyncRecordHandler invoiceEventsHandler; + + @Override + public List getEvents() { + return List.of(AcquisitionEventType.ACQ_INVOICE_CHANGED.getTopicName()); + } + + @Override + public AsyncRecordHandler getHandler() { + return invoiceEventsHandler; + } +} diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/InvoiceLineEventConsumersVerticle.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/InvoiceLineEventConsumersVerticle.java new file mode 100644 index 00000000..ff371601 --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/InvoiceLineEventConsumersVerticle.java @@ -0,0 +1,26 @@ +package org.folio.verticle.acquisition; + +import org.folio.kafka.AsyncRecordHandler; +import org.folio.util.AcquisitionEventType; +import org.folio.verticle.AbstractConsumersVerticle; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class InvoiceLineEventConsumersVerticle extends AbstractConsumersVerticle { + + @Autowired + private AsyncRecordHandler invoiceLineEventsHandler; + + @Override + public List getEvents() { + return List.of(AcquisitionEventType.ACQ_INVOICE_LINE_CHANGED.getTopicName()); + } + + @Override + public AsyncRecordHandler getHandler() { + return invoiceLineEventsHandler; + } +} diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrderEventConsumersVerticle.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrderEventConsumersVerticle.java index 63e4694d..64c082bd 100644 --- a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrderEventConsumersVerticle.java +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrderEventConsumersVerticle.java @@ -1,7 +1,6 @@ package org.folio.verticle.acquisition; import org.folio.kafka.AsyncRecordHandler; -import org.folio.kafka.KafkaConfig; import org.folio.util.AcquisitionEventType; import org.folio.verticle.AbstractConsumersVerticle; import org.springframework.beans.factory.annotation.Autowired; @@ -11,15 +10,16 @@ @Component public class OrderEventConsumersVerticle extends AbstractConsumersVerticle { - @Autowired - private KafkaConfig kafkaConfig; + @Autowired private AsyncRecordHandler orderEventsHandler; + @Override public List getEvents() { return List.of(AcquisitionEventType.ACQ_ORDER_CHANGED.getTopicName()); } + @Override public AsyncRecordHandler getHandler() { return orderEventsHandler; } diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrderLineEventConsumersVerticle.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrderLineEventConsumersVerticle.java index 1cbc45c3..ac7d4e3b 100644 --- a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrderLineEventConsumersVerticle.java +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrderLineEventConsumersVerticle.java @@ -1,7 +1,6 @@ package org.folio.verticle.acquisition; import org.folio.kafka.AsyncRecordHandler; -import org.folio.kafka.KafkaConfig; import org.folio.util.AcquisitionEventType; import org.folio.verticle.AbstractConsumersVerticle; import org.springframework.beans.factory.annotation.Autowired; @@ -11,8 +10,7 @@ @Component public class OrderLineEventConsumersVerticle extends AbstractConsumersVerticle { - @Autowired - private KafkaConfig kafkaConfig; + @Autowired private AsyncRecordHandler orderLineEventsHandler; diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrganizationEventConsumersVerticle.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrganizationEventConsumersVerticle.java new file mode 100644 index 00000000..28bf6afd --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/OrganizationEventConsumersVerticle.java @@ -0,0 +1,26 @@ +package org.folio.verticle.acquisition; + +import org.folio.kafka.AsyncRecordHandler; +import org.folio.util.AcquisitionEventType; +import org.folio.verticle.AbstractConsumersVerticle; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class OrganizationEventConsumersVerticle extends AbstractConsumersVerticle { + + @Autowired + private AsyncRecordHandler organizationEventsHandler; + + @Override + public List getEvents() { + return List.of(AcquisitionEventType.ACQ_ORGANIZATION_CHANGED.getTopicName()); + } + + @Override + public AsyncRecordHandler getHandler() { + return organizationEventsHandler; + } +} diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/InvoiceEventsHandler.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/InvoiceEventsHandler.java new file mode 100644 index 00000000..a204e3d2 --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/InvoiceEventsHandler.java @@ -0,0 +1,55 @@ +package org.folio.verticle.acquisition.consumers; + +import io.vertx.core.Future; +import io.vertx.core.Promise; +import io.vertx.core.Vertx; +import io.vertx.core.json.JsonObject; +import io.vertx.kafka.client.consumer.KafkaConsumerRecord; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.kafka.AsyncRecordHandler; +import org.folio.kafka.KafkaHeaderUtils; +import org.folio.kafka.exception.DuplicateEventException; +import org.folio.rest.jaxrs.model.InvoiceAuditEvent; +import org.folio.rest.util.OkapiConnectionParams; +import org.folio.services.acquisition.InvoiceAuditEventsService; +import org.springframework.stereotype.Component; + +@Component +public class InvoiceEventsHandler implements AsyncRecordHandler { + + private static final Logger LOGGER = LogManager.getLogger(); + + private final InvoiceAuditEventsService invoiceAuditEventsService; + private final Vertx vertx; + + public InvoiceEventsHandler(Vertx vertx, + InvoiceAuditEventsService invoiceAuditEventsService) { + this.vertx = vertx; + this.invoiceAuditEventsService = invoiceAuditEventsService; + } + + @Override + public Future handle(KafkaConsumerRecord kafkaConsumerRecord) { + var result = Promise.promise(); + var kafkaHeaders = kafkaConsumerRecord.headers(); + var okapiConnectionParams = new OkapiConnectionParams(KafkaHeaderUtils.kafkaHeadersToMap(kafkaHeaders), vertx); + var event = new JsonObject(kafkaConsumerRecord.value()).mapTo(InvoiceAuditEvent.class); + LOGGER.info("handle:: Starting processing of Invoice audit event with id: {} for invoice id: {}", event.getId(), event.getInvoiceId()); + invoiceAuditEventsService.saveInvoiceAuditEvent(event, okapiConnectionParams.getTenantId()) + .onSuccess(ar -> { + LOGGER.info("handle:: Invoice audit event with id: {} has been processed for invoice id: {}", event.getId(), event.getInvoiceId()); + result.complete(event.getId()); + }) + .onFailure(e -> { + if (e instanceof DuplicateEventException) { + LOGGER.info("handle:: Duplicate Invoice audit event with id: {} for invoice id: {} received, skipped processing", event.getId(), event.getInvoiceId()); + result.complete(event.getId()); + } else { + LOGGER.error("Processing of Invoice audit event with id: {} for invoice id: {} has been failed", event.getId(), event.getInvoiceId(), e); + result.fail(e); + } + }); + return result.future(); + } +} diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/InvoiceLineEventsHandler.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/InvoiceLineEventsHandler.java new file mode 100644 index 00000000..75ce87ef --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/InvoiceLineEventsHandler.java @@ -0,0 +1,56 @@ +package org.folio.verticle.acquisition.consumers; + +import io.vertx.core.Future; +import io.vertx.core.Promise; +import io.vertx.core.Vertx; +import io.vertx.core.json.JsonObject; +import io.vertx.kafka.client.consumer.KafkaConsumerRecord; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.kafka.AsyncRecordHandler; +import org.folio.kafka.KafkaHeaderUtils; +import org.folio.kafka.exception.DuplicateEventException; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; +import org.folio.rest.util.OkapiConnectionParams; +import org.folio.services.acquisition.InvoiceLineAuditEventsService; +import org.springframework.stereotype.Component; + +@Component +public class InvoiceLineEventsHandler implements AsyncRecordHandler { + + private static final Logger LOGGER = LogManager.getLogger(); + + private final InvoiceLineAuditEventsService invoiceLineAuditEventsService; + private final Vertx vertx; + + public InvoiceLineEventsHandler(Vertx vertx, + InvoiceLineAuditEventsService invoiceLineAuditEventsService) { + this.vertx = vertx; + this.invoiceLineAuditEventsService = invoiceLineAuditEventsService; + } + + @Override + public Future handle(KafkaConsumerRecord kafkaConsumerRecord) { + var result = Promise.promise(); + var kafkaHeaders = kafkaConsumerRecord.headers(); + var okapiConnectionParams = new OkapiConnectionParams(KafkaHeaderUtils.kafkaHeadersToMap(kafkaHeaders), vertx); + var event = new JsonObject(kafkaConsumerRecord.value()).mapTo(InvoiceLineAuditEvent.class); + LOGGER.info("handle:: Starting processing of Invoice Line audit event with id: {} for invoice line id: {}", event.getId(), event.getInvoiceLineId()); + invoiceLineAuditEventsService.saveInvoiceLineAuditEvent(event, okapiConnectionParams.getTenantId()) + .onSuccess(ar -> { + LOGGER.info("handle:: Invoice Line audit event with id: {} has been processed for invoice line id: {}", + event.getId(), event.getInvoiceLineId()); + result.complete(event.getId()); + }) + .onFailure(e -> { + if (e instanceof DuplicateEventException) { + LOGGER.info("handle:: Duplicate Invoice Line audit event with id: {} for invoice line id: {} received, skipped processing", event.getId(), event.getInvoiceLineId()); + result.complete(event.getId()); + } else { + LOGGER.error("Processing of Invoice Line audit event with id: {} for invoice line id: {} has been failed", event.getId(), event.getInvoiceLineId(), e); + result.fail(e); + } + }); + return result.future(); + } +} diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrderEventsHandler.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrderEventsHandler.java index 8d1f5a9e..b299cae9 100644 --- a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrderEventsHandler.java +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrderEventsHandler.java @@ -5,7 +5,6 @@ import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.kafka.client.consumer.KafkaConsumerRecord; -import io.vertx.kafka.client.producer.KafkaHeader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.folio.kafka.AsyncRecordHandler; @@ -14,35 +13,29 @@ import org.folio.rest.jaxrs.model.OrderAuditEvent; import org.folio.rest.util.OkapiConnectionParams; import org.folio.services.acquisition.OrderAuditEventsService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; - @Component public class OrderEventsHandler implements AsyncRecordHandler { private static final Logger LOGGER = LogManager.getLogger(); - private OrderAuditEventsService orderAuditEventsService; - - private Vertx vertx; + private final OrderAuditEventsService orderAuditEventsService; + private final Vertx vertx; - public OrderEventsHandler(@Autowired Vertx vertx, - @Autowired OrderAuditEventsService orderAuditEventsService) { + public OrderEventsHandler(Vertx vertx, + OrderAuditEventsService orderAuditEventsService) { this.vertx = vertx; this.orderAuditEventsService = orderAuditEventsService; } @Override - public Future handle(KafkaConsumerRecord record) { - - Promise result = Promise.promise(); - List kafkaHeaders = record.headers(); - OkapiConnectionParams okapiConnectionParams = new OkapiConnectionParams(KafkaHeaderUtils.kafkaHeadersToMap(kafkaHeaders), vertx); - OrderAuditEvent event = new JsonObject(record.value()).mapTo(OrderAuditEvent.class); + public Future handle(KafkaConsumerRecord kafkaConsumerRecord) { + var result = Promise.promise(); + var kafkaHeaders = kafkaConsumerRecord.headers(); + var okapiConnectionParams = new OkapiConnectionParams(KafkaHeaderUtils.kafkaHeadersToMap(kafkaHeaders), vertx); + var event = new JsonObject(kafkaConsumerRecord.value()).mapTo(OrderAuditEvent.class); LOGGER.info("handle:: Starting processing of Order audit event with id: {} for order id: {}", event.getId(), event.getOrderId()); - orderAuditEventsService.saveOrderAuditEvent(event, okapiConnectionParams.getTenantId()) .onSuccess(ar -> { LOGGER.info("handle:: Order audit event with id: {} has been processed for order id: {}", event.getId(), event.getOrderId()); @@ -57,7 +50,6 @@ public Future handle(KafkaConsumerRecord record) { result.fail(e); } }); - return result.future(); } } diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrderLineEventsHandler.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrderLineEventsHandler.java index d45c3618..c557af76 100644 --- a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrderLineEventsHandler.java +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrderLineEventsHandler.java @@ -5,7 +5,6 @@ import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.kafka.client.consumer.KafkaConsumerRecord; -import io.vertx.kafka.client.producer.KafkaHeader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.folio.kafka.AsyncRecordHandler; @@ -14,35 +13,30 @@ import org.folio.rest.jaxrs.model.OrderLineAuditEvent; import org.folio.rest.util.OkapiConnectionParams; import org.folio.services.acquisition.OrderLineAuditEventsService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; - @Component public class OrderLineEventsHandler implements AsyncRecordHandler { private static final Logger LOGGER = LogManager.getLogger(); - private OrderLineAuditEventsService orderLineAuditEventsService; - - private Vertx vertx; + private final OrderLineAuditEventsService orderLineAuditEventsService; + private final Vertx vertx; - public OrderLineEventsHandler(@Autowired Vertx vertx, - @Autowired OrderLineAuditEventsService orderLineAuditEventsService) { + public OrderLineEventsHandler(Vertx vertx, + OrderLineAuditEventsService orderLineAuditEventsService) { this.vertx = vertx; this.orderLineAuditEventsService = orderLineAuditEventsService; } @Override - public Future handle(KafkaConsumerRecord record) { - Promise result = Promise.promise(); - List kafkaHeaders = record.headers(); - OkapiConnectionParams okapiConnectionParams = new OkapiConnectionParams(KafkaHeaderUtils.kafkaHeadersToMap(kafkaHeaders), vertx); - OrderLineAuditEvent event = new JsonObject(record.value()).mapTo(OrderLineAuditEvent.class); + public Future handle(KafkaConsumerRecord kafkaConsumerRecord) { + var result = Promise.promise(); + var kafkaHeaders = kafkaConsumerRecord.headers(); + var okapiConnectionParams = new OkapiConnectionParams(KafkaHeaderUtils.kafkaHeadersToMap(kafkaHeaders), vertx); + var event = new JsonObject(kafkaConsumerRecord.value()).mapTo(OrderLineAuditEvent.class); LOGGER.info("handle:: Starting processing of Order Line audit event with id: {} for order id: {} and order line id: {}", event.getId(), event.getOrderId(), event.getOrderLineId()); - orderLineAuditEventsService.saveOrderLineAuditEvent(event, okapiConnectionParams.getTenantId()) .onSuccess(ar -> { LOGGER.info("handle:: Order Line audit event with id: {} has been processed for order id: {} and order line id: {}", @@ -60,7 +54,6 @@ public Future handle(KafkaConsumerRecord record) { result.fail(e); } }); - return result.future(); } } diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrganizationEventsHandler.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrganizationEventsHandler.java new file mode 100644 index 00000000..94d1b0b5 --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/OrganizationEventsHandler.java @@ -0,0 +1,55 @@ +package org.folio.verticle.acquisition.consumers; + +import io.vertx.core.Future; +import io.vertx.core.Promise; +import io.vertx.core.Vertx; +import io.vertx.core.json.JsonObject; +import io.vertx.kafka.client.consumer.KafkaConsumerRecord; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.kafka.AsyncRecordHandler; +import org.folio.kafka.KafkaHeaderUtils; +import org.folio.kafka.exception.DuplicateEventException; +import org.folio.rest.jaxrs.model.OrganizationAuditEvent; +import org.folio.rest.util.OkapiConnectionParams; +import org.folio.services.acquisition.OrganizationAuditEventsService; +import org.springframework.stereotype.Component; + +@Component +public class OrganizationEventsHandler implements AsyncRecordHandler { + + private static final Logger LOGGER = LogManager.getLogger(); + + private final OrganizationAuditEventsService organizationAuditEventsService; + private final Vertx vertx; + + public OrganizationEventsHandler(Vertx vertx, + OrganizationAuditEventsService organizationAuditEventsService) { + this.vertx = vertx; + this.organizationAuditEventsService = organizationAuditEventsService; + } + + @Override + public Future handle(KafkaConsumerRecord kafkaConsumerRecord) { + var result = Promise.promise(); + var kafkaHeaders = kafkaConsumerRecord.headers(); + var okapiConnectionParams = new OkapiConnectionParams(KafkaHeaderUtils.kafkaHeadersToMap(kafkaHeaders), vertx); + var event = new JsonObject(kafkaConsumerRecord.value()).mapTo(OrganizationAuditEvent.class); + LOGGER.info("handle:: Starting processing of Organization audit event with id: {} for organization id: {}", event.getId(), event.getOrganizationId()); + organizationAuditEventsService.saveOrganizationAuditEvent(event, okapiConnectionParams.getTenantId()) + .onSuccess(ar -> { + LOGGER.info("handle:: Organization audit event with id: {} has been processed for organization id: {}", event.getId(), event.getOrganizationId()); + result.complete(event.getId()); + }) + .onFailure(e -> { + if (e instanceof DuplicateEventException) { + LOGGER.info("handle:: Duplicate Organization audit event with id: {} for organization id: {} received, skipped processing", event.getId(), event.getOrganizationId()); + result.complete(event.getId()); + } else { + LOGGER.error("Processing of Organization audit event with id: {} for organization id: {} has been failed", event.getId(), event.getOrganizationId(), e); + result.fail(e); + } + }); + return result.future(); + } +} diff --git a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/PieceEventsHandler.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/PieceEventsHandler.java index 90a4e098..942e2747 100644 --- a/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/PieceEventsHandler.java +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/PieceEventsHandler.java @@ -1,13 +1,10 @@ package org.folio.verticle.acquisition.consumers; -import java.util.List; - import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.kafka.client.consumer.KafkaConsumerRecord; -import io.vertx.kafka.client.producer.KafkaHeader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.folio.kafka.AsyncRecordHandler; @@ -28,18 +25,17 @@ public class PieceEventsHandler implements AsyncRecordHandler { public PieceEventsHandler(Vertx vertx, PieceAuditEventsService pieceAuditEventsService) { - this.pieceAuditEventsService = pieceAuditEventsService; this.vertx = vertx; + this.pieceAuditEventsService = pieceAuditEventsService; } @Override public Future handle(KafkaConsumerRecord kafkaConsumerRecord) { - Promise result = Promise.promise(); - List kafkaHeaders = kafkaConsumerRecord.headers(); - OkapiConnectionParams okapiConnectionParams = new OkapiConnectionParams(KafkaHeaderUtils.kafkaHeadersToMap(kafkaHeaders), vertx); - PieceAuditEvent event = new JsonObject(kafkaConsumerRecord.value()).mapTo(PieceAuditEvent.class); + var result = Promise.promise(); + var kafkaHeaders = kafkaConsumerRecord.headers(); + var okapiConnectionParams = new OkapiConnectionParams(KafkaHeaderUtils.kafkaHeadersToMap(kafkaHeaders), vertx); + var event = new JsonObject(kafkaConsumerRecord.value()).mapTo(PieceAuditEvent.class); LOGGER.info("handle:: Starting processing of Piece audit event with id: {} for piece id: {}", event.getId(), event.getPieceId()); - pieceAuditEventsService.savePieceAuditEvent(event, okapiConnectionParams.getTenantId()) .onSuccess(ar -> { LOGGER.info("handle:: Piece audit event with id: {} has been processed for piece id: {}", event.getId(), event.getPieceId()); @@ -54,7 +50,6 @@ public Future handle(KafkaConsumerRecord kafkaConsumerRe result.fail(e); } }); - return result.future(); } } diff --git a/mod-audit-server/src/main/resources/templates/db_scripts/acquisition/create_acquisition_invoice_line_log_table.sql b/mod-audit-server/src/main/resources/templates/db_scripts/acquisition/create_acquisition_invoice_line_log_table.sql new file mode 100644 index 00000000..3bfce0c6 --- /dev/null +++ b/mod-audit-server/src/main/resources/templates/db_scripts/acquisition/create_acquisition_invoice_line_log_table.sql @@ -0,0 +1,12 @@ +CREATE TABLE IF NOT EXISTS acquisition_invoice_line_log ( + id uuid PRIMARY KEY, + action text NOT NULL, + invoice_id uuid NOT NULL, + invoice_line_id uuid NOT NULL, + user_id uuid NOT NULL, + event_date timestamp NOT NULL, + action_date timestamp NOT NULL, + modified_content_snapshot jsonb +); + +CREATE INDEX IF NOT EXISTS invoice_line_id_index ON acquisition_invoice_line_log USING BTREE (invoice_line_id); diff --git a/mod-audit-server/src/main/resources/templates/db_scripts/acquisition/create_acquisition_invoice_log_table.sql b/mod-audit-server/src/main/resources/templates/db_scripts/acquisition/create_acquisition_invoice_log_table.sql new file mode 100644 index 00000000..10c8f7b9 --- /dev/null +++ b/mod-audit-server/src/main/resources/templates/db_scripts/acquisition/create_acquisition_invoice_log_table.sql @@ -0,0 +1,11 @@ +CREATE TABLE IF NOT EXISTS acquisition_invoice_log ( + id uuid PRIMARY KEY, + action text NOT NULL, + invoice_id uuid NOT NULL, + user_id uuid NOT NULL, + event_date timestamp NOT NULL, + action_date timestamp NOT NULL, + modified_content_snapshot jsonb +); + +CREATE INDEX IF NOT EXISTS invoice_id_index ON acquisition_invoice_log USING BTREE (invoice_id); diff --git a/mod-audit-server/src/main/resources/templates/db_scripts/acquisition/create_acquisition_organization_log_table.sql b/mod-audit-server/src/main/resources/templates/db_scripts/acquisition/create_acquisition_organization_log_table.sql new file mode 100644 index 00000000..791766f2 --- /dev/null +++ b/mod-audit-server/src/main/resources/templates/db_scripts/acquisition/create_acquisition_organization_log_table.sql @@ -0,0 +1,11 @@ +CREATE TABLE IF NOT EXISTS acquisition_organization_log ( + id uuid PRIMARY KEY, + action text NOT NULL, + organization_id uuid NOT NULL, + user_id uuid NOT NULL, + event_date timestamp NOT NULL, + action_date timestamp NOT NULL, + modified_content_snapshot jsonb +); + +CREATE INDEX IF NOT EXISTS organization_id_index ON acquisition_organization_log USING BTREE (organization_id); diff --git a/mod-audit-server/src/main/resources/templates/db_scripts/schema.json b/mod-audit-server/src/main/resources/templates/db_scripts/schema.json index be4d0804..7cfe0f9a 100644 --- a/mod-audit-server/src/main/resources/templates/db_scripts/schema.json +++ b/mod-audit-server/src/main/resources/templates/db_scripts/schema.json @@ -79,6 +79,21 @@ "run": "after", "snippetPath": "acquisition/create_acquisition_piece_log_table.sql", "fromModuleVersion": "mod-audit-2.9.0" + }, + { + "run": "after", + "snippetPath": "acquisition/create_acquisition_invoice_log_table.sql", + "fromModuleVersion": "mod-audit-3.0.0" + }, + { + "run": "after", + "snippetPath": "acquisition/create_acquisition_invoice_line_log_table.sql", + "fromModuleVersion": "mod-audit-3.0.0" + }, + { + "run": "after", + "snippetPath": "acquisition/create_acquisition_organization_log_table.sql", + "fromModuleVersion": "mod-audit-3.0.0" } ] } diff --git a/mod-audit-server/src/test/java/org/folio/CopilotGenerated.java b/mod-audit-server/src/test/java/org/folio/CopilotGenerated.java new file mode 100644 index 00000000..590f0c49 --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/CopilotGenerated.java @@ -0,0 +1,25 @@ +package org.folio; + +import org.springframework.core.annotation.AliasFor; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotation to indicate that test(s) in the class are generated by GitHub Copilot. + *

+ * Set value or partiallyGenerated attribute to true + * if the generated test(s) were significantly modified/altered by the developer. + */ +@Target({ElementType.TYPE, ElementType.METHOD}) +@Retention(RetentionPolicy.SOURCE) +public @interface CopilotGenerated { + + @AliasFor("partiallyGenerated") + boolean value() default false; + + @AliasFor("value") + boolean partiallyGenerated() default false; +} diff --git a/mod-audit-server/src/test/java/org/folio/TestSuite.java b/mod-audit-server/src/test/java/org/folio/TestSuite.java index 797a0916..06ddbe3c 100644 --- a/mod-audit-server/src/test/java/org/folio/TestSuite.java +++ b/mod-audit-server/src/test/java/org/folio/TestSuite.java @@ -12,6 +12,7 @@ import io.restassured.RestAssured; import io.vertx.core.DeploymentOptions; +import io.vertx.core.ThreadingModel; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import net.mguenther.kafka.junit.EmbeddedKafkaCluster; @@ -23,6 +24,8 @@ import org.folio.builder.service.ManualBlockRecordBuilderTest; import org.folio.builder.service.NoticeRecordBuilderTest; import org.folio.builder.service.RequestRecordBuilderTest; +import org.folio.dao.InvoiceEventsDaoTest; +import org.folio.dao.InvoiceLineEventsDaoTest; import org.folio.dao.OrderEventsDaoTest; import org.folio.dao.OrderLineEventsDaoTest; import org.folio.dao.PieceEventsDaoTest; @@ -32,10 +35,14 @@ import org.folio.rest.impl.AuditDataImplApiTest; import org.folio.rest.impl.AuditHandlersImplApiTest; import org.folio.rest.impl.CirculationLogsImplApiTest; +import org.folio.rest.impl.InvoiceEventsHandlerMockTest; +import org.folio.rest.impl.InvoiceLineEventsHandlerMockTest; import org.folio.rest.impl.OrderEventsHandlerMockTest; import org.folio.rest.impl.OrderLineEventsHandlerMockTest; import org.folio.rest.impl.PieceEventsHandlerMockTest; import org.folio.rest.persist.PostgresClient; +import org.folio.services.InvoiceAuditEventsServiceTest; +import org.folio.services.InvoiceLineAuditEventsServiceTest; import org.folio.services.OrderAuditEventsServiceTest; import org.folio.services.OrderLineAuditEventsServiceTest; import org.folio.services.PieceAuditEventsServiceTest; @@ -66,7 +73,7 @@ public static void globalInitialize() throws InterruptedException, ExecutionExce DeploymentOptions options = new DeploymentOptions(); options.setConfig(new JsonObject().put("http.port", port).put("mock.httpclient", "true")); - options.setWorker(true); + options.setThreadingModel(ThreadingModel.WORKER); startKafkaMockServer(); String[] hostAndPort = kafkaCluster.getBrokerList().split(":"); @@ -194,6 +201,30 @@ class PieceAuditEventsServiceNestedTest extends PieceAuditEventsServiceTest { class PieceEventsHandlerMockNestedTest extends PieceEventsHandlerMockTest { } + @Nested + class InvoiceEventsHandlerMockNestedTest extends InvoiceEventsHandlerMockTest { + } + + @Nested + class InvoiceAuditEventsServiceNestedTest extends InvoiceAuditEventsServiceTest { + } + + @Nested + class InvoiceEventsDaoNestedTest extends InvoiceEventsDaoTest { + } + + @Nested + class InvoiceLineEventsHandlerMockNestedTest extends InvoiceLineEventsHandlerMockTest { + } + + @Nested + class InvoiceLineAuditEventsServiceNestedTest extends InvoiceLineAuditEventsServiceTest { + } + + @Nested + class InvoiceLineEventsDaoNestedTest extends InvoiceLineEventsDaoTest { + } + @Nested class AuditDataImplApiTestNested extends AuditDataImplApiTest { } diff --git a/mod-audit-server/src/test/java/org/folio/dao/InvoiceEventsDaoTest.java b/mod-audit-server/src/test/java/org/folio/dao/InvoiceEventsDaoTest.java new file mode 100644 index 00000000..e1c5e05a --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/dao/InvoiceEventsDaoTest.java @@ -0,0 +1,80 @@ +package org.folio.dao; + +import static org.folio.utils.EntityUtils.TENANT_ID; +import static org.folio.utils.EntityUtils.createInvoiceAuditEvent; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.UUID; + +import io.vertx.core.Vertx; +import io.vertx.pgclient.PgException; +import org.folio.CopilotGenerated; +import org.folio.dao.acquisition.impl.InvoiceEventsDaoImpl; +import org.folio.rest.jaxrs.model.InvoiceAuditEvent; +import org.folio.util.PostgresClientFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; + +@CopilotGenerated +public class InvoiceEventsDaoTest { + + @Spy + private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); + @InjectMocks + InvoiceEventsDaoImpl invoiceEventDao; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + invoiceEventDao = new InvoiceEventsDaoImpl(postgresClientFactory); + } + + @Test + void shouldCreateEventProcessed() { + var invoiceAuditEvent = createInvoiceAuditEvent(UUID.randomUUID().toString()); + + var saveFuture = invoiceEventDao.save(invoiceAuditEvent, TENANT_ID); + saveFuture.onComplete(ar -> assertTrue(ar.succeeded())); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); + } + + @Test + void shouldThrowConstraintViolation() { + var invoiceAuditEvent = createInvoiceAuditEvent(UUID.randomUUID().toString()); + + var saveFuture = invoiceEventDao.save(invoiceAuditEvent, TENANT_ID); + saveFuture.onComplete(ar -> { + var reSaveFuture = invoiceEventDao.save(invoiceAuditEvent, TENANT_ID); + reSaveFuture.onComplete(re -> { + assertTrue(re.failed()); + assertTrue(re.cause() instanceof PgException); + assertEquals("ERROR: duplicate key value violates unique constraint \"acquisition_invoice_log_pkey\" (23505)", re.cause().getMessage()); + }); + }); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); + } + + @Test + void shouldGetCreatedEvent() { + var id = UUID.randomUUID().toString(); + var invoiceAuditEvent = createInvoiceAuditEvent(id); + + invoiceEventDao.save(invoiceAuditEvent, TENANT_ID); + + var dto = invoiceEventDao.getAuditEventsByInvoiceId(id, "action_date", "desc", 1, 1, TENANT_ID); + dto.onComplete(ar -> { + var invoiceAuditEventOptional = ar.result(); + var invoiceAuditEventList = invoiceAuditEventOptional.getInvoiceAuditEvents(); + + assertEquals(invoiceAuditEventList.get(0).getId(), id); + assertEquals(InvoiceAuditEvent.Action.CREATE.value(), invoiceAuditEventList.get(0).getAction().value()); + }); + verify(postgresClientFactory, times(2)).createInstance(TENANT_ID); + } +} diff --git a/mod-audit-server/src/test/java/org/folio/dao/InvoiceLineEventsDaoTest.java b/mod-audit-server/src/test/java/org/folio/dao/InvoiceLineEventsDaoTest.java new file mode 100644 index 00000000..9d7ec138 --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/dao/InvoiceLineEventsDaoTest.java @@ -0,0 +1,80 @@ +package org.folio.dao; + +import static org.folio.utils.EntityUtils.TENANT_ID; +import static org.folio.utils.EntityUtils.createInvoiceLineAuditEvent; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.UUID; + +import io.vertx.core.Vertx; +import io.vertx.pgclient.PgException; +import org.folio.CopilotGenerated; +import org.folio.dao.acquisition.impl.InvoiceLineEventsDaoImpl; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; +import org.folio.util.PostgresClientFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; + +@CopilotGenerated +public class InvoiceLineEventsDaoTest { + + @Spy + private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); + @InjectMocks + InvoiceLineEventsDaoImpl invoiceLineEventsDao; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + invoiceLineEventsDao = new InvoiceLineEventsDaoImpl(postgresClientFactory); + } + + @Test + void shouldCreateEventProcessed() { + var invoiceLineAuditEvent = createInvoiceLineAuditEvent(UUID.randomUUID().toString()); + + var saveFuture = invoiceLineEventsDao.save(invoiceLineAuditEvent, TENANT_ID); + saveFuture.onComplete(ar -> assertTrue(ar.succeeded())); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); + } + + @Test + void shouldThrowConstraintViolation() { + var invoiceLineAuditEvent = createInvoiceLineAuditEvent(UUID.randomUUID().toString()); + + var saveFuture = invoiceLineEventsDao.save(invoiceLineAuditEvent, TENANT_ID); + saveFuture.onComplete(ar -> { + var reSaveFuture = invoiceLineEventsDao.save(invoiceLineAuditEvent, TENANT_ID); + reSaveFuture.onComplete(re -> { + assertTrue(re.failed()); + assertTrue(re.cause() instanceof PgException); + assertEquals("ERROR: duplicate key value violates unique constraint \"acquisition_invoice_line_log_pkey\" (23505)", re.cause().getMessage()); + }); + }); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); + } + + @Test + void shouldGetCreatedEvent() { + var id = UUID.randomUUID().toString(); + var invoiceLineAuditEvent = createInvoiceLineAuditEvent(id); + + invoiceLineEventsDao.save(invoiceLineAuditEvent, TENANT_ID); + + var dto = invoiceLineEventsDao.getAuditEventsByInvoiceLineId(id, "action_date", "asc", 1, 1, TENANT_ID); + dto.onComplete(ar -> { + var invoiceLineAuditEventOptional = ar.result(); + var invoiceLineAuditEventList = invoiceLineAuditEventOptional.getInvoiceLineAuditEvents(); + + assertEquals(invoiceLineAuditEventList.get(0).getId(), id); + assertEquals(InvoiceLineAuditEvent.Action.CREATE.value(), invoiceLineAuditEventList.get(0).getAction().value()); + }); + verify(postgresClientFactory, times(2)).createInstance(TENANT_ID); + } +} diff --git a/mod-audit-server/src/test/java/org/folio/dao/OrderEventsDaoTest.java b/mod-audit-server/src/test/java/org/folio/dao/OrderEventsDaoTest.java index d052046e..36293f26 100644 --- a/mod-audit-server/src/test/java/org/folio/dao/OrderEventsDaoTest.java +++ b/mod-audit-server/src/test/java/org/folio/dao/OrderEventsDaoTest.java @@ -4,18 +4,15 @@ import static org.folio.utils.EntityUtils.createOrderAuditEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; -import java.util.List; import java.util.UUID; -import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.pgclient.PgException; -import io.vertx.sqlclient.Row; -import io.vertx.sqlclient.RowSet; import org.folio.dao.acquisition.impl.OrderEventsDaoImpl; import org.folio.rest.jaxrs.model.OrderAuditEvent; -import org.folio.rest.jaxrs.model.OrderAuditEventCollection; import org.folio.util.PostgresClientFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -28,7 +25,7 @@ public class OrderEventsDaoTest { @Spy private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); @InjectMocks - OrderEventsDaoImpl orderEventDao = new OrderEventsDaoImpl(postgresClientFactory); + OrderEventsDaoImpl orderEventDao; @BeforeEach public void setUp() { @@ -40,23 +37,25 @@ public void setUp() { void shouldCreateEventProcessed() { var orderAuditEvent = createOrderAuditEvent(UUID.randomUUID().toString()); - Future> saveFuture = orderEventDao.save(orderAuditEvent, TENANT_ID); + var saveFuture = orderEventDao.save(orderAuditEvent, TENANT_ID); saveFuture.onComplete(ar -> assertTrue(ar.succeeded())); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); } @Test void shouldThrowConstraintViolation() { var orderAuditEvent = createOrderAuditEvent(UUID.randomUUID().toString()); - Future> saveFuture = orderEventDao.save(orderAuditEvent, TENANT_ID); + var saveFuture = orderEventDao.save(orderAuditEvent, TENANT_ID); saveFuture.onComplete(ar -> { - Future> reSaveFuture = orderEventDao.save(orderAuditEvent, TENANT_ID); + var reSaveFuture = orderEventDao.save(orderAuditEvent, TENANT_ID); reSaveFuture.onComplete(re -> { assertTrue(re.failed()); assertTrue(re.cause() instanceof PgException); assertEquals("ERROR: duplicate key value violates unique constraint \"acquisition_order_log_pkey\" (23505)", re.cause().getMessage()); }); }); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); } @Test @@ -66,16 +65,16 @@ void shouldGetCreatedEvent() { orderEventDao.save(orderAuditEvent, TENANT_ID); - Future dto = orderEventDao.getAuditEventsByOrderId(id, "action_date", "desc", 1, 1, TENANT_ID); + var dto = orderEventDao.getAuditEventsByOrderId(id, "action_date", "desc", 1, 1, TENANT_ID); dto.onComplete(ar -> { - OrderAuditEventCollection orderAuditEventOptional = ar.result(); - List orderAuditEventList = orderAuditEventOptional.getOrderAuditEvents(); + var orderAuditEventOptional = ar.result(); + var orderAuditEventList = orderAuditEventOptional.getOrderAuditEvents(); assertEquals(orderAuditEventList.get(0).getId(), id); assertEquals(OrderAuditEvent.Action.CREATE.value(), orderAuditEventList.get(0).getAction().value()); }); + verify(postgresClientFactory, times(2)).createInstance(TENANT_ID); } - } diff --git a/mod-audit-server/src/test/java/org/folio/dao/OrderLineEventsDaoTest.java b/mod-audit-server/src/test/java/org/folio/dao/OrderLineEventsDaoTest.java index 88d9ae87..61c0961a 100644 --- a/mod-audit-server/src/test/java/org/folio/dao/OrderLineEventsDaoTest.java +++ b/mod-audit-server/src/test/java/org/folio/dao/OrderLineEventsDaoTest.java @@ -4,19 +4,15 @@ import static org.folio.utils.EntityUtils.createOrderLineAuditEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; -import java.util.List; import java.util.UUID; -import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.pgclient.PgException; -import io.vertx.sqlclient.Row; -import io.vertx.sqlclient.RowSet; import org.folio.dao.acquisition.impl.OrderLineEventsDaoImpl; import org.folio.rest.jaxrs.model.OrderAuditEvent; -import org.folio.rest.jaxrs.model.OrderLineAuditEvent; -import org.folio.rest.jaxrs.model.OrderLineAuditEventCollection; import org.folio.util.PostgresClientFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -28,9 +24,8 @@ public class OrderLineEventsDaoTest { @Spy private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); - @InjectMocks - OrderLineEventsDaoImpl orderLineEventsDao = new OrderLineEventsDaoImpl(postgresClientFactory); + OrderLineEventsDaoImpl orderLineEventsDao; @BeforeEach public void setUp() { @@ -41,42 +36,45 @@ public void setUp() { @Test void shouldCreateEventProcessed() { var orderLineAuditEvent = createOrderLineAuditEvent(UUID.randomUUID().toString()); - Future> saveFuture = orderLineEventsDao.save(orderLineAuditEvent, TENANT_ID); + + var saveFuture = orderLineEventsDao.save(orderLineAuditEvent, TENANT_ID); saveFuture.onComplete(ar -> assertTrue(ar.succeeded())); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); } @Test void shouldThrowConstraintViolation() { var orderLineAuditEvent = createOrderLineAuditEvent(UUID.randomUUID().toString()); - Future> saveFuture = orderLineEventsDao.save(orderLineAuditEvent, TENANT_ID); + var saveFuture = orderLineEventsDao.save(orderLineAuditEvent, TENANT_ID); saveFuture.onComplete(ar -> { - Future> reSaveFuture = orderLineEventsDao.save(orderLineAuditEvent, TENANT_ID); + var reSaveFuture = orderLineEventsDao.save(orderLineAuditEvent, TENANT_ID); reSaveFuture.onComplete(re -> { assertTrue(re.failed()); assertTrue(re.cause() instanceof PgException); assertEquals("ERROR: duplicate key value violates unique constraint \"acquisition_order_line_log_pkey\" (23505)", re.cause().getMessage()); }); }); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); } @Test void shouldGetCreatedEvent() { - String id = UUID.randomUUID().toString(); + var id = UUID.randomUUID().toString(); var orderLineAuditEvent = createOrderLineAuditEvent(id); orderLineEventsDao.save(orderLineAuditEvent, TENANT_ID); - Future dto = orderLineEventsDao.getAuditEventsByOrderLineId(id, "action_date", "asc", 1, 1, TENANT_ID); + var dto = orderLineEventsDao.getAuditEventsByOrderLineId(id, "action_date", "asc", 1, 1, TENANT_ID); dto.onComplete(ar -> { - OrderLineAuditEventCollection orderLineAuditEventOptional = ar.result(); - List orderLineAuditEventList = orderLineAuditEventOptional.getOrderLineAuditEvents(); + var orderLineAuditEventOptional = ar.result(); + var orderLineAuditEventList = orderLineAuditEventOptional.getOrderLineAuditEvents(); assertEquals(orderLineAuditEventList.get(0).getId(), id); assertEquals(OrderAuditEvent.Action.CREATE.value(), orderLineAuditEventList.get(0).getAction().value()); }); + verify(postgresClientFactory, times(2)).createInstance(TENANT_ID); } - } diff --git a/mod-audit-server/src/test/java/org/folio/dao/OrganizationEventsDaoTest.java b/mod-audit-server/src/test/java/org/folio/dao/OrganizationEventsDaoTest.java new file mode 100644 index 00000000..72f2204b --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/dao/OrganizationEventsDaoTest.java @@ -0,0 +1,80 @@ +package org.folio.dao; + +import io.vertx.core.Vertx; +import io.vertx.pgclient.PgException; +import org.folio.CopilotGenerated; +import org.folio.dao.acquisition.impl.OrganizationEventsDaoImpl; +import org.folio.rest.jaxrs.model.OrganizationAuditEvent; +import org.folio.util.PostgresClientFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; + +import java.util.UUID; + +import static org.folio.utils.EntityUtils.TENANT_ID; +import static org.folio.utils.EntityUtils.createOrganizationAuditEvent; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@CopilotGenerated +public class OrganizationEventsDaoTest { + + @Spy + private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); + @InjectMocks + OrganizationEventsDaoImpl organizationEventDao; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + organizationEventDao = new OrganizationEventsDaoImpl(postgresClientFactory); + } + + @Test + void shouldCreateEventProcessed() { + var organizationAuditEvent = createOrganizationAuditEvent(UUID.randomUUID().toString()); + + var saveFuture = organizationEventDao.save(organizationAuditEvent, TENANT_ID); + saveFuture.onComplete(ar -> assertTrue(ar.succeeded())); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); + } + + @Test + void shouldThrowConstraintViolation() { + var organizationAuditEvent = createOrganizationAuditEvent(UUID.randomUUID().toString()); + + var saveFuture = organizationEventDao.save(organizationAuditEvent, TENANT_ID); + saveFuture.onComplete(ar -> { + var reSaveFuture = organizationEventDao.save(organizationAuditEvent, TENANT_ID); + reSaveFuture.onComplete(re -> { + assertTrue(re.failed()); + assertTrue(re.cause() instanceof PgException); + assertEquals("ERROR: duplicate key value violates unique constraint \"acquisition_organization_log_pkey\" (23505)", re.cause().getMessage()); + }); + }); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); + } + + @Test + void shouldGetCreatedEvent() { + var id = UUID.randomUUID().toString(); + var organizationAuditEvent = createOrganizationAuditEvent(id); + + organizationEventDao.save(organizationAuditEvent, TENANT_ID); + + var dto = organizationEventDao.getAuditEventsByOrganizationId(id, "action_date", "desc", 1, 1, TENANT_ID); + dto.onComplete(ar -> { + var organizationAuditEventOptional = ar.result(); + var organizationAuditEventList = organizationAuditEventOptional.getOrganizationAuditEvents(); + + assertEquals(organizationAuditEventList.get(0).getId(), id); + assertEquals(OrganizationAuditEvent.Action.CREATE.value(), organizationAuditEventList.get(0).getAction().value()); + }); + verify(postgresClientFactory, times(2)).createInstance(TENANT_ID); + } +} diff --git a/mod-audit-server/src/test/java/org/folio/dao/PieceEventsDaoTest.java b/mod-audit-server/src/test/java/org/folio/dao/PieceEventsDaoTest.java index 817d0b78..65bb7030 100644 --- a/mod-audit-server/src/test/java/org/folio/dao/PieceEventsDaoTest.java +++ b/mod-audit-server/src/test/java/org/folio/dao/PieceEventsDaoTest.java @@ -4,18 +4,15 @@ import static org.folio.utils.EntityUtils.createPieceAuditEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; -import java.util.List; import java.util.UUID; -import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.pgclient.PgException; -import io.vertx.sqlclient.Row; -import io.vertx.sqlclient.RowSet; import org.folio.dao.acquisition.impl.PieceEventsDaoImpl; import org.folio.rest.jaxrs.model.PieceAuditEvent; -import org.folio.rest.jaxrs.model.PieceAuditEventCollection; import org.folio.util.PostgresClientFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,38 +37,42 @@ public void setUp() { void shouldCreateEventProcessed() { var pieceAuditEvent = createPieceAuditEvent(UUID.randomUUID().toString()); - Future> saveFuture = pieceEventsDao.save(pieceAuditEvent, TENANT_ID); + var saveFuture = pieceEventsDao.save(pieceAuditEvent, TENANT_ID); saveFuture.onComplete(ar -> assertTrue(ar.succeeded())); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); } @Test void shouldThrowConstrainViolation() { var pieceAuditEvent = createPieceAuditEvent(UUID.randomUUID().toString()); - Future> saveFuture = pieceEventsDao.save(pieceAuditEvent, TENANT_ID); + var saveFuture = pieceEventsDao.save(pieceAuditEvent, TENANT_ID); saveFuture.onComplete(ar -> { - Future> reSaveFuture = pieceEventsDao.save(pieceAuditEvent, TENANT_ID); + var reSaveFuture = pieceEventsDao.save(pieceAuditEvent, TENANT_ID); reSaveFuture.onComplete(re -> { assertTrue(re.failed()); assertTrue(re.cause() instanceof PgException); assertEquals("ERROR: duplicate key value violates unique constraint \"acquisition_piece_log_pkey\" (23505)", re.cause().getMessage()); }); }); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); } @Test void shouldGetCreatedEvent() { - String id = UUID.randomUUID().toString(); + var id = UUID.randomUUID().toString(); var pieceAuditEvent = createPieceAuditEvent(id); pieceEventsDao.save(pieceAuditEvent, TENANT_ID); - Future saveFuture = pieceEventsDao.getAuditEventsByPieceId(id, "action_date", "desc", 1, 1, TENANT_ID); + var saveFuture = pieceEventsDao.getAuditEventsByPieceId(id, "action_date", "desc", 1, 1, TENANT_ID); saveFuture.onComplete(ar -> { - PieceAuditEventCollection pieceAuditEventCollection = ar.result(); - List pieceAuditEventList = pieceAuditEventCollection.getPieceAuditEvents(); + var pieceAuditEventCollection = ar.result(); + var pieceAuditEventList = pieceAuditEventCollection.getPieceAuditEvents(); + assertEquals(pieceAuditEventList.get(0).getId(), id); assertEquals(PieceAuditEvent.Action.CREATE.value(), pieceAuditEventList.get(0).getAction().value()); }); + verify(postgresClientFactory, times(2)).createInstance(TENANT_ID); } } diff --git a/mod-audit-server/src/test/java/org/folio/rest/impl/ApiTestBase.java b/mod-audit-server/src/test/java/org/folio/rest/impl/ApiTestBase.java index 4889ca3f..f0a13313 100644 --- a/mod-audit-server/src/test/java/org/folio/rest/impl/ApiTestBase.java +++ b/mod-audit-server/src/test/java/org/folio/rest/impl/ApiTestBase.java @@ -5,7 +5,6 @@ import static org.folio.utils.TenantApiTestUtil.deleteTenantAndPurgeTables; import static org.folio.utils.TenantApiTestUtil.prepareTenant; -import java.io.IOException; import java.util.Locale; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; @@ -30,7 +29,7 @@ public class ApiTestBase { private static TenantJob tenantJob; @BeforeAll - public static void globalSetup() throws InterruptedException, ExecutionException, TimeoutException, IOException { + public static void globalSetup() throws InterruptedException, ExecutionException, TimeoutException { Locale.setDefault(Locale.US); if (!isInitialized) { diff --git a/mod-audit-server/src/test/java/org/folio/rest/impl/AuditDataAcquisitionAPITest.java b/mod-audit-server/src/test/java/org/folio/rest/impl/AuditDataAcquisitionAPITest.java index 08788e50..940bb813 100644 --- a/mod-audit-server/src/test/java/org/folio/rest/impl/AuditDataAcquisitionAPITest.java +++ b/mod-audit-server/src/test/java/org/folio/rest/impl/AuditDataAcquisitionAPITest.java @@ -3,7 +3,9 @@ import static io.restassured.RestAssured.given; import static org.folio.utils.EntityUtils.ORDER_ID; import static org.folio.utils.EntityUtils.ORDER_LINE_ID; +import static org.folio.utils.EntityUtils.ORGANIZATION_ID; import static org.folio.utils.EntityUtils.PIECE_ID; +import static org.folio.utils.EntityUtils.INVOICE_ID; import static org.folio.utils.EntityUtils.createPieceAuditEvent; import static org.hamcrest.Matchers.containsString; @@ -15,11 +17,18 @@ import io.restassured.http.Header; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; +import org.folio.CopilotGenerated; +import org.folio.dao.acquisition.impl.InvoiceEventsDaoImpl; +import org.folio.dao.acquisition.impl.InvoiceLineEventsDaoImpl; import org.folio.dao.acquisition.impl.OrderEventsDaoImpl; import org.folio.dao.acquisition.impl.OrderLineEventsDaoImpl; +import org.folio.dao.acquisition.impl.OrganizationEventsDaoImpl; import org.folio.dao.acquisition.impl.PieceEventsDaoImpl; +import org.folio.rest.jaxrs.model.InvoiceAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; import org.folio.rest.jaxrs.model.OrderAuditEvent; import org.folio.rest.jaxrs.model.OrderLineAuditEvent; +import org.folio.rest.jaxrs.model.OrganizationAuditEvent; import org.folio.rest.jaxrs.model.PieceAuditEvent; import org.folio.util.PostgresClientFactory; import org.junit.jupiter.api.BeforeEach; @@ -38,6 +47,9 @@ public class AuditDataAcquisitionAPITest extends ApiTestBase { private static final String ACQ_AUDIT_ORDER_LINE_PATH = "/audit-data/acquisition/order-line/"; private static final String ACQ_AUDIT_PIECE_PATH = "/audit-data/acquisition/piece/"; private static final String ACQ_AUDIT_PIECE_STATUS_CHANGE_HISTORY_PATH = "/status-change-history"; + private static final String ACQ_AUDIT_INVOICE_PATH = "/audit-data/acquisition/invoice/"; + private static final String ACQ_AUDIT_INVOICE_LINE_PATH = "/audit-data/acquisition/invoice-line/"; + private static final String ACQ_AUDIT_ORGANIZATION_PATH = "/audit-data/acquisition/organization/"; private static final String TENANT_ID = "modaudittest"; @Spy @@ -49,12 +61,21 @@ public class AuditDataAcquisitionAPITest extends ApiTestBase { OrderLineEventsDaoImpl orderLineEventDao; @InjectMocks PieceEventsDaoImpl pieceEventsDao; + @InjectMocks + InvoiceEventsDaoImpl invoiceEventsDao; + @InjectMocks + InvoiceLineEventsDaoImpl invoiceLineEventsDao; + @InjectMocks + OrganizationEventsDaoImpl organizationEventsDao; @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); orderEventDao = new OrderEventsDaoImpl(postgresClientFactory); orderLineEventDao = new OrderLineEventsDaoImpl(postgresClientFactory); + invoiceEventsDao = new InvoiceEventsDaoImpl(postgresClientFactory); + invoiceLineEventsDao = new InvoiceLineEventsDaoImpl(postgresClientFactory); + organizationEventsDao = new OrganizationEventsDaoImpl(postgresClientFactory); } @Test @@ -248,4 +269,129 @@ void shouldReturnPieceEventsStatusChangesHistoryGetByPieceId() { .then().log().all().statusCode(500) .body(containsString("UUID string too large")); } + + @Test + @CopilotGenerated + void shouldReturnInvoiceEventsOnGetByInvoiceId() { + JsonObject jsonObject = new JsonObject(); + jsonObject.put("name", "Test Product2"); + + InvoiceAuditEvent invoiceAuditEvent = new InvoiceAuditEvent() + .withId(UUID.randomUUID().toString()) + .withAction(InvoiceAuditEvent.Action.CREATE) + .withInvoiceId(INVOICE_ID) + .withUserId(UUID.randomUUID().toString()) + .withEventDate(new Date()) + .withActionDate(new Date()) + .withInvoiceSnapshot(jsonObject); + + invoiceEventsDao.save(invoiceAuditEvent, TENANT_ID); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS) + .get(ACQ_AUDIT_INVOICE_PATH + INVALID_ID) + .then().log().all().statusCode(200) + .body(containsString("invoiceAuditEvents")).body(containsString("totalItems")); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS) + .get(ACQ_AUDIT_INVOICE_PATH + INVOICE_ID) + .then().log().all().statusCode(200) + .body(containsString(INVOICE_ID)); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS) + .get(ACQ_AUDIT_INVOICE_PATH + INVOICE_ID + "?limit=1") + .then().log().all().statusCode(200) + .body(containsString(INVOICE_ID)); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS) + .get(ACQ_AUDIT_INVOICE_PATH + INVOICE_ID + "?sortBy=action_date") + .then().log().all().statusCode(200) + .body(containsString(INVOICE_ID)); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS) + .get(ACQ_AUDIT_INVOICE_PATH + INVOICE_ID + 123) + .then().log().all().statusCode(500) + .body(containsString("UUID string too large")); + } + + @Test + @CopilotGenerated + void shouldReturnInvoiceLineEventsOnGetByInvoiceLineId() { + JsonObject jsonObject = new JsonObject(); + jsonObject.put("name", "Test Product2"); + + InvoiceLineAuditEvent invoiceLineAuditEvent = new InvoiceLineAuditEvent() + .withId(UUID.randomUUID().toString()) + .withAction(InvoiceLineAuditEvent.Action.CREATE) + .withInvoiceId(UUID.randomUUID().toString()) + .withInvoiceLineId(UUID.randomUUID().toString()) + .withUserId(UUID.randomUUID().toString()) + .withEventDate(new Date()) + .withActionDate(new Date()) + .withInvoiceLineSnapshot(jsonObject); + + invoiceLineEventsDao.save(invoiceLineAuditEvent, TENANT_ID).onComplete(v -> { + given().header(CONTENT_TYPE).header(TENANT).header(PERMS).get(ACQ_AUDIT_INVOICE_LINE_PATH + INVALID_ID) + .then().log().all().statusCode(200) + .body(containsString("invoiceLineAuditEvents")).body(containsString("totalItems")); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS).get(ACQ_AUDIT_INVOICE_LINE_PATH + invoiceLineAuditEvent.getInvoiceLineId()) + .then().log().all().statusCode(200) + .body(containsString(invoiceLineAuditEvent.getInvoiceLineId())); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS).get(ACQ_AUDIT_INVOICE_LINE_PATH + invoiceLineAuditEvent.getInvoiceLineId() + "?limit=1") + .then().log().all().statusCode(200) + .body(containsString(invoiceLineAuditEvent.getInvoiceLineId())); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS).get(ACQ_AUDIT_INVOICE_LINE_PATH + invoiceLineAuditEvent.getInvoiceLineId() + "?sortBy=action_date") + .then().log().all().statusCode(200) + .body(containsString(invoiceLineAuditEvent.getInvoiceLineId())); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS).get(ACQ_AUDIT_INVOICE_LINE_PATH + invoiceLineAuditEvent.getInvoiceLineId() + 123) + .then().log().all().statusCode(500) + .body(containsString("UUID string too large")); + }); + } + + @Test + @CopilotGenerated + void shouldReturnOrganizationEventsOnGetByOrganizationId() { + JsonObject jsonObject = new JsonObject(); + jsonObject.put("name", "Test Product2"); + + OrganizationAuditEvent organizationAuditEvent = new OrganizationAuditEvent() + .withId(UUID.randomUUID().toString()) + .withAction(OrganizationAuditEvent.Action.CREATE) + .withOrganizationId(ORGANIZATION_ID) + .withUserId(UUID.randomUUID().toString()) + .withEventDate(new Date()) + .withActionDate(new Date()) + .withOrganizationSnapshot(jsonObject); + + organizationEventsDao.save(organizationAuditEvent, TENANT_ID); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS) + .get(ACQ_AUDIT_ORGANIZATION_PATH + INVALID_ID) + .then().log().all().statusCode(200) + .body(containsString("organizationAuditEvents")).body(containsString("totalItems")); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS) + .get(ACQ_AUDIT_ORGANIZATION_PATH + ORGANIZATION_ID) + .then().log().all().statusCode(200) + .body(containsString(ORGANIZATION_ID)); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS) + .get(ACQ_AUDIT_ORGANIZATION_PATH + ORGANIZATION_ID + "?limit=1") + .then().log().all().statusCode(200) + .body(containsString(ORGANIZATION_ID)); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS) + .get(ACQ_AUDIT_ORGANIZATION_PATH + ORGANIZATION_ID + "?sortBy=action_date") + .then().log().all().statusCode(200) + .body(containsString(ORGANIZATION_ID)); + + given().header(CONTENT_TYPE).header(TENANT).header(PERMS) + .get(ACQ_AUDIT_ORGANIZATION_PATH + ORGANIZATION_ID + 123) + .then().log().all().statusCode(500) + .body(containsString("UUID string too large")); + } } diff --git a/mod-audit-server/src/test/java/org/folio/rest/impl/InvoiceEventsHandlerMockTest.java b/mod-audit-server/src/test/java/org/folio/rest/impl/InvoiceEventsHandlerMockTest.java new file mode 100644 index 00000000..966f85f6 --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/rest/impl/InvoiceEventsHandlerMockTest.java @@ -0,0 +1,94 @@ +package org.folio.rest.impl; + +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.core.json.Json; +import io.vertx.kafka.client.consumer.KafkaConsumerRecord; +import io.vertx.kafka.client.consumer.impl.KafkaConsumerRecordImpl; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.common.header.internals.RecordHeader; +import org.folio.CopilotGenerated; +import org.folio.dao.acquisition.impl.InvoiceEventsDaoImpl; +import org.folio.kafka.KafkaTopicNameHelper; +import org.folio.rest.jaxrs.model.InvoiceAuditEvent; +import org.folio.rest.util.OkapiConnectionParams; +import org.folio.services.acquisition.InvoiceAuditEventsService; +import org.folio.services.acquisition.impl.InvoiceAuditEventsServiceImpl; +import org.folio.util.PostgresClientFactory; +import org.folio.verticle.acquisition.consumers.InvoiceEventsHandler; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.*; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +import static org.folio.kafka.KafkaTopicNameHelper.getDefaultNameSpace; +import static org.folio.utils.EntityUtils.createInvoiceAuditEvent; +import static org.folio.utils.EntityUtils.createInvoiceAuditEventWithoutSnapshot; + +@CopilotGenerated(partiallyGenerated = true) +public class InvoiceEventsHandlerMockTest { + + private static final String TENANT_ID = "diku"; + protected static final String TOKEN = "token"; + private static final String KAFKA_ENV = "folio"; + + public static final String OKAPI_TOKEN_HEADER = "x-okapi-token"; + public static final String OKAPI_URL_HEADER = "x-okapi-url"; + + @Spy + private Vertx vertx = Vertx.vertx(); + + @Spy + private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); + + @Mock + InvoiceEventsDaoImpl invoiceEventDao; + @Mock + InvoiceAuditEventsService invoiceAuditEventServiceImpl; + + private InvoiceEventsHandler invoiceEventsHandler; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + invoiceEventDao = new InvoiceEventsDaoImpl(postgresClientFactory); + invoiceAuditEventServiceImpl = new InvoiceAuditEventsServiceImpl(invoiceEventDao); + invoiceEventsHandler = new InvoiceEventsHandler(vertx, invoiceAuditEventServiceImpl); + } + + @Test + void shouldProcessEvent() { + var invoiceAuditEvent = createInvoiceAuditEvent(UUID.randomUUID().toString()); + KafkaConsumerRecord kafkaConsumerRecord = buildKafkaConsumerRecord(invoiceAuditEvent); + + Future saveFuture = invoiceEventsHandler.handle(kafkaConsumerRecord); + saveFuture.onComplete(ar -> Assertions.assertTrue(ar.succeeded())); + } + + @Test + void shouldNotProcessEvent() { + var invoiceAuditEvent = createInvoiceAuditEventWithoutSnapshot(); + KafkaConsumerRecord kafkaConsumerRecord = buildKafkaConsumerRecord(invoiceAuditEvent); + + Future save = invoiceEventsHandler.handle(kafkaConsumerRecord); + Assertions.assertTrue(save.failed()); + } + + private KafkaConsumerRecord buildKafkaConsumerRecord(InvoiceAuditEvent kafkaConsumerRecord) { + String topic = KafkaTopicNameHelper.formatTopicName(KAFKA_ENV, getDefaultNameSpace(), TENANT_ID, kafkaConsumerRecord.getAction().toString()); + ConsumerRecord consumerRecord = buildConsumerRecord(topic, kafkaConsumerRecord); + return new KafkaConsumerRecordImpl<>(consumerRecord); + } + + protected ConsumerRecord buildConsumerRecord(String topic, InvoiceAuditEvent event) { + ConsumerRecord consumerRecord = new ConsumerRecord<>("folio", 0, 0, topic, Json.encode(event)); + consumerRecord.headers().add(new RecordHeader(OkapiConnectionParams.OKAPI_TENANT_HEADER, TENANT_ID.getBytes(StandardCharsets.UTF_8))); + consumerRecord.headers().add(new RecordHeader(OKAPI_URL_HEADER, ("http://localhost:" + 8080).getBytes(StandardCharsets.UTF_8))); + consumerRecord.headers().add(new RecordHeader(OKAPI_TOKEN_HEADER, (TOKEN).getBytes(StandardCharsets.UTF_8))); + return consumerRecord; + } +} diff --git a/mod-audit-server/src/test/java/org/folio/rest/impl/InvoiceLineEventsHandlerMockTest.java b/mod-audit-server/src/test/java/org/folio/rest/impl/InvoiceLineEventsHandlerMockTest.java new file mode 100644 index 00000000..1da80381 --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/rest/impl/InvoiceLineEventsHandlerMockTest.java @@ -0,0 +1,88 @@ +package org.folio.rest.impl; + +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.core.json.Json; +import io.vertx.core.json.JsonObject; +import io.vertx.kafka.client.consumer.KafkaConsumerRecord; +import io.vertx.kafka.client.consumer.impl.KafkaConsumerRecordImpl; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.common.header.internals.RecordHeader; +import org.folio.CopilotGenerated; +import org.folio.dao.acquisition.impl.InvoiceLineEventsDaoImpl; +import org.folio.kafka.KafkaTopicNameHelper; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; +import org.folio.rest.util.OkapiConnectionParams; +import org.folio.services.acquisition.impl.InvoiceLineAuditEventsServiceImpl; +import org.folio.util.PostgresClientFactory; +import org.folio.verticle.acquisition.consumers.InvoiceLineEventsHandler; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Spy; + +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.UUID; + +import static org.folio.kafka.KafkaTopicNameHelper.getDefaultNameSpace; + +@CopilotGenerated(partiallyGenerated = true) +public class InvoiceLineEventsHandlerMockTest { + + private static final String TENANT_ID = "diku"; + protected static final String TOKEN = "token"; + private static final String KAFKA_ENV = "folio"; + + public static final String OKAPI_TOKEN_HEADER = "x-okapi-token"; + public static final String OKAPI_URL_HEADER = "x-okapi-url"; + + @Spy + private Vertx vertx = Vertx.vertx(); + + @Spy + private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); + + @InjectMocks + InvoiceLineEventsDaoImpl invoiceLineEventsDao = new InvoiceLineEventsDaoImpl(postgresClientFactory); + + @InjectMocks + InvoiceLineAuditEventsServiceImpl invoiceLineAuditEventServiceImpl = new InvoiceLineAuditEventsServiceImpl(invoiceLineEventsDao); + + @InjectMocks + private InvoiceLineEventsHandler invoiceLineEventsHandler = new InvoiceLineEventsHandler(vertx, invoiceLineAuditEventServiceImpl); + + @Test + void shouldProcessEvent() { + JsonObject jsonObject = new JsonObject(); + jsonObject.put("Test", "TestValue"); + + InvoiceLineAuditEvent invoiceLineAuditEvent = new InvoiceLineAuditEvent() + .withId(UUID.randomUUID().toString()) + .withInvoiceLineId(UUID.randomUUID().toString()) + .withEventDate(new Date()) + .withInvoiceId(UUID.randomUUID().toString()) + .withActionDate(new Date()) + .withAction(InvoiceLineAuditEvent.Action.CREATE) + .withInvoiceLineSnapshot(jsonObject) + .withUserId(UUID.randomUUID().toString()); + KafkaConsumerRecord kafkaConsumerRecord = buildKafkaConsumerRecord(invoiceLineAuditEvent); + + Future saveFuture = invoiceLineEventsHandler.handle(kafkaConsumerRecord); + saveFuture.onComplete(ar -> Assertions.assertTrue(ar.succeeded())); + } + + private KafkaConsumerRecord buildKafkaConsumerRecord(InvoiceLineAuditEvent kafkaConsumerRecord) { + String topic = KafkaTopicNameHelper.formatTopicName(KAFKA_ENV, getDefaultNameSpace(), TENANT_ID, kafkaConsumerRecord.getAction().toString()); + ConsumerRecord consumerRecord = buildConsumerRecord(topic, kafkaConsumerRecord); + return new KafkaConsumerRecordImpl<>(consumerRecord); + } + + protected ConsumerRecord buildConsumerRecord(String topic, InvoiceLineAuditEvent event) { + ConsumerRecord consumerRecord = new ConsumerRecord<>(topic, 0, 0, topic, Json.encode(event)); + consumerRecord.headers().add(new RecordHeader(OkapiConnectionParams.OKAPI_TENANT_HEADER, TENANT_ID.getBytes(StandardCharsets.UTF_8))); + consumerRecord.headers().add(new RecordHeader(OKAPI_URL_HEADER, ("http://localhost:" + 8080).getBytes(StandardCharsets.UTF_8))); + consumerRecord.headers().add(new RecordHeader(OKAPI_TOKEN_HEADER, TOKEN.getBytes(StandardCharsets.UTF_8))); + return consumerRecord; + } +} diff --git a/mod-audit-server/src/test/java/org/folio/rest/impl/OrderEventsHandlerMockTest.java b/mod-audit-server/src/test/java/org/folio/rest/impl/OrderEventsHandlerMockTest.java index 31e321d9..4bf4733a 100644 --- a/mod-audit-server/src/test/java/org/folio/rest/impl/OrderEventsHandlerMockTest.java +++ b/mod-audit-server/src/test/java/org/folio/rest/impl/OrderEventsHandlerMockTest.java @@ -81,9 +81,9 @@ void shouldNotProcessEvent() { assertTrue(save.failed()); } - private KafkaConsumerRecord buildKafkaConsumerRecord(OrderAuditEvent record) { - String topic = KafkaTopicNameHelper.formatTopicName(KAFKA_ENV, getDefaultNameSpace(), TENANT_ID, record.getAction().toString()); - ConsumerRecord consumerRecord = buildConsumerRecord(topic, record); + private KafkaConsumerRecord buildKafkaConsumerRecord(OrderAuditEvent kafkaConsumerRecord) { + String topic = KafkaTopicNameHelper.formatTopicName(KAFKA_ENV, getDefaultNameSpace(), TENANT_ID, kafkaConsumerRecord.getAction().toString()); + ConsumerRecord consumerRecord = buildConsumerRecord(topic, kafkaConsumerRecord); return new KafkaConsumerRecordImpl<>(consumerRecord); } diff --git a/mod-audit-server/src/test/java/org/folio/rest/impl/OrderLineEventsHandlerMockTest.java b/mod-audit-server/src/test/java/org/folio/rest/impl/OrderLineEventsHandlerMockTest.java index 6abf7639..eccd6d62 100644 --- a/mod-audit-server/src/test/java/org/folio/rest/impl/OrderLineEventsHandlerMockTest.java +++ b/mod-audit-server/src/test/java/org/folio/rest/impl/OrderLineEventsHandlerMockTest.java @@ -73,9 +73,9 @@ void shouldProcessEvent() { }); } - private KafkaConsumerRecord buildKafkaConsumerRecord(OrderLineAuditEvent record) { - String topic = KafkaTopicNameHelper.formatTopicName(KAFKA_ENV, getDefaultNameSpace(), TENANT_ID, record.getAction().toString()); - ConsumerRecord consumerRecord = buildConsumerRecord(topic, record); + private KafkaConsumerRecord buildKafkaConsumerRecord(OrderLineAuditEvent kafkaConsumerRecord) { + String topic = KafkaTopicNameHelper.formatTopicName(KAFKA_ENV, getDefaultNameSpace(), TENANT_ID, kafkaConsumerRecord.getAction().toString()); + ConsumerRecord consumerRecord = buildConsumerRecord(topic, kafkaConsumerRecord); return new KafkaConsumerRecordImpl<>(consumerRecord); } diff --git a/mod-audit-server/src/test/java/org/folio/rest/impl/OrganizationEventsHandlerMockTest.java b/mod-audit-server/src/test/java/org/folio/rest/impl/OrganizationEventsHandlerMockTest.java new file mode 100644 index 00000000..3d4b0e02 --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/rest/impl/OrganizationEventsHandlerMockTest.java @@ -0,0 +1,95 @@ +package org.folio.rest.impl; + +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.core.json.Json; +import io.vertx.kafka.client.consumer.KafkaConsumerRecord; +import io.vertx.kafka.client.consumer.impl.KafkaConsumerRecordImpl; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.common.header.internals.RecordHeader; +import org.folio.CopilotGenerated; +import org.folio.dao.acquisition.impl.OrganizationEventsDaoImpl; +import org.folio.kafka.KafkaTopicNameHelper; +import org.folio.rest.jaxrs.model.OrganizationAuditEvent; +import org.folio.rest.util.OkapiConnectionParams; +import org.folio.services.acquisition.OrganizationAuditEventsService; +import org.folio.services.acquisition.impl.OrganizationAuditEventsServiceImpl; +import org.folio.util.PostgresClientFactory; +import org.folio.verticle.acquisition.consumers.OrganizationEventsHandler; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +import static org.folio.kafka.KafkaTopicNameHelper.getDefaultNameSpace; +import static org.folio.utils.EntityUtils.createOrganizationAuditEvent; +import static org.folio.utils.EntityUtils.createOrganizationAuditEventWithoutSnapshot; + +@CopilotGenerated(partiallyGenerated = true) +public class OrganizationEventsHandlerMockTest { + + private static final String TENANT_ID = "diku"; + protected static final String TOKEN = "token"; + private static final String KAFKA_ENV = "folio"; + + public static final String OKAPI_TOKEN_HEADER = "x-okapi-token"; + public static final String OKAPI_URL_HEADER = "x-okapi-url"; + + @Spy + private Vertx vertx = Vertx.vertx(); + + @Spy + private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); + + @Mock + OrganizationEventsDaoImpl organizationEventDao; + @Mock + OrganizationAuditEventsService organizationAuditEventServiceImpl; + + private OrganizationEventsHandler organizationEventsHandler; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + organizationEventDao = new OrganizationEventsDaoImpl(postgresClientFactory); + organizationAuditEventServiceImpl = new OrganizationAuditEventsServiceImpl(organizationEventDao); + organizationEventsHandler = new OrganizationEventsHandler(vertx, organizationAuditEventServiceImpl); + } + + @Test + void shouldProcessEvent() { + var organizationAuditEvent = createOrganizationAuditEvent(UUID.randomUUID().toString()); + KafkaConsumerRecord kafkaConsumerRecord = buildKafkaConsumerRecord(organizationAuditEvent); + + Future saveFuture = organizationEventsHandler.handle(kafkaConsumerRecord); + saveFuture.onComplete(ar -> Assertions.assertTrue(ar.succeeded())); + } + + @Test + void shouldNotProcessEvent() { + var organizationAuditEvent = createOrganizationAuditEventWithoutSnapshot(); + KafkaConsumerRecord kafkaConsumerRecord = buildKafkaConsumerRecord(organizationAuditEvent); + + Future save = organizationEventsHandler.handle(kafkaConsumerRecord); + Assertions.assertTrue(save.failed()); + } + + private KafkaConsumerRecord buildKafkaConsumerRecord(OrganizationAuditEvent kafkaConsumerRecord) { + String topic = KafkaTopicNameHelper.formatTopicName(KAFKA_ENV, getDefaultNameSpace(), TENANT_ID, kafkaConsumerRecord.getAction().toString()); + ConsumerRecord consumerRecord = buildConsumerRecord(topic, kafkaConsumerRecord); + return new KafkaConsumerRecordImpl<>(consumerRecord); + } + + protected ConsumerRecord buildConsumerRecord(String topic, OrganizationAuditEvent event) { + ConsumerRecord consumerRecord = new ConsumerRecord<>("folio", 0, 0, topic, Json.encode(event)); + consumerRecord.headers().add(new RecordHeader(OkapiConnectionParams.OKAPI_TENANT_HEADER, TENANT_ID.getBytes(StandardCharsets.UTF_8))); + consumerRecord.headers().add(new RecordHeader(OKAPI_URL_HEADER, ("http://localhost:" + 8080).getBytes(StandardCharsets.UTF_8))); + consumerRecord.headers().add(new RecordHeader(OKAPI_TOKEN_HEADER, (TOKEN).getBytes(StandardCharsets.UTF_8))); + return consumerRecord; + } +} diff --git a/mod-audit-server/src/test/java/org/folio/services/InvoiceAuditEventsServiceTest.java b/mod-audit-server/src/test/java/org/folio/services/InvoiceAuditEventsServiceTest.java new file mode 100644 index 00000000..f7e06bb9 --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/services/InvoiceAuditEventsServiceTest.java @@ -0,0 +1,92 @@ +package org.folio.services; + +import static org.folio.utils.EntityUtils.ACTION_DATE_SORT_BY; +import static org.folio.utils.EntityUtils.DESC_ORDER; +import static org.folio.utils.EntityUtils.LIMIT; +import static org.folio.utils.EntityUtils.OFFSET; +import static org.folio.utils.EntityUtils.TENANT_ID; +import static org.folio.utils.EntityUtils.createInvoiceAuditEvent; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.List; +import java.util.UUID; + +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.Tuple; +import org.folio.CopilotGenerated; +import org.folio.dao.acquisition.InvoiceEventsDao; +import org.folio.dao.acquisition.impl.InvoiceEventsDaoImpl; +import org.folio.rest.jaxrs.model.InvoiceAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceAuditEventCollection; +import org.folio.rest.persist.PostgresClient; +import org.folio.services.acquisition.impl.InvoiceAuditEventsServiceImpl; +import org.folio.util.PostgresClientFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +@CopilotGenerated +public class InvoiceAuditEventsServiceTest { + + @Mock + private RowSet rowSet; + @Mock + private PostgresClient postgresClient; + + private InvoiceEventsDao invoiceEventsDao; + private InvoiceAuditEventsServiceImpl invoiceAuditEventService; + + @BeforeEach + public void setUp() throws Exception { + try (var ignored = MockitoAnnotations.openMocks(this)) { + var postgresClientFactory = spy(new PostgresClientFactory(Vertx.vertx())); + invoiceEventsDao = spy(new InvoiceEventsDaoImpl(postgresClientFactory)); + invoiceAuditEventService = new InvoiceAuditEventsServiceImpl(invoiceEventsDao); + + doReturn(postgresClient).when(postgresClientFactory).createInstance(TENANT_ID); + } + } + + @Test + void shouldCallDaoForSuccessfulCase() { + var invoiceAuditEvent = createInvoiceAuditEvent(UUID.randomUUID().toString()); + doReturn(Future.succeededFuture(rowSet)).when(postgresClient).execute(anyString(), any(Tuple.class)); + + var saveFuture = invoiceAuditEventService.saveInvoiceAuditEvent(invoiceAuditEvent, TENANT_ID); + saveFuture.onComplete(asyncResult -> assertTrue(asyncResult.succeeded())); + + verify(invoiceEventsDao, times(1)).save(invoiceAuditEvent, TENANT_ID); + } + + @Test + void shouldGetDto() { + var id = UUID.randomUUID().toString(); + var invoiceAuditEvent = createInvoiceAuditEvent(id); + var invoiceAuditEventCollection = new InvoiceAuditEventCollection().withInvoiceAuditEvents(List.of(invoiceAuditEvent)).withTotalItems(1); + + doReturn(Future.succeededFuture(invoiceAuditEventCollection)).when(invoiceEventsDao).getAuditEventsByInvoiceId(anyString(), anyString(), anyString(), anyInt(), anyInt(), anyString()); + + var dto = invoiceAuditEventService.getAuditEventsByInvoiceId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + dto.onComplete(asyncResult -> { + var invoiceAuditEventOptional = asyncResult.result(); + var invoiceAuditEventList = invoiceAuditEventOptional.getInvoiceAuditEvents(); + + assertEquals(invoiceAuditEventList.get(0).getId(), id); + assertEquals(InvoiceAuditEvent.Action.CREATE, invoiceAuditEventList.get(0).getAction()); + }); + + verify(invoiceEventsDao, times(1)).getAuditEventsByInvoiceId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + } +} diff --git a/mod-audit-server/src/test/java/org/folio/services/InvoiceLineAuditEventsServiceTest.java b/mod-audit-server/src/test/java/org/folio/services/InvoiceLineAuditEventsServiceTest.java new file mode 100644 index 00000000..f9920063 --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/services/InvoiceLineAuditEventsServiceTest.java @@ -0,0 +1,92 @@ +package org.folio.services; + +import static org.folio.utils.EntityUtils.ACTION_DATE_SORT_BY; +import static org.folio.utils.EntityUtils.DESC_ORDER; +import static org.folio.utils.EntityUtils.LIMIT; +import static org.folio.utils.EntityUtils.OFFSET; +import static org.folio.utils.EntityUtils.TENANT_ID; +import static org.folio.utils.EntityUtils.createInvoiceLineAuditEvent; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.List; +import java.util.UUID; + +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.Tuple; +import org.folio.CopilotGenerated; +import org.folio.dao.acquisition.InvoiceLineEventsDao; +import org.folio.dao.acquisition.impl.InvoiceLineEventsDaoImpl; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEventCollection; +import org.folio.rest.persist.PostgresClient; +import org.folio.services.acquisition.impl.InvoiceLineAuditEventsServiceImpl; +import org.folio.util.PostgresClientFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +@CopilotGenerated +public class InvoiceLineAuditEventsServiceTest { + + @Mock + private RowSet rowSet; + @Mock + private PostgresClient postgresClient; + + private InvoiceLineEventsDao invoiceLineEventsDao; + private InvoiceLineAuditEventsServiceImpl invoiceLineAuditEventService; + + @BeforeEach + public void setUp() throws Exception { + try (var ignored = MockitoAnnotations.openMocks(this)) { + var postgresClientFactory = spy(new PostgresClientFactory(Vertx.vertx())); + invoiceLineEventsDao = spy(new InvoiceLineEventsDaoImpl(postgresClientFactory)); + invoiceLineAuditEventService = new InvoiceLineAuditEventsServiceImpl(invoiceLineEventsDao); + + doReturn(postgresClient).when(postgresClientFactory).createInstance(TENANT_ID); + } + } + + @Test + public void shouldCallDaoForSuccessfulCase() { + var invoiceLineAuditEvent = createInvoiceLineAuditEvent(UUID.randomUUID().toString()); + doReturn(Future.succeededFuture(rowSet)).when(postgresClient).execute(anyString(), any(Tuple.class)); + + var saveFuture = invoiceLineAuditEventService.saveInvoiceLineAuditEvent(invoiceLineAuditEvent, TENANT_ID); + saveFuture.onComplete(asyncResult -> assertTrue(asyncResult.succeeded())); + + verify(invoiceLineEventsDao, times(1)).save(invoiceLineAuditEvent, TENANT_ID); + } + + @Test + void shouldGetInvoiceLineDto() { + var id = UUID.randomUUID().toString(); + var invoiceLineAuditEvent = createInvoiceLineAuditEvent(id); + var invoiceLineAuditEventCollection = new InvoiceLineAuditEventCollection().withInvoiceLineAuditEvents(List.of(invoiceLineAuditEvent)).withTotalItems(1); + + doReturn(Future.succeededFuture(invoiceLineAuditEventCollection)).when(invoiceLineEventsDao).getAuditEventsByInvoiceLineId(anyString(), anyString(), anyString(), anyInt(), anyInt(), anyString()); + + var dto = invoiceLineAuditEventService.getAuditEventsByInvoiceLineId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + dto.onComplete(asyncResult -> { + var invoiceLineAuditEventOptional = asyncResult.result(); + var invoiceLineAuditEventList = invoiceLineAuditEventOptional.getInvoiceLineAuditEvents(); + + assertEquals(invoiceLineAuditEventList.get(0).getId(), id); + assertEquals(InvoiceLineAuditEvent.Action.CREATE, invoiceLineAuditEventList.get(0).getAction()); + }); + + verify(invoiceLineEventsDao, times(1)).getAuditEventsByInvoiceLineId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + } +} diff --git a/mod-audit-server/src/test/java/org/folio/services/OrderAuditEventsServiceTest.java b/mod-audit-server/src/test/java/org/folio/services/OrderAuditEventsServiceTest.java index 2bd3904c..0001f9a8 100644 --- a/mod-audit-server/src/test/java/org/folio/services/OrderAuditEventsServiceTest.java +++ b/mod-audit-server/src/test/java/org/folio/services/OrderAuditEventsServiceTest.java @@ -1,9 +1,20 @@ package org.folio.services; +import static org.folio.utils.EntityUtils.ACTION_DATE_SORT_BY; +import static org.folio.utils.EntityUtils.DESC_ORDER; +import static org.folio.utils.EntityUtils.LIMIT; +import static org.folio.utils.EntityUtils.OFFSET; import static org.folio.utils.EntityUtils.TENANT_ID; import static org.folio.utils.EntityUtils.createOrderAuditEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.util.List; import java.util.UUID; @@ -12,52 +23,68 @@ import io.vertx.core.Vertx; import io.vertx.sqlclient.Row; import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.Tuple; import org.folio.dao.acquisition.OrderEventsDao; import org.folio.dao.acquisition.impl.OrderEventsDaoImpl; import org.folio.rest.jaxrs.model.OrderAuditEvent; import org.folio.rest.jaxrs.model.OrderAuditEventCollection; +import org.folio.rest.persist.PostgresClient; import org.folio.services.acquisition.impl.OrderAuditEventsServiceImpl; import org.folio.util.PostgresClientFactory; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Spy; +import org.mockito.MockitoAnnotations; public class OrderAuditEventsServiceTest { - @Spy - private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); @Mock - OrderEventsDao orderEventsDao = new OrderEventsDaoImpl(postgresClientFactory); + private RowSet rowSet; + @Mock + private PostgresClient postgresClient; + + private OrderEventsDao orderEventsDao; + private OrderAuditEventsServiceImpl orderAuditEventService; - @InjectMocks - OrderAuditEventsServiceImpl orderAuditEventService = new OrderAuditEventsServiceImpl(orderEventsDao); + @BeforeEach + public void setUp() throws Exception { + try (var ignored = MockitoAnnotations.openMocks(this)) { + var postgresClientFactory = spy(new PostgresClientFactory(Vertx.vertx())); + orderEventsDao = spy(new OrderEventsDaoImpl(postgresClientFactory)); + orderAuditEventService = new OrderAuditEventsServiceImpl(orderEventsDao); + + doReturn(postgresClient).when(postgresClientFactory).createInstance(TENANT_ID); + } + } @Test void shouldCallDaoForSuccessfulCase() { var orderAuditEvent = createOrderAuditEvent(UUID.randomUUID().toString()); + doReturn(Future.succeededFuture(rowSet)).when(postgresClient).execute(anyString(), any(Tuple.class)); - Future> saveFuture = orderAuditEventService.saveOrderAuditEvent(orderAuditEvent, TENANT_ID); - saveFuture.onComplete(ar -> { - assertTrue(ar.succeeded()); - }); + var saveFuture = orderAuditEventService.saveOrderAuditEvent(orderAuditEvent, TENANT_ID); + saveFuture.onComplete(asyncResult -> assertTrue(asyncResult.succeeded())); + + verify(orderEventsDao, times(1)).save(orderAuditEvent, TENANT_ID); } @Test void shouldGetDto() { - String id = UUID.randomUUID().toString(); + var id = UUID.randomUUID().toString(); var orderAuditEvent = createOrderAuditEvent(id); + var orderAuditEventCollection = new OrderAuditEventCollection().withOrderAuditEvents(List.of(orderAuditEvent)).withTotalItems(1); - orderAuditEventService.saveOrderAuditEvent(orderAuditEvent, TENANT_ID); + doReturn(Future.succeededFuture(orderAuditEventCollection)).when(orderEventsDao).getAuditEventsByOrderId(anyString(), anyString(), anyString(), anyInt(), anyInt(), anyString()); - Future dto = orderAuditEventService.getAuditEventsByOrderId(id, "action_date", "asc", 1, 1, TENANT_ID); - dto.onComplete(ar -> { - OrderAuditEventCollection orderAuditEventOptional = ar.result(); - List orderAuditEventList = orderAuditEventOptional.getOrderAuditEvents(); + var dto = orderAuditEventService.getAuditEventsByOrderId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + dto.onComplete(asyncResult -> { + var orderAuditEventOptional = asyncResult.result(); + var orderAuditEventList = orderAuditEventOptional.getOrderAuditEvents(); assertEquals(orderAuditEventList.get(0).getId(), id); - assertEquals(OrderAuditEvent.Action.CREATE.value(), orderAuditEventList.get(0).getAction().value()); + assertEquals(OrderAuditEvent.Action.CREATE, orderAuditEventList.get(0).getAction()); }); - } + verify(orderEventsDao, times(1)).getAuditEventsByOrderId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + } } diff --git a/mod-audit-server/src/test/java/org/folio/services/OrderLineAuditEventsServiceTest.java b/mod-audit-server/src/test/java/org/folio/services/OrderLineAuditEventsServiceTest.java index 272c9816..4d5412ca 100644 --- a/mod-audit-server/src/test/java/org/folio/services/OrderLineAuditEventsServiceTest.java +++ b/mod-audit-server/src/test/java/org/folio/services/OrderLineAuditEventsServiceTest.java @@ -1,64 +1,90 @@ package org.folio.services; +import static org.folio.utils.EntityUtils.ACTION_DATE_SORT_BY; +import static org.folio.utils.EntityUtils.DESC_ORDER; +import static org.folio.utils.EntityUtils.LIMIT; +import static org.folio.utils.EntityUtils.OFFSET; +import static org.folio.utils.EntityUtils.TENANT_ID; +import static org.folio.utils.EntityUtils.createOrderLineAuditEvent; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.List; +import java.util.UUID; + import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.sqlclient.Row; import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.Tuple; import org.folio.dao.acquisition.OrderLineEventsDao; import org.folio.dao.acquisition.impl.OrderLineEventsDaoImpl; import org.folio.rest.jaxrs.model.OrderLineAuditEvent; import org.folio.rest.jaxrs.model.OrderLineAuditEventCollection; +import org.folio.rest.persist.PostgresClient; import org.folio.services.acquisition.impl.OrderLineAuditEventsServiceImpl; import org.folio.util.PostgresClientFactory; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Spy; - -import java.util.List; -import java.util.UUID; - -import static org.folio.utils.EntityUtils.TENANT_ID; -import static org.folio.utils.EntityUtils.createOrderLineAuditEvent; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.mockito.MockitoAnnotations; public class OrderLineAuditEventsServiceTest { - @Spy - private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); @Mock - OrderLineEventsDao orderLineEventsDao = new OrderLineEventsDaoImpl(postgresClientFactory); - @InjectMocks - OrderLineAuditEventsServiceImpl orderLineAuditEventService = new OrderLineAuditEventsServiceImpl(orderLineEventsDao); + private RowSet rowSet; + @Mock + private PostgresClient postgresClient; + + private OrderLineEventsDao orderLineEventsDao; + private OrderLineAuditEventsServiceImpl orderLineAuditEventService; + + @BeforeEach + public void setUp() throws Exception { + try (var ignored = MockitoAnnotations.openMocks(this)) { + var postgresClientFactory = spy(new PostgresClientFactory(Vertx.vertx())); + orderLineEventsDao = spy(new OrderLineEventsDaoImpl(postgresClientFactory)); + orderLineAuditEventService = new OrderLineAuditEventsServiceImpl(orderLineEventsDao); + + doReturn(postgresClient).when(postgresClientFactory).createInstance(TENANT_ID); + } + } @Test public void shouldCallDaoForSuccessfulCase() { var orderLineAuditEvent = createOrderLineAuditEvent(UUID.randomUUID().toString()); + doReturn(Future.succeededFuture(rowSet)).when(postgresClient).execute(anyString(), any(Tuple.class)); - Future> saveFuture = orderLineAuditEventService.saveOrderLineAuditEvent(orderLineAuditEvent, TENANT_ID); + var saveFuture = orderLineAuditEventService.saveOrderLineAuditEvent(orderLineAuditEvent, TENANT_ID); + saveFuture.onComplete(asyncResult -> assertTrue(asyncResult.succeeded())); - saveFuture.onComplete(ar -> { - assertTrue(ar.succeeded()); - }); + verify(orderLineEventsDao, times(1)).save(orderLineAuditEvent, TENANT_ID); } @Test void shouldGetOrderLineDto() { - String id = UUID.randomUUID().toString(); + var id = UUID.randomUUID().toString(); var orderLineAuditEvent = createOrderLineAuditEvent(id); + var orderLineAuditEventCollection = new OrderLineAuditEventCollection().withOrderLineAuditEvents(List.of(orderLineAuditEvent)).withTotalItems(1); - orderLineAuditEventService.saveOrderLineAuditEvent(orderLineAuditEvent, TENANT_ID); + doReturn(Future.succeededFuture(orderLineAuditEventCollection)).when(orderLineEventsDao).getAuditEventsByOrderLineId(anyString(), anyString(), anyString(), anyInt(), anyInt(), anyString()); - Future dto = orderLineAuditEventService.getAuditEventsByOrderLineId(id, "action_date", "desc", 1, 1, TENANT_ID); - dto.onComplete(ar -> { - OrderLineAuditEventCollection orderLineAuditEventOptional = ar.result(); - List orderLineAuditEventList = orderLineAuditEventOptional.getOrderLineAuditEvents(); + var dto = orderLineAuditEventService.getAuditEventsByOrderLineId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + dto.onComplete(asyncResult -> { + var orderLineAuditEventOptional = asyncResult.result(); + var orderLineAuditEventList = orderLineAuditEventOptional.getOrderLineAuditEvents(); assertEquals(orderLineAuditEventList.get(0).getId(), id); assertEquals(OrderLineAuditEvent.Action.CREATE, orderLineAuditEventList.get(0).getAction()); - }); - } + verify(orderLineEventsDao, times(1)).getAuditEventsByOrderLineId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + } } diff --git a/mod-audit-server/src/test/java/org/folio/services/OrganizationAuditEventsServiceTest.java b/mod-audit-server/src/test/java/org/folio/services/OrganizationAuditEventsServiceTest.java new file mode 100644 index 00000000..8ce23718 --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/services/OrganizationAuditEventsServiceTest.java @@ -0,0 +1,92 @@ +package org.folio.services; + +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.Tuple; +import org.folio.CopilotGenerated; +import org.folio.dao.acquisition.OrganizationEventsDao; +import org.folio.dao.acquisition.impl.OrganizationEventsDaoImpl; +import org.folio.rest.jaxrs.model.OrganizationAuditEvent; +import org.folio.rest.jaxrs.model.OrganizationAuditEventCollection; +import org.folio.rest.persist.PostgresClient; +import org.folio.services.acquisition.impl.OrganizationAuditEventsServiceImpl; +import org.folio.util.PostgresClientFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.List; +import java.util.UUID; + +import static org.folio.utils.EntityUtils.ACTION_DATE_SORT_BY; +import static org.folio.utils.EntityUtils.DESC_ORDER; +import static org.folio.utils.EntityUtils.LIMIT; +import static org.folio.utils.EntityUtils.OFFSET; +import static org.folio.utils.EntityUtils.TENANT_ID; +import static org.folio.utils.EntityUtils.createOrganizationAuditEvent; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@CopilotGenerated +public class OrganizationAuditEventsServiceTest { + + @Mock + private RowSet rowSet; + @Mock + private PostgresClient postgresClient; + + private OrganizationEventsDao organizationEventsDao; + private OrganizationAuditEventsServiceImpl organizationAuditEventService; + + @BeforeEach + public void setUp() throws Exception { + try (var ignored = MockitoAnnotations.openMocks(this)) { + var postgresClientFactory = spy(new PostgresClientFactory(Vertx.vertx())); + organizationEventsDao = spy(new OrganizationEventsDaoImpl(postgresClientFactory)); + organizationAuditEventService = new OrganizationAuditEventsServiceImpl(organizationEventsDao); + + doReturn(postgresClient).when(postgresClientFactory).createInstance(TENANT_ID); + } + } + + @Test + void shouldCallDaoForSuccessfulCase() { + var organizationAuditEvent = createOrganizationAuditEvent(UUID.randomUUID().toString()); + doReturn(Future.succeededFuture(rowSet)).when(postgresClient).execute(anyString(), any(Tuple.class)); + + var saveFuture = organizationAuditEventService.saveOrganizationAuditEvent(organizationAuditEvent, TENANT_ID); + saveFuture.onComplete(asyncResult -> assertTrue(asyncResult.succeeded())); + + verify(organizationEventsDao, times(1)).save(organizationAuditEvent, TENANT_ID); + } + + @Test + void shouldGetDto() { + var id = UUID.randomUUID().toString(); + var organizationAuditEvent = createOrganizationAuditEvent(id); + var organizationAuditEventCollection = new OrganizationAuditEventCollection().withOrganizationAuditEvents(List.of(organizationAuditEvent)).withTotalItems(1); + + doReturn(Future.succeededFuture(organizationAuditEventCollection)).when(organizationEventsDao).getAuditEventsByOrganizationId(anyString(), anyString(), anyString(), anyInt(), anyInt(), anyString()); + + var dto = organizationAuditEventService.getAuditEventsByOrganizationId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + dto.onComplete(asyncResult -> { + var organizationAuditEventOptional = asyncResult.result(); + var organizationAuditEventList = organizationAuditEventOptional.getOrganizationAuditEvents(); + + assertEquals(organizationAuditEventList.get(0).getId(), id); + assertEquals(OrganizationAuditEvent.Action.CREATE, organizationAuditEventList.get(0).getAction()); + }); + + verify(organizationEventsDao, times(1)).getAuditEventsByOrganizationId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + } +} diff --git a/mod-audit-server/src/test/java/org/folio/services/PieceAuditEventsServiceTest.java b/mod-audit-server/src/test/java/org/folio/services/PieceAuditEventsServiceTest.java index df2af446..b1e24561 100644 --- a/mod-audit-server/src/test/java/org/folio/services/PieceAuditEventsServiceTest.java +++ b/mod-audit-server/src/test/java/org/folio/services/PieceAuditEventsServiceTest.java @@ -1,40 +1,90 @@ package org.folio.services; +import static org.folio.utils.EntityUtils.ACTION_DATE_SORT_BY; +import static org.folio.utils.EntityUtils.DESC_ORDER; +import static org.folio.utils.EntityUtils.LIMIT; +import static org.folio.utils.EntityUtils.OFFSET; import static org.folio.utils.EntityUtils.TENANT_ID; import static org.folio.utils.EntityUtils.createPieceAuditEvent; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import java.util.List; import java.util.UUID; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.sqlclient.Row; import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.Tuple; import org.folio.dao.acquisition.PieceEventsDao; import org.folio.dao.acquisition.impl.PieceEventsDaoImpl; +import org.folio.rest.jaxrs.model.PieceAuditEvent; +import org.folio.rest.jaxrs.model.PieceAuditEventCollection; +import org.folio.rest.persist.PostgresClient; import org.folio.services.acquisition.impl.PieceAuditEventsServiceImpl; import org.folio.util.PostgresClientFactory; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Spy; +import org.mockito.MockitoAnnotations; public class PieceAuditEventsServiceTest { - @Spy - private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); @Mock - PieceEventsDao pieceEventsDao = new PieceEventsDaoImpl(postgresClientFactory); - @InjectMocks - PieceAuditEventsServiceImpl pieceAuditEventsService = new PieceAuditEventsServiceImpl(pieceEventsDao); + private RowSet rowSet; + @Mock + private PostgresClient postgresClient; + + private PieceEventsDao pieceEventsDao; + private PieceAuditEventsServiceImpl pieceAuditEventsService; + + @BeforeEach + public void setUp() throws Exception { + try (var ignored = MockitoAnnotations.openMocks(this)) { + var postgresClientFactory = spy(new PostgresClientFactory(Vertx.vertx())); + pieceEventsDao = spy(new PieceEventsDaoImpl(postgresClientFactory)); + pieceAuditEventsService = new PieceAuditEventsServiceImpl(pieceEventsDao); + + doReturn(postgresClient).when(postgresClientFactory).createInstance(TENANT_ID); + } + } @Test void shouldCallDaoSuccessfully() { var pieceAuditEvent = createPieceAuditEvent(UUID.randomUUID().toString()); + doReturn(Future.succeededFuture(rowSet)).when(postgresClient).execute(anyString(), any(Tuple.class)); + + var saveFuture = pieceAuditEventsService.savePieceAuditEvent(pieceAuditEvent, TENANT_ID); + saveFuture.onComplete(asyncResult -> assertTrue(asyncResult.succeeded())); - Future> saveFuture = pieceAuditEventsService.savePieceAuditEvent(pieceAuditEvent, TENANT_ID); - saveFuture.onComplete(ar -> { - assertTrue(ar.succeeded()); + verify(pieceEventsDao, times(1)).save(pieceAuditEvent, TENANT_ID); + } + + @Test + void shouldGetDto() { + var id = UUID.randomUUID().toString(); + var pieceAuditEvent = createPieceAuditEvent(id); + var pieceAuditEventCollection = new PieceAuditEventCollection().withPieceAuditEvents(List.of(pieceAuditEvent)).withTotalItems(1); + + doReturn(Future.succeededFuture(pieceAuditEventCollection)).when(pieceEventsDao).getAuditEventsByPieceId(anyString(), anyString(), anyString(), anyInt(), anyInt(), anyString()); + + var dto = pieceAuditEventsService.getAuditEventsByPieceId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); + dto.onComplete(asyncResult -> { + var pieceAuditEventOptional = asyncResult.result(); + var pieceAuditEventList = pieceAuditEventOptional.getPieceAuditEvents(); + + assertEquals(pieceAuditEventList.get(0).getId(), id); + assertEquals(PieceAuditEvent.Action.CREATE, pieceAuditEventList.get(0).getAction()); }); + + verify(pieceEventsDao, times(1)).getAuditEventsByPieceId(id, ACTION_DATE_SORT_BY, DESC_ORDER, LIMIT, OFFSET, TENANT_ID); } } diff --git a/mod-audit-server/src/test/java/org/folio/utils/EntityUtils.java b/mod-audit-server/src/test/java/org/folio/utils/EntityUtils.java index d359311f..e1a57beb 100644 --- a/mod-audit-server/src/test/java/org/folio/utils/EntityUtils.java +++ b/mod-audit-server/src/test/java/org/folio/utils/EntityUtils.java @@ -4,16 +4,26 @@ import java.util.UUID; import io.vertx.core.json.JsonObject; +import org.folio.rest.jaxrs.model.InvoiceAuditEvent; +import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; import org.folio.rest.jaxrs.model.OrderAuditEvent; import org.folio.rest.jaxrs.model.OrderLineAuditEvent; +import org.folio.rest.jaxrs.model.OrganizationAuditEvent; import org.folio.rest.jaxrs.model.PieceAuditEvent; public class EntityUtils { - public static String TENANT_ID = "diku"; - public static String PIECE_ID = "2cd4adc4-f287-49b6-a9c6-9eacdc4868e7"; - public static String ORDER_ID = "a21fc51c-d46b-439b-8c79-9b2be41b79a6"; - public static String ORDER_LINE_ID = "a22fc51c-d46b-439b-8c79-9b2be41b79a6"; + public static final String ACTION_DATE_SORT_BY = "action_date"; + public static final String DESC_ORDER = "desc"; + public static final int LIMIT = 1; + public static final int OFFSET = 1; + public static final String TENANT_ID = "diku"; + public static final String PIECE_ID = "2cd4adc4-f287-49b6-a9c6-9eacdc4868e7"; + public static final String ORDER_ID = "a21fc51c-d46b-439b-8c79-9b2be41b79a6"; + public static final String ORDER_LINE_ID = "3448efa3-ef4b-4518-a924-d1b36255cc20"; + public static final String INVOICE_ID = "3f29b1a4-8c2b-4d3a-9b1e-5f2a1b4c8d3a"; + public static final String INVOICE_LINE_ID = "550e8400-e29b-41d4-a716-446655440001"; + public static final String ORGANIZATION_ID = "39e7362e-b487-4d51-8bdb-cbd6bf29d1c7"; public static OrderAuditEvent createOrderAuditEvent(String id) { JsonObject jsonObject = new JsonObject(); @@ -96,4 +106,71 @@ public static PieceAuditEvent createPieceAuditEventWithoutSnapshot() { .withActionDate(new Date()) .withPieceSnapshot("Test"); } + + public static InvoiceAuditEvent createInvoiceAuditEvent(String id) { + JsonObject jsonObject = new JsonObject(); + jsonObject.put("name", "Test Invoice 123"); + + return new InvoiceAuditEvent() + .withId(id) + .withAction(InvoiceAuditEvent.Action.CREATE) + .withInvoiceId(UUID.randomUUID().toString()) + .withUserId(UUID.randomUUID().toString()) + .withEventDate(new Date()) + .withActionDate(new Date()) + .withInvoiceSnapshot(jsonObject); + } + + public static InvoiceAuditEvent createInvoiceAuditEventWithoutSnapshot() { + return new InvoiceAuditEvent() + .withId(UUID.randomUUID().toString()) + .withAction(InvoiceAuditEvent.Action.CREATE) + .withInvoiceId(UUID.randomUUID().toString()) + .withUserId(UUID.randomUUID().toString()) + .withEventDate(new Date()) + .withActionDate(new Date()) + .withInvoiceSnapshot("Test"); + } + + public static InvoiceLineAuditEvent createInvoiceLineAuditEvent(String id) { + JsonObject jsonObject = new JsonObject(); + jsonObject.put("name", "Test Product"); + + return new InvoiceLineAuditEvent() + .withId(id) + .withAction(InvoiceLineAuditEvent.Action.CREATE) + .withInvoiceId(INVOICE_ID) + .withInvoiceLineId(INVOICE_LINE_ID) + .withUserId(UUID.randomUUID().toString()) + .withEventDate(new Date()) + .withActionDate(new Date()) + .withInvoiceLineSnapshot(jsonObject); + } + + + + public static OrganizationAuditEvent createOrganizationAuditEvent(String id) { + JsonObject jsonObject = new JsonObject(); + jsonObject.put("name", "Test Organization 123"); + + return new OrganizationAuditEvent() + .withId(id) + .withAction(OrganizationAuditEvent.Action.CREATE) + .withOrganizationId(UUID.randomUUID().toString()) + .withUserId(UUID.randomUUID().toString()) + .withEventDate(new Date()) + .withActionDate(new Date()) + .withOrganizationSnapshot(jsonObject); + } + + public static OrganizationAuditEvent createOrganizationAuditEventWithoutSnapshot() { + return new OrganizationAuditEvent() + .withId(UUID.randomUUID().toString()) + .withAction(OrganizationAuditEvent.Action.CREATE) + .withOrganizationId(UUID.randomUUID().toString()) + .withUserId(UUID.randomUUID().toString()) + .withEventDate(new Date()) + .withActionDate(new Date()) + .withOrganizationSnapshot("Test"); + } } diff --git a/pom.xml b/pom.xml index 6c68a24c..d4eddff0 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 org.folio mod-audit - 2.10.2-SNAPSHOT + 3.0.0-SNAPSHOT pom diff --git a/ramls/acquisition-events.raml b/ramls/acquisition-events.raml index 8bdd0850..e57e2d58 100644 --- a/ramls/acquisition-events.raml +++ b/ramls/acquisition-events.raml @@ -8,7 +8,6 @@ documentation: - title: Acquisition Audit events API content: API for retrieving events for acquisition changes - types: errors: !include raml-util/schemas/errors.schema order-line-audit-event: !include order_line_audit_event.json @@ -17,6 +16,11 @@ types: order-line-audit-event-collection: !include order_line_audit_event_collection.json piece-audit-event: !include piece_audit_event.json piece-audit-event-collection: !include piece_audit_event_collection.json + invoice-audit-event: !include invoice_audit_event.json + invoice-audit-event-collection: !include invoice_audit_event_collection.json + invoice-line-audit-event-collection: !include invoice_line_audit_event_collection.json + organization-audit-event: !include organization_audit_event.json + organization-audit-event-collection: !include organization_audit_event_collection.json traits: searchable: !include raml-util/traits/searchable.raml @@ -159,3 +163,105 @@ traits: example: strict: false value: !include raml-util/examples/errors.sample + + /invoice/{id}: + get: + description: Get list of invoice events by invoice_id + is: [ + pageable, + validate + ] + queryParameters: + sortBy: + description: "sorting by field: actionDate" + type: string + default: action_date + sortOrder: + description: "sort order: asc or desc" + enum: [asc, desc] + type: string + default: desc + limit: + default: 2147483647 + offset: + default: 0 + responses: + 200: + body: + application/json: + type: invoice-audit-event-collection + 500: + description: "Internal server error" + body: + application/json: + type: errors + example: + strict: false + value: !include raml-util/examples/errors.sample + + /invoice-line/{id}: + get: + description: Get list of invoice_line events by invoice_line_id + is: [ + pageable, + validate + ] + queryParameters: + sortBy: + description: "sorting by field: actionDate" + type: string + default: action_date + sortOrder: + description: "sort order: asc or desc" + enum: [asc, desc] + type: string + default: desc + limit: + default: 2147483647 + offset: + default: 0 + responses: + 200: + body: + application/json: + type: invoice-line-audit-event-collection + 500: + description: "Internal server error" + body: + application/json: + type: errors + + /organization/{id}: + get: + description: Get list of organization events by organization_id + is: [ + pageable, + validate + ] + queryParameters: + sortBy: + description: "sorting by field: actionDate" + type: string + default: action_date + sortOrder: + description: "sort order: asc or desc" + enum: [asc, desc] + type: string + default: desc + limit: + default: 2147483647 + offset: + default: 0 + responses: + 200: + body: + application/json: + type: organization-audit-event-collection + 500: + description: "Internal server error" + body: + application/json: + type: errors + example: + strict: false + value: !include raml-util/examples/errors.sample diff --git a/ramls/invoice_audit_event.json b/ramls/invoice_audit_event.json new file mode 100644 index 00000000..ea5359ac --- /dev/null +++ b/ramls/invoice_audit_event.json @@ -0,0 +1,40 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Invoice audit event", + "type": "object", + "properties": { + "id": { + "description": "UUID of the event", + "$ref": "common/uuid.json" + }, + "action": { + "description": "Action for invoice (Create, Edit or Delete)", + "type": "string", + "$ref": "event_action.json" + }, + "invoiceId": { + "description": "UUID of the invoice", + "$ref": "common/uuid.json" + }, + "userId": { + "description": "UUID of the user who performed the action", + "$ref": "common/uuid.json" + }, + "eventDate": { + "description": "Date time when event triggered", + "format": "date-time", + "type": "string" + }, + "actionDate": { + "description": "Date time when invoice action occurred", + "format": "date-time", + "type": "string" + }, + "invoiceSnapshot": { + "description": "Full snapshot of the invoice", + "type": "object", + "javaType": "java.lang.Object" + } + }, + "additionalProperties": true +} diff --git a/ramls/invoice_audit_event_collection.json b/ramls/invoice_audit_event_collection.json new file mode 100644 index 00000000..75fce73b --- /dev/null +++ b/ramls/invoice_audit_event_collection.json @@ -0,0 +1,25 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Collection of invoiceAuditEvents", + "type": "object", + "additionalProperties": false, + "properties": { + "invoiceAuditEvents": { + "description": "List of invoiceAuditEvents", + "type": "array", + "id": "invoiceAuditEventsList", + "items": { + "type": "object", + "$ref": "invoice_audit_event.json" + } + }, + "totalItems": { + "description": "total records", + "type": "integer" + } + }, + "required": [ + "invoiceAuditEvents", + "totalItems" + ] +} diff --git a/ramls/invoice_line_audit_event.json b/ramls/invoice_line_audit_event.json new file mode 100644 index 00000000..6c481fe4 --- /dev/null +++ b/ramls/invoice_line_audit_event.json @@ -0,0 +1,44 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Invoice line audit event", + "type": "object", + "properties": { + "id": { + "description": "UUID of the event", + "$ref": "common/uuid.json" + }, + "action": { + "description": "Action for invoice line (Create, Edit or Delete)", + "type": "string", + "$ref": "event_action.json" + }, + "invoiceId": { + "description": "UUID of the invoice", + "$ref": "common/uuid.json" + }, + "invoiceLineId": { + "description": "UUID of the invoice line", + "$ref": "common/uuid.json" + }, + "userId": { + "description": "UUID of the user who performed the action", + "$ref": "common/uuid.json" + }, + "eventDate": { + "description": "Date time when event triggered", + "format": "date-time", + "type": "string" + }, + "actionDate": { + "description": "Date time when invoice action occurred", + "format": "date-time", + "type": "string" + }, + "invoiceLineSnapshot": { + "description": "Full snapshot of the invoice line", + "type": "object", + "javaType": "java.lang.Object" + } + }, + "additionalProperties": true +} diff --git a/ramls/invoice_line_audit_event_collection.json b/ramls/invoice_line_audit_event_collection.json new file mode 100644 index 00000000..b6832e71 --- /dev/null +++ b/ramls/invoice_line_audit_event_collection.json @@ -0,0 +1,25 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Collection of invoiceLineAuditEvents", + "type": "object", + "additionalProperties": false, + "properties": { + "invoiceLineAuditEvents": { + "description": "List of invoiceLineAuditEvents", + "type": "array", + "id": "invoiceLineAuditEventsList", + "items": { + "type": "object", + "$ref": "invoice_line_audit_event.json" + } + }, + "totalItems": { + "description": "total records", + "type": "integer" + } + }, + "required": [ + "invoiceLineAuditEvents", + "totalItems" + ] +} diff --git a/ramls/organization_audit_event.json b/ramls/organization_audit_event.json new file mode 100644 index 00000000..053f96a9 --- /dev/null +++ b/ramls/organization_audit_event.json @@ -0,0 +1,40 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Organization audit event", + "type": "object", + "properties": { + "id": { + "description": "UUID of the event", + "$ref": "common/uuid.json" + }, + "action": { + "description": "Action for organization (Create, Edit or Delete)", + "type": "string", + "$ref": "event_action.json" + }, + "organizationId": { + "description": "UUID of the organization", + "$ref": "common/uuid.json" + }, + "userId": { + "description": "UUID of the user who performed the action", + "$ref": "common/uuid.json" + }, + "eventDate": { + "description": "Date time when event triggered", + "format": "date-time", + "type": "string" + }, + "actionDate": { + "description": "Date time when organization action occurred", + "format": "date-time", + "type": "string" + }, + "organizationSnapshot": { + "description": "Full snapshot of the organization", + "type": "object", + "javaType": "java.lang.Object" + } + }, + "additionalProperties": true +} diff --git a/ramls/organization_audit_event_collection.json b/ramls/organization_audit_event_collection.json new file mode 100644 index 00000000..667c1319 --- /dev/null +++ b/ramls/organization_audit_event_collection.json @@ -0,0 +1,25 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Collection of organizationAuditEvents", + "type": "object", + "additionalProperties": false, + "properties": { + "organizationAuditEvents": { + "description": "List of organizationAuditEvents", + "type": "array", + "id": "organizationAuditEventsList", + "items": { + "type": "object", + "$ref": "organization_audit_event.json" + } + }, + "totalItems": { + "description": "total records", + "type": "integer" + } + }, + "required": [ + "organizationAuditEvents", + "totalItems" + ] +}