summaryrefslogtreecommitdiff
path: root/nexus/src/main/kotlin/tech/libeufin/nexus/Iso20022.kt
blob: e9a9efcc47287df1536fd8917caa754ecc82f253 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
 * This file is part of LibEuFin.
 * Copyright (C) 2024 Taler Systems S.A.

 * LibEuFin is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation; either version 3, or
 * (at your option) any later version.

 * LibEuFin is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
 * Public License for more details.

 * You should have received a copy of the GNU Affero General Public
 * License along with LibEuFin; see the file COPYING.  If not, see
 * <http://www.gnu.org/licenses/>
 */
package tech.libeufin.nexus

import tech.libeufin.common.*
import tech.libeufin.ebics.iso20022.*
import tech.libeufin.ebics.*
import java.net.URLEncoder
import java.time.*
import java.time.format.DateTimeFormatter
import com.gitlab.mvysny.konsumexml.*


/**
 * Collects details to define the pain.001 namespace
 * XML attributes.
 */
data class Pain001Namespaces(
    val fullNamespace: String,
    val xsdFilename: String
)

/**
 * Gets the amount number, also converting it from the
 * Taler-friendly 8 fractional digits to the more bank
 * friendly with 2.
 *
 * @param amount the Taler amount where to extract the number
 * @return [String] of the amount number without the currency.
 */
fun getAmountNoCurrency(amount: TalerAmount): String {
    if (amount.frac == 0) {
        return amount.value.toString()
    } else {
        val fractionFormat = amount.frac.toString().padStart(8, '0').dropLastWhile { it == '0' }
        if (fractionFormat.length > 2) throw Exception("Sub-cent amounts not supported")
        return "${amount.value}.${fractionFormat}"
    }
}

/**
 * Create a pain.001 document.  It requires the debtor BIC.
 *
 * @param requestUid UID of this request, helps to make this request idempotent.
 * @param initiationTimestamp timestamp when the payment was initiated in the database.
 *                            Although this is NOT the pain.001 creation timestamp, it
 *                            will help making idempotent requests where one MsgId is
 *                            always associated with one, and only one creation timestamp.
 * @param debtorAccount [IbanPayto] bank account information of the EBICS subscriber that
 *                           sends this request.  It's expected to contain IBAN, BIC, and NAME.
 * @param amount amount to pay.  The caller is responsible for sanity-checking this
 *               value to match the bank expectation.  For example, that the decimal
 *               part formats always to at most two digits.
 * @param wireTransferSubject wire transfer subject.
 * @param creditAccount payment receiver in [IbanPayto].  It should contain IBAN and NAME.
 * @return raw pain.001 XML, or throws if the debtor BIC is not found.
 */
fun createPain001(
    requestUid: String,
    initiationTimestamp: Instant,
    debitAccount: IbanAccountMetadata,
    amount: TalerAmount,
    wireTransferSubject: String,
    creditAccount: FullIbanPayto
): String {
    val namespace = Pain001Namespaces(
        fullNamespace = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.09",
        xsdFilename = "pain.001.001.09.ch.03.xsd"
    )
    val zonedTimestamp = ZonedDateTime.ofInstant(initiationTimestamp, ZoneId.of("UTC"))
    val amountWithoutCurrency: String = getAmountNoCurrency(amount)
    return constructXml {
        root("Document") {
            attribute(
                "xmlns",
                namespace.fullNamespace
            )
            attribute(
                "xmlns:xsi",
                "http://www.w3.org/2001/XMLSchema-instance"
            )
            attribute(
                "xsi:schemaLocation",
                "${namespace.fullNamespace} ${namespace.xsdFilename}"
            )
            element("CstmrCdtTrfInitn") {
                element("GrpHdr") {
                    element("MsgId") {
                        text(requestUid)
                    }
                    element("CreDtTm") {
                        val dateFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME
                        text(dateFormatter.format(zonedTimestamp))
                    }
                    element("NbOfTxs") {
                        text("1")
                    }
                    element("CtrlSum") {
                        text(amountWithoutCurrency)
                    }
                    element("InitgPty/Nm") {
                        text(debitAccount.name)
                    }
                }
                element("PmtInf") {
                    element("PmtInfId") {
                        text("NOTPROVIDED")
                    }
                    element("PmtMtd") {
                        text("TRF")
                    }
                    element("BtchBookg") {
                        text("false")
                    }
                    element("ReqdExctnDt") {
                        element("Dt") {
                            text(DateTimeFormatter.ISO_DATE.format(zonedTimestamp))
                        }
                    }
                    element("Dbtr/Nm") {
                        text(debitAccount.name)
                    }
                    element("DbtrAcct/Id/IBAN") {
                        text(debitAccount.iban)
                    }
                    element("DbtrAgt/FinInstnId/BICFI") {
                        text(debitAccount.bic)
                    }
                    element("CdtTrfTxInf") {
                        element("PmtId") {
                            element("InstrId") { text("NOTPROVIDED") }
                            element("EndToEndId") { text("NOTPROVIDED") }
                        }
                        element("Amt/InstdAmt") {
                            attribute("Ccy", amount.currency)
                            text(amountWithoutCurrency)
                        }
                        element("Cdtr/Nm") {
                            text(creditAccount.receiverName)
                        }
                        element("CdtrAcct/Id/IBAN") {
                            text(creditAccount.payto.iban)
                        }
                        element("RmtInf/Ustrd") {
                            text(wireTransferSubject)
                        }
                    }
                }
            }
        }
    }
}

