Skip to content

Commit

Permalink
Init commit
Browse files Browse the repository at this point in the history
  • Loading branch information
JanisSaldabols committed Nov 21, 2023
1 parent e8d8b53 commit 5395b97
Show file tree
Hide file tree
Showing 17 changed files with 151 additions and 150 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ GRANT ALL PRIVILEGES ON DATABASE folio_modules TO folio;
The module's database connection is then configured by setting environment
variables:
`DB_HOST`, `DB_PORT`, `DB_USERNAME`, `DB_PASSWORD`, `DB_DATABASE`,
`DB_MAXPOOLSIZE`, `DB_SERVER_PEM`.
`DB_MAXPOOLSIZE`.

Once configured, start the module with:

Expand Down
16 changes: 15 additions & 1 deletion descriptors/ModuleDescriptor-template.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,18 @@
],
"requires": [],
"permissionSets": [
{
"permissionName": "mod-batch-print.print.write",
"displayName": "batch print - write print entries",
"description": "Write print entries",
"visible": false
},
{
"permissionName": "mod-batch-print.print.read",
"displayName": "batch print - read print entries",
"description": "Read print entries",
"visible": false
},
{
"permissionName": "mod-batch-print.entries.mail.post",
"displayName": "batch print - send mail",
Expand Down Expand Up @@ -163,7 +175,9 @@
"mod-batch-print.entries.collection.get",
"mod-batch-print.entries.item.get",
"mod-batch-print.entries.item.put",
"mod-batch-print.entries.item.delete"
"mod-batch-print.entries.item.delete",
"mod-batch-print.print.write",
"mod-batch-print.print.read"
]
}
],
Expand Down
4 changes: 4 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@
<groupId>io.vertx</groupId>
<artifactId>vertx-pg-client</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-sql-client-templates</artifactId>
</dependency>
<dependency>
<groupId>org.folio</groupId>
<artifactId>vertx-lib</artifactId>
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/org/folio/print/server/data/Message.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class Message {
private String deliveryChannel;
private String notificationId;
private String from;
private String to;
private String outputFormat;
private String header;
private String body;
Expand Down
38 changes: 6 additions & 32 deletions src/main/java/org/folio/print/server/data/PrintEntry.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import java.time.ZonedDateTime;
import java.util.UUID;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PrintEntry {

Expand All @@ -13,37 +17,7 @@ public class PrintEntry {

private PrintEntryType type;

private String content;

public UUID getId() {
return id;
}

public void setId(UUID id) {
this.id = id;
}

public ZonedDateTime getCreated() {
return created;
}

public void setCreated(ZonedDateTime created) {
this.created = created;
}
private String sortingField;

public PrintEntryType getType() {
return type;
}

public void setType(PrintEntryType type) {
this.type = type;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}
private String content;
}
3 changes: 1 addition & 2 deletions src/main/java/org/folio/print/server/main/MainVerticle.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,12 @@ public void start(Promise<Void> promise) {
log.info("Listening on port {}", port);

var printServiceService = new PrintService();
var batchCreationResource = new BatchCreationResource();

RouterCreator[] routerCreators = {
printServiceService,
batchCreationResource,
new Tenant2Api(printServiceService),
new HealthApi(),
new BatchCreationResource()
};

RouterCreator.mountAll(vertx, routerCreators)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
Expand All @@ -16,39 +16,37 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.pdfbox.util.Hex;
import org.folio.okapi.common.XOkapiHeaders;
import org.folio.print.server.data.PrintEntry;
import org.folio.print.server.data.PrintEntryType;
import org.folio.print.server.service.PdfService;
import org.folio.print.server.service.PrintService;
import org.folio.print.server.storage.PrintStorage;
import org.folio.tlib.RouterCreator;


public class BatchCreationResource implements RouterCreator {
private static final Logger LOGGER = LogManager.getLogger(BatchCreationResource.class);
private static final int MAX_COUNT_IN_BATCH = 1000;

public BatchCreationResource() {
}

@Override
public Future<Router> createRouter(Vertx vertx) {
Router router = Router.router(vertx);
String rootPath = "/print/batch-creation";
router.post(rootPath + "*").handler(BodyHandler.create());
router.post(rootPath).handler(this::process)
.failureHandler(this::failureResponder);
router.post("/print/batch-creation").handler((ctx) -> process(ctx, vertx))
.failureHandler(this::failureResponder);
return Future.succeededFuture(router);
}

private void process(RoutingContext ctx) {
PrintStorage storage = PrintService.create(ctx);
private void process(RoutingContext ctx, Vertx vertx) {
String tenant = ctx.request().getHeader(XOkapiHeaders.TENANT);
JsonArray permissions = new JsonArray(ctx.request().getHeader(XOkapiHeaders.PERMISSIONS));
PrintStorage printStorage = new PrintStorage(vertx, tenant, permissions);
LocalDateTime localDateTime = LocalDateTime.now().with(LocalTime.MIDNIGHT);

storage.getEntriesByQuery("type=\"SINGLE\" and created > " + localDateTime
+ " order by created", 0, MAX_COUNT_IN_BATCH)
.onSuccess(l -> processListAndSaveResult(l, storage))
.onFailure(e -> LOGGER.error("Failed to create print batch", e));
printStorage.getEntriesByQuery("type=\"SINGLE\" and created > " + localDateTime
+ " sortby sortingField created", 0, MAX_COUNT_IN_BATCH)
.onSuccess(l -> processListAndSaveResult(l, printStorage))
.onFailure(e -> LOGGER.error("Failed to create print batch", e));
ctx.response().setStatusCode(204);
ctx.response().end();
}

private void processListAndSaveResult(List<PrintEntry> entries, PrintStorage storage) {
Expand All @@ -65,7 +63,6 @@ private void processListAndSaveResult(List<PrintEntry> entries, PrintStorage sto

private void failureResponder(RoutingContext context) {
Throwable failure = context.failure();

if (failure != null) {
if (StringUtils.isNotBlank(failure.getMessage())) {
internalError(context.response(), failure.getMessage());
Expand Down
12 changes: 3 additions & 9 deletions src/main/java/org/folio/print/server/service/PrintService.java
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,10 @@ static PrintStorage createFromParams(Vertx vertx, RequestParameters params) {
RequestParameter tenantParameter = params.headerParameter(XOkapiHeaders.TENANT);
String tenant = tenantParameter.getString();

// get user Id
RequestParameter userIdParameter = params.headerParameter(XOkapiHeaders.USER_ID);
UUID currentUserId = null;
if (userIdParameter != null) {
currentUserId = UUID.fromString(userIdParameter.getString());
}

// get permissions which is required in OpenAPI spec
RequestParameter okapiPermissions = params.headerParameter(XOkapiHeaders.PERMISSIONS);
JsonArray permissions = new JsonArray(okapiPermissions.getString());
return new PrintStorage(vertx, tenant, currentUserId, permissions);
return new PrintStorage(vertx, tenant, permissions);
}

public static PrintStorage create(RoutingContext ctx) {
Expand Down Expand Up @@ -159,6 +152,7 @@ Future<Void> saveMail(RoutingContext ctx) {
entry.setId(UUID.randomUUID());
entry.setType(PrintEntryType.SINGLE);
entry.setCreated(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC));
entry.setSortingField(message.getTo());
entry.setContent(Hex.getString(PdfService.createPdfFile(message.getBody())));
return storage.createEntry(entry)
.map(entity -> {
Expand Down Expand Up @@ -226,7 +220,7 @@ public Future<Void> postInit(Vertx vertx, String tenant, JsonObject tenantAttrib
if (!tenantAttributes.containsKey("module_to")) {
return Future.succeededFuture(); // doing nothing for disable
}
PrintStorage storage = new PrintStorage(vertx, tenant, null, null);
PrintStorage storage = new PrintStorage(vertx, tenant, null);
return storage.init();
}

Expand Down
21 changes: 10 additions & 11 deletions src/main/java/org/folio/print/server/storage/PrintStorage.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,21 +50,17 @@ public class PrintStorage {

private final JsonArray permissions;

private final UUID currentUser;


/**
* Construct storage request for a user with given okapi permissions.
*
* @param vertx Vert.x handle
* @param tenant tenant
* @param currentUser UUID of user as it comes from X-Okapi-User-Id
* @param permissions permissions as it comes from X-Okapi-Permissions
*/
public PrintStorage(Vertx vertx, String tenant, UUID currentUser, JsonArray permissions) {
public PrintStorage(Vertx vertx, String tenant, JsonArray permissions) {
this.pool = TenantPgPool.pool(vertx, tenant);
this.permissions = permissions;
this.currentUser = currentUser;
this.printTable = pool.getSchema() + ".printing";
}

Expand All @@ -79,7 +75,8 @@ public Future<Void> init() {
+ "(id uuid NOT NULL PRIMARY KEY,"
+ " created TIMESTAMP NOT NULL,"
+ " type VARCHAR NOT NULL,"
+ " content JSONB NOT NULL"
+ " sorting_field VARCHAR NULL,"
+ " content VARCHAR NOT NULL"
+ ")"
));
}
Expand All @@ -100,6 +97,7 @@ PrintEntry fromRow(Row row) {
entry.setId(row.getUUID("id"));
entry.setCreated(row.getLocalDateTime("created").atZone(ZoneId.of(ZoneOffset.UTC.getId())));
entry.setType(PrintEntryType.valueOf(row.getString("type")));
entry.setSortingField(row.getString("sorting_field"));
entry.setContent(row.getString("content"));
return entry;
}
Expand All @@ -116,11 +114,11 @@ public Future<Void> createEntry(PrintEntry entry) {
}
return pool.preparedQuery(
"INSERT INTO " + printTable
+ " (id, created, type, content)"
+ " VALUES ($1, $2, $3, $4)"
+ " (id, created, type, sorting_field, content)"
+ " VALUES ($1, $2, $3, $4, $5)"
)
.execute(Tuple.of(entry.getId(), toLocalDateTime(entry.getCreated()),
entry.getType(), entry.getContent()))
entry.getType(), entry.getSortingField(), entry.getContent()))
.map(rowSet -> {
if (rowSet.rowCount() == 0) {
throw new ForbiddenException();
Expand Down Expand Up @@ -204,11 +202,11 @@ public Future<Void> updateEntry(PrintEntry entry) {
}
return pool.preparedQuery(
"UPDATE " + printTable
+ " SET created = $2, type = $3, content = $4"
+ " SET created = $2, type = $3, sorting_field = $4, content = $5"
+ " WHERE id = $1"
)
.execute(Tuple.of(entry.getId(), toLocalDateTime(entry.getCreated()),
entry.getType(), entry.getContent()))
entry.getType(), entry.getSortingField(), entry.getContent()))
.map(rowSet -> {
if (rowSet.rowCount() == 0) {
throw new NotFoundException();
Expand Down Expand Up @@ -342,6 +340,7 @@ private Pair<String, String> createSqlQuery(String cqlQuery, int offset, int lim
definition.addField("id", new PgCqlFieldUuid());
definition.addField("type", new PgCqlFieldText().withExact());
definition.addField("created", new PgCqlFieldTimestamp());
definition.addField("sortingField", new PgCqlFieldText().withColumn("sorting_field"));

PgCqlQuery pgCqlQuery = definition.parse(cqlQuery);
String sqlOrderBy = pgCqlQuery.getOrderByClause();
Expand Down
29 changes: 16 additions & 13 deletions src/main/resources/openapi/batchPrint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -158,27 +158,30 @@ paths:
- $ref: headers/okapi-user.yaml
post:
description: >
Create batch print entry for day.
X-Okapi-Permissions must include mod-batch-print.print.write and mod-batch-print.print.read
requestBody:
content:
application/json:
schema:
$ref: schemas/messageRequest.json
Send mail to create print entry.
X-Okapi-Permissions must include mod-batch-print.print.write
responses:
"200":
description: Batch created
content:
application/json:
schema:
$ref: schemas/messageRequest.json
description: Print entry created
"400":
$ref: "#/components/responses/trait_400"
"403":
$ref: "#/components/responses/trait_403"
"500":
$ref: "#/components/responses/trait_500"

/print/fake:
parameters:
- $ref: headers/okapi-permissions.yaml
- $ref: headers/okapi-tenant.yaml
- $ref: headers/okapi-token.yaml
- $ref: headers/okapi-url.yaml
- $ref: headers/okapi-user.yaml
post:
description: >
Fake endpoint for service to work
responses:
"200":
description: Fake
components:
responses:
trait_400:
Expand Down
15 changes: 0 additions & 15 deletions src/main/resources/openapi/examples/errors.sample

This file was deleted.

9 changes: 9 additions & 0 deletions src/main/resources/openapi/examples/mailMessage.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"notificationId": "123",
"from": "[email protected]",
"to": "[email protected]",
"outputFormat": "text/html",
"header": "okapi",
"body": "<div>Dear James</div><div><br></div><div>you were charged a Lost item fee</div><div>amount: 10.00</div><div><br></div><div>Owner: Test owner for cd1</div><div>Type: Lost item fee</div><div>Status: Cancelled item returned</div><div>Date: 1/4/24</div><div>Time: 1/4/24, 12:12 PM</div><div>Amount: 10.00</div><div>Remaining: 0.00</div><div>Info: </div>",
"attachments": []
}
4 changes: 4 additions & 0 deletions src/main/resources/openapi/schemas/entry.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
"type": "string",
"description": "Print entry type"
},
"sortingField": {
"type": "string",
"description": "Print entry sorting field"
},
"content": {
"type": "string",
"description": "Print entry content"
Expand Down
Loading

0 comments on commit 5395b97

Please sign in to comment.