demo-money-project/src/main/kotlin/com/example/demo/domain/MoneyExtension.kt

38 lines
1.3 KiB
Kotlin

package com.example.demo.domain
operator fun StdMoney.plus(other: StdMoney): StdMoney {
if (!this.getMoneyCurrency().equals(other.getMoneyCurrency(), ignoreCase = true)) {
throw IllegalStateException("money currency is not valid")
}
return Money(this.getMoneyValue().plus(other.getMoneyValue()), currency = Currency.create(this.getMoneyCurrency()))
}
fun StdMoney.addMoney(other: StdMoney): StdMoney {
if (this.getMoneyCurrency() == other.getMoneyCurrency()) {
return this + other
}
// this = USD
// other = KHR
// other (20000) -> this (5)
// exchange
val otherExchange = other.exchange(this.getMoneyCurrency())
return this + otherExchange
}
fun StdMoney.addMoney(value: Double, currency: String): StdMoney {
return this.addMoney(Money(value = value, currency = Currency.create(currency)))
}
fun StdMoney.exchange(toCurrency: String): StdMoney {
val rateFrom = MoneyConfig.getRate(this.getMoneyCurrency())
val rateTo = MoneyConfig.getRate(toCurrency)
val resultAmount = this.getMoneyValue() * ((1 / rateFrom) / (1 / rateTo))
return Money(value = resultAmount, currency = Currency.create(toCurrency))
}
fun StdMoney.toStdMoneyFormatable(): StdMoneyFormatable {
return this as StdMoneyFormatable
}