def program()

in src/main/scala/com/gu/invoicing/refundErroneousPayment/Program.scala [8:29]


  def program(input: RefundInput): RefundOutput = {
    val RefundInput(accountId, paymentDate, comment, _) = input
    val payments = getPayments(accountId, paymentDate)
    assert(payments.nonEmpty, s"No payments were taken on $paymentDate")
    val invoices = getInvoices(accountId)
    assert(invoices.nonEmpty, "No invoices for this account")
    val dateOfLatestInvoice = invoices.map(_.InvoiceDate).max
    val invoicesOnLatestDate = invoices.filter(_.InvoiceDate == dateOfLatestInvoice)
    val balancingInvoice = invoicesOnLatestDate.minBy(_.Amount)
    assert(
      balancingInvoice.InvoiceDate.isBefore(paymentDate),
      "Balancing invoice should have been created before the erroneous payment was taken",
    )
    assert(
      balancingInvoice.Amount == -payments.map(_.amount).sum,
      "Payments don't agree with balancing invoice",
    )
    transferToCreditBalance(balancingInvoice.InvoiceNumber, -balancingInvoice.Amount, comment)
    val results = payments.map(processRefund(comment))
    assert(getAccountBalance(accountId) == 0, "Account balance isn't settled")
    RefundOutput(accountId, results, balancingInvoice.InvoiceNumber)
  }