data class CustomerAck(
    val actionType: String,
    val code: ExternalStatusReason1Code?,
    val timestamp: Instant
) {
    override fun toString(): String {
        return if (code != null)
            "${timestamp.fmtDateTime()} ${actionType} ${code.isoCode} '${code.description}'"
        else 
            "${timestamp.fmtDateTime()} ${actionType}"
    }
}

/**
 * Extract logs from a pain.002 HAC document.
 *
 * @param xml pain.002 input document
 */
fun parseCustomerAck(xml: String): List<CustomerAck> {
    val doc = xml.konsumeXml().use { 
        it.child("Document") {
            logger.debug("HAC ${name.namespaceURI}")
            pain_002_001_13.parse(this) 
        }
    }
    return doc.CstmrPmtStsRpt.OrgnlPmtInfAndSts.map {
        val actionType = it.OrgnlPmtInfId
        val code = it.StsRsnInf[0].Rsn?.let {
            when (it) {
                is StatusReason6Choice.Cd -> it.value
                is StatusReason6Choice.Prtry -> null // TODO handle proprietary code
            }
        }
        var timestamp: Instant? = null;
        (it.StsRsnInf[0].Orgtr!!.Id!! as Party38Choice.OrgId).value.Othr.map {
            val id = (it.SchmeNm!! as OrganisationIdentificationSchemeName1Choice.Prtry).value
            if (id == "TimeStamp") {
                timestamp = parseCamtTime(it.Id.trimEnd('Z'))
            }
        }
        CustomerAck(actionType, code, timestamp!!)
    }
}

data class TransactionStatus(
    val status: ExternalPaymentTransactionStatus1Code,
    val reasons: List<Reason>
)

data class PaymentStatus(
    val msgId: String,
    val status: ExternalPaymentGroupStatus1Code,
    val reasons: List<Reason>,
    val txs: TransactionStatus?,
) {
    override fun toString(): String {
        val builder = StringBuilder("'${msgId}' - ")
        if (txs != null) {
            builder.append("${txs.status.isoCode} '${txs.status.description}'")
            for (reason in txs.reasons) {
                builder.append(" - ${reason.code.isoCode} '${reason.code.description}'")
            }
        } else {
            builder.append("${status.isoCode} '${status.description}'")
            for (reason in reasons) {
                builder.append(" - ${reason.code.isoCode} '${reason.code.description}'")
            }
        }
        return builder.toString()
    }
}

data class Reason (
    val code: ExternalStatusReason1Code,
    val information: String
)

/**
 * Extract payment status from a pain.002 document.
 *
 * @param xml pain.002 input document
 */
