-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathCustomer.scala
More file actions
75 lines (53 loc) · 2.19 KB
/
Customer.scala
File metadata and controls
75 lines (53 loc) · 2.19 KB
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
package com.abc
import scala.collection.mutable.Map
case class Customer(val name: String, private var accounts: Map[String ,Account] = Map[String,Account]()) {
// Ideal would be to use the akka framework and create Customer, Account etc. as Actors instead of explicit synchronization...
def openAccount(account: Account): Customer = {
this.synchronized {
accounts += (account.accountNumber -> account)
}
this
}
def numberOfAccounts: Int = accounts.size
def totalInterestEarned: Double = accounts.mapValues { x => x.getInterestEarned }.values.sum
/**
* This method gets a statement
*/
def getStatement: String = {
val totalAcrossAllAccounts = accounts.mapValues(_.sumTransactions()).values.sum
//statement =
s"Statement for $name\n" +
accounts.values.map(statementForAccount).mkString("\n", "\n\n", "\n") +
s"\nTotal In All Accounts ${toDollars(totalAcrossAllAccounts)}"
}
/*
* Transfer money between 2 accounts for same customer
* returns a tuple of balance of fromAccount and 2 account
*/
def transfer(fromAccount : String , toAccount : String , transferAmount : Double) = {
val from = accounts.get(fromAccount)
val to = accounts.get(toAccount)
require ( from != None && to != None, " Invalid accounts numbers provided.")
require (transferAmount > 0 , " Transfer amount must be greater than 0")
require (from.get.sumTransactions() > transferAmount , "Insufficient Balance")
this.synchronized {
from.get.withdraw(transferAmount)
to.get.deposit(transferAmount)
(from.get.sumTransactions(), to.get.sumTransactions())
}
}
private def statementForAccount(a: Account): String = {
val accountType = a.accountType match {
case AccountType.CHECKING =>
"Checking Account\n"
case AccountType.SAVINGS =>
"Savings Account\n"
case AccountType.MAXI_SAVINGS =>
"Maxi Savings Account\n"
}
val transactionSummary = a.getTransactionSummary
val totalSummary = s"Total ${toDollars(a.sumTransactions())}"
accountType + transactionSummary + totalSummary
}
private def toDollars(number: Double): String = f"$$$number%.2f"
}