diff --git a/descriptors/ModuleDescriptor-template.json b/descriptors/ModuleDescriptor-template.json index 70e9915..bf8b01c 100644 --- a/descriptors/ModuleDescriptor-template.json +++ b/descriptors/ModuleDescriptor-template.json @@ -152,16 +152,16 @@ ] }, { - "id": "circulation-logs", - "version": "1.2", + "id": "acquisition-invoice-events", + "version": "1.0", "handlers": [ { "methods": [ "GET" ], - "pathPattern": "/audit-data/circulation/logs", + "pathPattern": "/audit-data/acquisition/invoice/{id}", "permissionsRequired": [ - "circulation-logs.collection.get" + "acquisition.invoice.events.get" ] } ] @@ -181,6 +181,21 @@ } ] }, + { + "id": "circulation-logs", + "version": "1.2", + "handlers": [ + { + "methods": [ + "GET" + ], + "pathPattern": "/audit-data/circulation/logs", + "permissionsRequired": [ + "circulation-logs.collection.get" + ] + } + ] + }, { "id": "audit-data-event-handlers", "version": "1.1", @@ -279,6 +294,11 @@ "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", @@ -299,6 +319,7 @@ "acquisition.order-line.events.get", "acquisition.piece.events.get", "acquisition.piece.events.history.get", + "acquisition.invoice.events.get", "acquisition.invoice-line.events.get" ] } 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 0000000..fc955b6 --- /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 sortInvoice sort invoice + * @param limit limit + * @param offset offset + * @param tenantId tenant id + * @return future with InvoiceAuditEventCollection + */ + Future getAuditEventsByInvoiceId(String invoiceId, String sortBy, String sortInvoice, 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 0000000..f4a8c5d --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/dao/acquisition/impl/InvoiceEventsDaoImpl.java @@ -0,0 +1,112 @@ +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 invoiceAuditEvent, String tenantId) { + LOGGER.debug("save:: Saving Invoice AuditEvent with tenant id : {}", tenantId); + String logTable = formatDBTableName(tenantId, TABLE_NAME); + String query = format(INSERT_SQL, logTable); + return makeSaveCall(query, invoiceAuditEvent, tenantId) + .onSuccess(rows -> LOGGER.info("save:: Saved Invoice AuditEvent with tenant id : {}", tenantId)) + .onFailure(e -> LOGGER.error("Failed to save record with id: {} for invoice id: {} in to table {}", + invoiceAuditEvent.getId(), invoiceAuditEvent.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(rowSet -> rowSet.rowCount() == 0 ? new InvoiceAuditEventCollection().withTotalItems(0) + : mapRowToListOfInvoiceEvent(rowSet)); + } + + 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) {LOGGER.error("Failed to save record with id: {} for invoice id: {} in to table {}", + invoiceAuditEvent.getId(), invoiceAuditEvent.getInvoiceId(), TABLE_NAME, e); + return Future.failedFuture(e); + } + } + + private InvoiceAuditEventCollection mapRowToListOfInvoiceEvent(RowSet rowSet) { + LOGGER.debug("mapRowToListOfInvoiceEvent:: Mapping row to List of Invoice Events"); + 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/rest/impl/AuditDataAcquisitionImpl.java b/mod-audit-server/src/main/java/org/folio/rest/impl/AuditDataAcquisitionImpl.java index 57ede44..c42c9dd 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,6 +7,7 @@ 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; @@ -14,6 +15,7 @@ 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; @@ -38,6 +40,8 @@ public class AuditDataAcquisitionImpl implements AuditDataAcquisition { @Autowired private PieceAuditEventsService pieceAuditEventsService; @Autowired + private InvoiceAuditEventsService invoiceAuditEventsService; + @Autowired private InvoiceLineAuditEventsService invoiceLineAuditEventsService; public AuditDataAcquisitionImpl() { @@ -114,6 +118,24 @@ 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 piece 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) { @@ -126,7 +148,7 @@ public void getAuditDataAcquisitionInvoiceLineById(String invoiceLineId, String .otherwise(this::mapExceptionToResponse) .onComplete(asyncResultHandler); } catch (Exception e) { - LOGGER.error("Failed to get order line audit events by order line id: {}", invoiceLineId, e); + LOGGER.error("Failed to get invoice line audit events by order line id: {}", invoiceLineId, e); asyncResultHandler.handle(Future.succeededFuture(mapExceptionToResponse(e))); } } 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 e6fcaf5..9e60c8d 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,6 +16,7 @@ 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; @@ -30,10 +32,28 @@ 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; @Override public void init(Vertx vertx, Context context, Handler> handler) { @@ -65,36 +85,31 @@ 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(); - 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); - - vertx.deployVerticle(getVerticleName(verticleFactory, InvoiceLineEventConsumersVerticle.class), - new DeploymentOptions() - .setWorker(true) - .setInstances(acqPieceConsumerInstancesNumber), invoiceLineEventsConsumer); + 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); LOGGER.info("deployConsumersVerticles:: All consumer verticles were successfully deployed"); return GenericCompositeFuture.all(Arrays.asList( orderEventsConsumer.future(), orderLineEventsConsumer.future(), pieceEventsConsumer.future(), + invoiceEventsConsumer.future(), invoiceLineEventsConsumer.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) { LOGGER.debug("getVerticleName:: Retrieving Verticle name"); return verticleFactory.prefix() + ":" + clazz.getName(); 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 0000000..782480f --- /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 sortInvoice sort invoice + * @param limit limit + * @param offset offset + * @return future with InvoiceAuditEventCollection + */ + Future getAuditEventsByInvoiceId(String invoiceId, String sortBy, String sortInvoice, 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 0000000..d2e427c --- /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 index 31c5f38..9fc6c4d 100644 --- 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 @@ -26,7 +26,7 @@ public InvoiceLineAuditEventsServiceImpl(InvoiceLineEventsDao invoiceLineEventsD @Override public Future> saveInvoiceLineAuditEvent(InvoiceLineAuditEvent invoiceLineAuditEvent, String tenantId) { - LOGGER.debug("saveInvoiceLineAuditEvent:: Saving invoice line audit event with id: {} in tenant Id : {}", invoiceLineAuditEvent.getId(), 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); @@ -36,7 +36,7 @@ public Future> saveInvoiceLineAuditEvent(InvoiceLineAuditEvent invoi @Override public Future getAuditEventsByInvoiceLineId(String invoiceLineId, String sortBy, String sortOrder, int limit, int offset, String tenantId) { - LOGGER.debug("getAuditEventsByInvoiceLineId:: Retrieving audit events for invoice line Id : {} and tenant Id : {}", invoiceLineId, 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/util/AcquisitionEventType.java b/mod-audit-server/src/main/java/org/folio/util/AcquisitionEventType.java index 3a863ce..b500403 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 @@ -4,6 +4,7 @@ public enum AcquisitionEventType { ACQ_ORDER_CHANGED("ACQ_ORDER_CHANGED"), ACQ_ORDER_LINE_CHANGED("ACQ_ORDER_LINE_CHANGED"), ACQ_PIECE_CHANGED("ACQ_PIECE_CHANGED"), + ACQ_INVOICE_CHANGED("ACQ_INVOICE_CHANGED"), ACQ_INVOICE_LINE_CHANGED("ACQ_INVOICE_LINE_CHANGED") ; private final String topicName; 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 0000000..25afa5c --- /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/consumers/InvoiceEventsHandler.java b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/InvoiceEventsHandler.java new file mode 100644 index 0000000..e24ffdf --- /dev/null +++ b/mod-audit-server/src/main/java/org/folio/verticle/acquisition/consumers/InvoiceEventsHandler.java @@ -0,0 +1,61 @@ +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 io.vertx.kafka.client.producer.KafkaHeader; +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.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class InvoiceEventsHandler implements AsyncRecordHandler { + + private static final Logger LOGGER = LogManager.getLogger(); + + private final InvoiceAuditEventsService invoiceAuditEventsService; + private final Vertx vertx; + + public InvoiceEventsHandler(@Autowired Vertx vertx, + @Autowired InvoiceAuditEventsService invoiceAuditEventsService) { + this.vertx = vertx; + this.invoiceAuditEventsService = invoiceAuditEventsService; + } + + @Override + public Future handle(KafkaConsumerRecord kafkaConsumerRecord) { + Promise result = Promise.promise(); + List kafkaHeaders = kafkaConsumerRecord.headers(); + OkapiConnectionParams okapiConnectionParams = new OkapiConnectionParams(KafkaHeaderUtils.kafkaHeadersToMap(kafkaHeaders), vertx); + InvoiceAuditEvent 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/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 0000000..10c8f7b --- /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/schema.json b/mod-audit-server/src/main/resources/templates/db_scripts/schema.json index 5d0b7fc..4254e72 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 @@ -80,6 +80,11 @@ "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", 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 a7cad1f..06ddbe3 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,7 @@ 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; @@ -33,11 +35,13 @@ 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; @@ -69,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(":"); @@ -197,6 +201,18 @@ 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 { } 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 0000000..e1c5e05 --- /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 index 6bc2b4d..9d7ec13 100644 --- a/mod-audit-server/src/test/java/org/folio/dao/InvoiceLineEventsDaoTest.java +++ b/mod-audit-server/src/test/java/org/folio/dao/InvoiceLineEventsDaoTest.java @@ -4,19 +4,16 @@ 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.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.CopilotGenerated; import org.folio.dao.acquisition.impl.InvoiceLineEventsDaoImpl; import org.folio.rest.jaxrs.model.InvoiceLineAuditEvent; -import org.folio.rest.jaxrs.model.InvoiceLineAuditEventCollection; import org.folio.util.PostgresClientFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -29,9 +26,8 @@ public class InvoiceLineEventsDaoTest { @Spy private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); - @InjectMocks - InvoiceLineEventsDaoImpl invoiceLineEventsDao = new InvoiceLineEventsDaoImpl(postgresClientFactory); + InvoiceLineEventsDaoImpl invoiceLineEventsDao; @BeforeEach public void setUp() { @@ -42,39 +38,43 @@ public void setUp() { @Test void shouldCreateEventProcessed() { var invoiceLineAuditEvent = createInvoiceLineAuditEvent(UUID.randomUUID().toString()); - Future> saveFuture = invoiceLineEventsDao.save(invoiceLineAuditEvent, TENANT_ID); + + 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()); - Future> saveFuture = invoiceLineEventsDao.save(invoiceLineAuditEvent, TENANT_ID); + var saveFuture = invoiceLineEventsDao.save(invoiceLineAuditEvent, TENANT_ID); saveFuture.onComplete(ar -> { - Future> reSaveFuture = invoiceLineEventsDao.save(invoiceLineAuditEvent, TENANT_ID); + 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() { - String id = UUID.randomUUID().toString(); + var id = UUID.randomUUID().toString(); var invoiceLineAuditEvent = createInvoiceLineAuditEvent(id); invoiceLineEventsDao.save(invoiceLineAuditEvent, TENANT_ID); - Future dto = invoiceLineEventsDao.getAuditEventsByInvoiceLineId(id, "action_date", "asc", 1, 1, TENANT_ID); + var dto = invoiceLineEventsDao.getAuditEventsByInvoiceLineId(id, "action_date", "asc", 1, 1, TENANT_ID); dto.onComplete(ar -> { - InvoiceLineAuditEventCollection invoiceLineAuditEventOptional = ar.result(); - List invoiceLineAuditEventList = invoiceLineAuditEventOptional.getInvoiceLineAuditEvents(); + 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 15c937e..36293f2 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,23 +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.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; 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 io.vertx.sqlclient.Tuple; 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; @@ -33,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() { @@ -45,27 +37,25 @@ public void setUp() { void shouldCreateEventProcessed() { var orderAuditEvent = createOrderAuditEvent(UUID.randomUUID().toString()); - Future> saveFuture = orderEventDao.save(orderAuditEvent, TENANT_ID); - saveFuture.onComplete(ar -> { - assertTrue(ar.succeeded()); - verify(postgresClientFactory, times(1)).createInstance(TENANT_ID).execute(anyString(), any(Tuple.class)); - }); + 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).execute(anyString(), any(Tuple.class)); }); }); + verify(postgresClientFactory, times(1)).createInstance(TENANT_ID); } @Test @@ -75,15 +65,15 @@ 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(1)).createInstance(TENANT_ID).selectRead(anyString(), any(Tuple.class), any()); }); + 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 88d9ae8..61c0961 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/PieceEventsDaoTest.java b/mod-audit-server/src/test/java/org/folio/dao/PieceEventsDaoTest.java index 817d0b7..65bb703 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 4889ca3..f0a1331 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 353c02b..c14a419 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 @@ -4,6 +4,7 @@ import static org.folio.utils.EntityUtils.ORDER_ID; import static org.folio.utils.EntityUtils.ORDER_LINE_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,10 +16,13 @@ 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.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; @@ -40,6 +44,7 @@ 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 TENANT_ID = "modaudittest"; @@ -53,6 +58,8 @@ public class AuditDataAcquisitionAPITest extends ApiTestBase { @InjectMocks PieceEventsDaoImpl pieceEventsDao; @InjectMocks + InvoiceEventsDaoImpl invoiceEventsDao; + @InjectMocks InvoiceLineEventsDaoImpl invoiceLineEventsDao; @BeforeEach @@ -60,6 +67,8 @@ public void setUp() { MockitoAnnotations.openMocks(this); orderEventDao = new OrderEventsDaoImpl(postgresClientFactory); orderLineEventDao = new OrderLineEventsDaoImpl(postgresClientFactory); + invoiceEventsDao = new InvoiceEventsDaoImpl(postgresClientFactory); + invoiceLineEventsDao = new InvoiceLineEventsDaoImpl(postgresClientFactory); } @Test @@ -254,6 +263,49 @@ void shouldReturnPieceEventsStatusChangesHistoryGetByPieceId() { .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 void shouldReturnInvoiceLineEventsOnGetByInvoiceLineId() { JsonObject jsonObject = new JsonObject(); 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 0000000..966f85f --- /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/services/InvoiceAuditEventsServiceTest.java b/mod-audit-server/src/test/java/org/folio/services/InvoiceAuditEventsServiceTest.java new file mode 100644 index 0000000..83f4c5d --- /dev/null +++ b/mod-audit-server/src/test/java/org/folio/services/InvoiceAuditEventsServiceTest.java @@ -0,0 +1,64 @@ +package org.folio.services; + +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 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 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.services.acquisition.impl.InvoiceAuditEventsServiceImpl; +import org.folio.util.PostgresClientFactory; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; + +@CopilotGenerated +public class InvoiceAuditEventsServiceTest { + + @Spy + private PostgresClientFactory postgresClientFactory = new PostgresClientFactory(Vertx.vertx()); + @Mock + InvoiceEventsDao invoiceEventsDao = new InvoiceEventsDaoImpl(postgresClientFactory); + + @InjectMocks + InvoiceAuditEventsServiceImpl invoiceAuditEventService = new InvoiceAuditEventsServiceImpl(invoiceEventsDao); + + @Test + void shouldCallDaoForSuccessfulCase() { + var invoiceAuditEvent = createInvoiceAuditEvent(UUID.randomUUID().toString()); + + Future> saveFuture = invoiceAuditEventService.saveInvoiceAuditEvent(invoiceAuditEvent, TENANT_ID); + saveFuture.onComplete(ar -> { + assertTrue(ar.succeeded()); + }); + } + + @Test + void shouldGetDto() { + String id = UUID.randomUUID().toString(); + var invoiceAuditEvent = createInvoiceAuditEvent(id); + + invoiceAuditEventService.saveInvoiceAuditEvent(invoiceAuditEvent, TENANT_ID); + + Future dto = invoiceAuditEventService.getAuditEventsByInvoiceId(id, "action_date", "asc", 1, 1, TENANT_ID); + dto.onComplete(ar -> { + InvoiceAuditEventCollection invoiceAuditEventOptional = ar.result(); + List invoiceAuditEventList = invoiceAuditEventOptional.getInvoiceAuditEvents(); + + assertEquals(invoiceAuditEventList.get(0).getId(), id); + assertEquals(InvoiceAuditEvent.Action.CREATE.value(), invoiceAuditEventList.get(0).getAction().value()); + }); + } +} 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 87ba31e..05acd83 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,6 +4,7 @@ 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; @@ -15,7 +16,7 @@ public class EntityUtils { 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 = "a22fc51c-d46b-439b-8c79-9b2be41b79a6"; - public static final String INVOICE_ID = "550e8400-e29b-41d4-a716-446655440001"; + 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 OrderAuditEvent createOrderAuditEvent(String id) { @@ -100,6 +101,31 @@ public static PieceAuditEvent createPieceAuditEventWithoutSnapshot() { .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"); diff --git a/ramls/acquisition-events.raml b/ramls/acquisition-events.raml index ccdc057..9b21ea0 100644 --- a/ramls/acquisition-events.raml +++ b/ramls/acquisition-events.raml @@ -17,6 +17,8 @@ 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 traits: @@ -161,6 +163,41 @@ traits: 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 diff --git a/ramls/invoice_audit_event.json b/ramls/invoice_audit_event.json new file mode 100644 index 0000000..ea5359a --- /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 0000000..75fce73 --- /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" + ] +}