fun parseCustomerPaymentStatusReport(xml: String): PaymentStatus {
    fun StatusReasonInformation12.reason(): Reason {
        val code = Rsn?.let { it ->
            when (it) {
                is StatusReason6Choice.Cd -> it.value
                is StatusReason6Choice.Prtry -> null // TODO handle proprietary code
            }
        }
        return Reason(code!!, AddtlInf.joinToString("\n"))
    }

    val doc = xml.konsumeXml().use { 
        it.child("Document") {
            logger.debug("payment status ${name.namespaceURI}")
            pain_002_001_13.parse(this) 
        }
    }
    val msgId = doc.CstmrPmtStsRpt.OrgnlGrpInfAndSts.OrgnlMsgId
    val msgCode = doc.CstmrPmtStsRpt.OrgnlGrpInfAndSts.GrpSts
    val msgReasons = doc.CstmrPmtStsRpt.OrgnlGrpInfAndSts.StsRsnInf.map { it.reason() }
    require(doc.CstmrPmtStsRpt.OrgnlPmtInfAndSts.size <= 1) // TODO will we handle batch status latter
    val paymentInfo = doc.CstmrPmtStsRpt.OrgnlPmtInfAndSts.firstOrNull()?.run {
        val code = PmtInfSts!!
        val reasons = StsRsnInf.map { it.reason() }
        require(doc.CstmrPmtStsRpt.OrgnlPmtInfAndSts.size <= 1) // TODO will we handle batch status latter
        val transactionInfo = TxInfAndSts.firstOrNull()?.run {
            val code = TxSts!!
            val reasons = StsRsnInf.map { it.reason() }
            TransactionStatus(code, reasons)
        }
        Triple(code, reasons, transactionInfo)
    }

    // TODO handle multi level code better 
    return if (paymentInfo != null) {
        val (code, reasons, transactionInfo) = paymentInfo
        PaymentStatus(msgId, code, reasons, transactionInfo)
    } else {
        PaymentStatus(msgId, msgCode!!, msgReasons, null)
    }
}

fun ActiveOrHistoricCurrencyAndAmount.talerAmount(acceptedCurrency: String): TalerAmount {
    /**
     * FIXME: test by sending non-CHF to PoFi and see which currency gets here.
     */
    if (Ccy != acceptedCurrency) throw Exception("Currency $Ccy not supported")
    return TalerAmount("$Ccy:$value")
}

/**
 * Searches payments in a camt.054 (Detailavisierung) document.
 *
 * @param notifXml camt.054 input document
 * @param acceptedCurrency currency accepted by Nexus
 * @param incoming list of incoming payments
 * @param outgoing list of outgoing payments
 */
