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
|
package tech.libeufin.sandbox
import io.ktor.http.*
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.transactions.experimental.suspendedTransactionAsync
import org.jetbrains.exposed.sql.transactions.transaction
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import tech.libeufin.util.*
import java.math.BigDecimal
private val logger: Logger = LoggerFactory.getLogger("tech.libeufin.sandbox")
fun getAccountFromLabel(accountLabel: String): BankAccountEntity {
return transaction {
val account = BankAccountEntity.find {
BankAccountsTable.label eq accountLabel
}.firstOrNull()
if (account == null) throw SandboxError(
HttpStatusCode.NotFound, "Account '$accountLabel' not found"
)
account
}
}
// Mainly useful inside the CAMT generator.
fun balanceForAccount(
history: MutableList<RawPayment>,
baseBalance: BigDecimal
): BigDecimal {
var ret = baseBalance
history.forEach direction@ {
if (it.direction == "CRDT") {
val amount = parseDecimal(it.amount)
ret += amount
return@direction
}
if (it.direction == "DBIT") {
val amount = parseDecimal(it.amount)
ret -= amount
return@direction
}
throw SandboxError(
HttpStatusCode.InternalServerError,
"A payment direction was found neither CRDT nor DBIT",
LibeufinErrorCode.LIBEUFIN_EC_INVALID_STATE
)
}
return ret
}
fun balanceForAccount(bankAccount: BankAccountEntity): BigDecimal {
var balance = BigDecimal.ZERO
transaction {
BankAccountTransactionEntity.find {
BankAccountTransactionsTable.direction eq "CRDT" and (
BankAccountTransactionsTable.account eq bankAccount.id)
}.forEach {
val amount = parseDecimal(it.amount)
balance += amount
}
BankAccountTransactionEntity.find {
BankAccountTransactionsTable.direction eq "DBIT" and (
BankAccountTransactionsTable.account eq bankAccount.id)
}.forEach {
val amount = parseDecimal(it.amount)
balance -= amount
}
}
/**
* FIXME: for negative accounts, temporarily return 0, so as to make
* the current CAMT generator happy. Negative amounts need to have their
* onw sub-tree in the report, see bug: #6962
*/
if (balance < BigDecimal.ZERO) return BigDecimal.ZERO
return balance
}
// For now, returns everything.
fun historyForAccount(bankAccount: BankAccountEntity): MutableList<RawPayment> {
val history = mutableListOf<RawPayment>()
transaction {
/**
FIXME: add the following condition too:
and (BankAccountTransactionsTable.date.between(start.millis, end.millis))
*/
/**
FIXME: add the following condition too:
and (BankAccountTransactionsTable.date.between(start.millis, end.millis))
*/
BankAccountTransactionEntity.find {
BankAccountTransactionsTable.account eq bankAccount.id
}.forEach {
history.add(
RawPayment(
subject = it.subject,
creditorIban = it.creditorIban,
creditorBic = it.creditorBic,
creditorName = it.creditorName,
debtorIban = it.debtorIban,
debtorBic = it.debtorBic,
debtorName = it.debtorName,
date = importDateFromMillis(it.date).toDashedDate(),
amount = it.amount,
currency = it.currency,
// The line below produces a value too long (>35 chars),
// and it makes the document invalid!
// uid = "${it.pmtInfId}-${it.msgId}"
uid = it.accountServicerReference,
direction = it.direction,
pmtInfId = it.pmtInfId
)
)
}
}
return history
}
/**
* https://github.com/JetBrains/Exposed/wiki/Transactions#working-with-coroutines
* https://medium.com/androiddevelopers/threading-models-in-coroutines-and-android-sqlite-api-6cab11f7eb90
*/
fun wireTransfer(
debitAccount: String, creditAccount: String,
amount: String, subjectArg: String
) {
transaction {
// check accounts exist
val credit = BankAccountEntity.find {
BankAccountsTable.label eq creditAccount
}.firstOrNull() ?: run {
throw SandboxError(HttpStatusCode.NotFound, "Credit account: $creditAccount, not found")
}
val debit = BankAccountEntity.find {
BankAccountsTable.label eq debitAccount
}.firstOrNull() ?: run {
throw SandboxError(HttpStatusCode.NotFound, "Debit account: $debitAccount, not found")
}
if (credit.currency != debit.currency) {
throw SandboxError(HttpStatusCode.InternalServerError,
"Sandbox has inconsistent state: " +
"currency of credit (${credit.currency}) and debit (${debit.currency}) account differs."
)
}
val amountObj = try {
parseAmount(amount)
} catch (e: Exception) {
throw SandboxError(HttpStatusCode.BadRequest, "Amount given not valid: $amount")
}
// Extra check on the currency's consistency
if (credit.currency != debit.currency) throw SandboxError(
HttpStatusCode.InternalServerError,
"Credit and debit account have different currency (${credit.currency} vs ${debit.currency})!",
LibeufinErrorCode.LIBEUFIN_EC_CURRENCY_INCONSISTENT
)
if (amountObj.currency != credit.currency || amountObj.currency != debit.currency) {
throw SandboxError(
HttpStatusCode.BadRequest,
"Currency (${amountObj.currency}) is not supported",
LibeufinErrorCode.LIBEUFIN_EC_BAD_CURRENCY
)
}
val randId = getRandomString(16)
BankAccountTransactionEntity.new {
creditorIban = credit.iban
creditorBic = credit.bic
creditorName = credit.name
debtorIban = debit.iban
debtorBic = debit.bic
debtorName = debit.name
subject = subjectArg
this.amount = amountObj.amount.toString()
currency = amountObj.currency
date = getUTCnow().toInstant().toEpochMilli()
accountServicerReference = "sandbox-$randId"
account = debit
direction = "DBIT"
}
BankAccountTransactionEntity.new {
creditorIban = credit.iban
creditorBic = credit.bic
creditorName = credit.name
debtorIban = debit.iban
debtorBic = debit.bic
debtorName = debit.name
subject = subjectArg
this.amount = amountObj.amount.toString()
currency = amountObj.currency
date = getUTCnow().toInstant().toEpochMilli()
accountServicerReference = "sandbox-$randId"
account = credit
direction = "CRDT"
}
}
}
|