Skip to content

Commit

Permalink
Merge pull request open-runtimes#123 from sahalsaad/feat-generate-inv…
Browse files Browse the repository at this point in the history
…oice-java

Add generate_invoice example for java
  • Loading branch information
Meldiron committed Jan 23, 2023
2 parents c6ed743 + 16ed32d commit 3aaa6fa
Show file tree
Hide file tree
Showing 3 changed files with 189 additions and 0 deletions.
116 changes: 116 additions & 0 deletions java/generate_invoice/Index.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import com.google.gson.Gson;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.VerticalPositionMark;

import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.List;

final Gson gson = new Gson();

public RuntimeResponse main(RuntimeRequest req, RuntimeResponse res) {
String payloadString = req.getPayload();
Map<String, Object> payload = gson.fromJson(payloadString, Map.class);
Map<String, Object> responseData = new HashMap<>();

try {
String currency = Objects.toString(payload.get("currency"), "");
List<Map<String, Object>> items = (List<Map<String, Object>>)(List<?>) payload.get("items");
String issuer = Objects.toString(payload.get("issuer"), "");
String customer = Objects.toString(payload.get("customer"), "");
Number vat = (Number) payload.get("vat");

List<String> errorFields = validatePayload(currency, items, issuer, customer, vat);
if (!errorFields.isEmpty()) {
throw new NoSuchFieldException("Please provide " + String.join(", ", errorFields));
}

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document doc = new Document();
PdfWriter writer = PdfWriter.getInstance(doc, baos);

doc.open();
Font font = new Font(Font.FontFamily.TIMES_ROMAN, 26, Font.BOLD | Font.UNDERLINE);
Paragraph invoice = new Paragraph("Invoice", font);
invoice.setAlignment(Element.ALIGN_CENTER);
doc.add(invoice);

font.setSize(12);
font.setStyle(Font.NORMAL);
doc.add(new Paragraph(50));
doc.add(new Paragraph("Issuer: " + issuer, font));
doc.add(new Paragraph("Customer: " + customer, font));
doc.add(new Paragraph("Currency: " + currency, font));
doc.add(new Paragraph("VAT: " + vat, font));

Chunk glue = new Chunk(new VerticalPositionMark());
Chunk rightChunk = new Chunk(glue);

font.setStyle(Font.BOLD);
Paragraph itemHeader = new Paragraph(50, "Item", font);
itemHeader.add(rightChunk);
itemHeader.add("Price");
doc.add(itemHeader);

font.setStyle(Font.NORMAL);
double total = 0;
for (Map<String, Object> item : items) {
String name = item.get("name").toString();
double price = (double) item.get("price");

total += price;
Paragraph itemParagraph = new Paragraph(name, font);
itemParagraph.add(rightChunk);
itemParagraph.add(String.valueOf(price));
doc.add(itemParagraph);
}

font.setStyle(Font.UNDERLINE | Font.BOLD);
font.setSize(15);
Paragraph totalParagraph = new Paragraph(20, "Total:", font);
totalParagraph.add(rightChunk);
totalParagraph.add(String.valueOf(total));
doc.add(totalParagraph);
doc.close();
writer.close();

String base64String = Base64.getEncoder().encodeToString(baos.toByteArray());

responseData.put("success", true);
responseData.put("invoice", base64String);

return res.json(responseData);
} catch (DocumentException | NoSuchFieldException exception) {
responseData.put("success", false);
responseData.put("message", exception.getMessage());
return res.json(responseData);
}
}

private List<String> validatePayload(String currency, List<Map<String, Object>> items, String issuer, String customer, Number vat) {

List<String> errors = new ArrayList<>();

if (currency.isEmpty()) {
errors.add("currency");
}

if (items == null || items.isEmpty()) {
errors.add("items");
}

if (issuer.isEmpty()) {
errors.add("issuer");
}

if (customer.isEmpty()) {
errors.add("customer");
}

if (vat == null) {
errors.add("vat");
}

return errors;
}
69 changes: 69 additions & 0 deletions java/generate_invoice/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# 💻 Generate invoice

A Java Cloud Function for generating invoice.

```json
{
"currency":"EUR",
"items":[{"name":"Web development","price":15}],
"issuer":"Some\nIssuer",
"customer":"Some\nCustomer",
"vat":21
}
```

_Example output:_


```json
{
"success":true,
"invoice":"iVBORw0KGgoAAAANSUhEUgAAAaQAAALiCAY...QoH9hbkTPQAAAABJRU5ErkJggg=="
}
```

_Error Example output:_

```json
{
"success": false,
"message":"Please provide currency"
}
```


## 📝 Environment Variables

This function does not require any variables.

## 🚀 Deployment

1. Clone this repository, and enter this function folder:

```
$ git clone https://github.com/open-runtimes/examples.git && cd examples
$ cd java/generate_invoice
```

2. Enter this function folder and build the code:
```
docker run -e INTERNAL_RUNTIME_ENTRYPOINT=Index.java --rm --interactive --tty --volume $PWD:/usr/code openruntimes/java:v2-18.0 sh /usr/local/src/build.sh
```
As a result, a `code.tar.gz` file will be generated.

3. Start the Open Runtime:
```
docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/java:v2-18.0 sh /usr/local/src/start.sh
```

Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Java runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/java-18.0).

4. Execute function:

```
curl http:https://localhost:3000/ -d '{"payload":"{\"currency\":\"EUR\",\"items\":[{\"name\":\"Web development\",\"price\":15}],\"issuer\":\"Some\nIssuer\",\"customer\":\"Some\nCustomer\",\"vat\":21}"}' -H "X-Internal-Challenge: secret-key" -H "Content-Type: application/json"
```

## 📝 Notes
- This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions).
- This example is compatible with Java 18.0. Other versions may work but are not guarenteed to work as they haven't been tested.
4 changes: 4 additions & 0 deletions java/generate_invoice/deps.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dependencies {
implementation 'com.google.code.gson:gson:2.9.0'
implementation 'com.itextpdf:itextpdf:5.5.13.3'
}

0 comments on commit 3aaa6fa

Please sign in to comment.