// Typed Inputs and Outputs belong to process.json. execute(input) database = service "database_sales" customer = database.first({ from: "Customer (id, name, email)", where: { id: input.customerId, deleted: false } }) if customer == null fail NotFound "Customer not found" end lines = priceLines(input.lines, input.decimalPlaces) totals = calculateTotals(lines, input.taxRate, input.decimalPlaces) issuedOn = Dates.today(input.timezone) expiresOn = Dates.add(issuedOn, input.validDays, "days") quotation = saveQuotation(database, customer.id, lines, totals, issuedOn, expiresOn) // Copy data only; do not announce that the transaction has committed. receipt = { email: customer.email, reference: input.reference } async sendReceipt(receipt) end return { quotationId: quotation.id, lines: lines, totals: totals, expiresOn: expiresOn } end priceLines(items, places) lines = [] for each item in items if item.quantity <= 0 or item.unitPrice < 0 fail InvalidInput "Quantity must be positive and price cannot be negative" end lines.add({ description: item.description, quantity: item.quantity, unitPrice: item.unitPrice, total: round(item.quantity * item.unitPrice, places, "half-up") }) end return lines end calculateTotals(lines, rate, places) subtotal = sum line.total for each line in lines tax = round(subtotal * rate, places, "half-up") return { subtotal: subtotal, tax: tax, total: subtotal + tax } end saveQuotation(database, customerId, lines, totals, issuedOn, expiresOn) quotation = database.create("Quotation") quotation.customer = { id: customerId } quotation.lines = lines quotation.totals = totals quotation.issuedOn = issuedOn quotation.expiresOn = expiresOn quotation.status = "draft" quotation.save() return quotation end sendReceipt(receipt) notifications = service "smtp_notifications" content = "We received request " + receipt.reference message = notifications.create("Request Received", content, "text/plain") message.send([{ scope: "to", email: receipt.email }]) end