fun parseTxNotif(
    notifXml: String,
    acceptedCurrency: String,
    incoming: MutableList<IncomingPayment>,
    outgoing: MutableList<OutgoingPayment>
) {
    val doc = notifXml.konsumeXml().use { 
        it.child("Document") {
            val schema = name.namespaceURI.removePrefix("urn:iso:std:iso:20022:tech:xsd:")
            when (schema) {
                "camt.054.001.08" -> camt_054_001_08.parse(this)
                "camt.054.001.04" -> camt_054_001_04.parse(this)
                else -> throw Exception("Unsupported camt.054 schema $schema")
            }
        }
    }
    // TODO document null assertion of throw erro with human friendly message
    when (doc) {
        is camt_054_001_08 -> {
            for (notification in doc.BkToCstmrDbtCdtNtfctn.Ntfctn) {
                for (entry in notification.Ntry) {
                    require(ExternalEntryStatus1Code.BOOK == (entry.Sts as EntryStatus1Choice.Cd).value)
                    val rawDate = entry.BookgDt!! // Not null as BOOK
                    val bookDate = when(rawDate) {
                        is DateAndDateTime2Choice.Dt -> rawDate.value.atStartOfDay().toInstant(ZoneOffset.UTC)
                        is DateAndDateTime2Choice.DtTm -> rawDate.value.toInstant(ZoneOffset.UTC)
                    }
                    if (entry.RvslInd ?: false) {
                        logger.error("Reversal transaction")
                        break;
                    }
                    for (batch in entry.NtryDtls) {
                        for (tx in batch.TxDtls) {
                            val amount = tx.Amt!!.talerAmount(acceptedCurrency)
                            
                            when (tx.CdtDbtInd!!) {
                                CreditDebitCode.CRDT -> {
                                    val bankId = tx.Refs!!.AcctSvcrRef!!
                                    // Obtaining payment subject. 
                                    val subject = tx.RmtInf?.let {it.Ustrd.joinToString("") }
                                    if (subject == null) {
                                        logger.error("No subject")
                                        break;
                                    }
                    
                                    // Obtaining the payer's details
                                    val iban = (tx.RltdPties!!.DbtrAcct!!.Id as AccountIdentification4Choice.IBAN).value
                                    val debtorPayto = StringBuilder("payto://iban/$iban")
                                    val debitor = tx.RltdPties!!.Dbtr
                                    if (debitor != null) {
                                        val name = (debitor as Party40Choice.Pty).value.Nm
                                        if (name != null) {
                                            val urlEncName = URLEncoder.encode(name, "utf-8")
                                            debtorPayto.append("?receiver-name=$urlEncName")
                                        }
                                    }

                                    incoming.add(
                                        IncomingPayment(
                                            amount = amount,
                                            bankId = bankId,
                                            debitPaytoUri = debtorPayto.toString(),
                                            executionTime = bookDate,
                                            wireTransferSubject = subject
                                        )
                                    )
                                }
                                CreditDebitCode.DBIT -> {
                                    val messageId = tx.Refs!!.MsgId!!
                                    outgoing.add(
                                        OutgoingPayment(
                                            amount = amount,
                                            messageId = messageId,
                                            executionTime = bookDate
                                        )
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
        is camt_054_001_04 -> {
            for (notification in doc.BkToCstmrDbtCdtNtfctn.Ntfctn) {
                for (entry in notification.Ntry) {
                    assert(entry.Sts == EntryStatus2Code.BOOK)
                    val rawDate = entry.BookgDt!! // Not null as BOOK
                    val bookDate = when(rawDate) {
                        is DateAndDateTimeChoice.Dt -> rawDate.value.atStartOfDay().toInstant(ZoneOffset.UTC)
                        is DateAndDateTimeChoice.DtTm -> rawDate.value.toInstant(ZoneOffset.UTC)
                    }
                    if (entry.RvslInd ?: false) {
                        logger.error("Reversal transaction")
                        break;
                    }
                    for (batch in entry.NtryDtls) {
                        for (tx in batch.TxDtls) {
                            val amount = tx.Amt!!.talerAmount(acceptedCurrency)
                            
                            when (tx.CdtDbtInd!!) {
                                CreditDebitCode.CRDT -> {
                                    val bankId = tx.Refs!!.AcctSvcrRef!!
                                    // Obtaining payment subject. 
                                    val subject = tx.RmtInf?.let {it.Ustrd.joinToString("") }
                                    if (subject == null) {
                                        logger.error("No subject")
                                        break;
                                    }
                    
                                    // Obtaining the payer's details
                                    val iban = (tx.RltdPties!!.DbtrAcct!!.Id as AccountIdentification4Choice.IBAN).value
                                    val debtorPayto = StringBuilder("payto://iban/$iban")
                                    val debitor = tx.RltdPties!!.Dbtr
                                    if (debitor != null) {
                                        val name = debitor.Nm
                                        if (name != null) {
                                            val urlEncName = URLEncoder.encode(name, "utf-8")
                                            debtorPayto.append("?receiver-name=$urlEncName")
                                        }
                                    }
                                    
                                    incoming.add(
                                        IncomingPayment(
                                            amount = amount,
                                            bankId = bankId,
                                            debitPaytoUri = debtorPayto.toString(),
                                            executionTime = bookDate,
                                            wireTransferSubject = subject
                                        )
                                    )
                                }
                                CreditDebitCode.DBIT -> {
                                    val messageId = tx.Refs!!.MsgId!!
                                    outgoing.add(
                                        OutgoingPayment(
                                            amount = amount,
                                            messageId = messageId,
                                            executionTime = bookDate
                                        )
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
        else -> throw Exception("Unexpected camt.054 document ${doc::class.simpleName}")
    }
}