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
;;;;;;;;;; UTILS NS

(ns utils
  (:use clojure.pprint)
  (:import [java.text SimpleDateFormat]
           [java.util Date Calendar TimeZone GregorianCalendar]
           [org.joda.time DateTime Days]))

(defn days-between [date-a date-b]
  (.getDays (Days/daysBetween (DateTime. date-a) (DateTime. date-b))))


(defn time-zone [tz-string]
  (TimeZone/getTimeZone tz-string))

(defn sdf [sdf-pattern tz-string]
  (doto (SimpleDateFormat. sdf-pattern)
    (.setTimeZone (time-zone tz-string))))

(defn date-from-str [sdf-pattern string]
  (.parse (sdf sdf-pattern "UTC") string))


;;;;;;;;;; BANK NS

(ns bank
  (:use utils clojure.contrib.str-utils)
  (:import [java.util Date]))

(declare update-account print-account transaction-results)

;;;;;; bank related

(def BASE-OVERDRAFT-FEE 10)

(def MAX-OVERDRAWN-BALANCE -1000)

(def INTEREST-EVERY 6)

(def BONUS-EVERY 14)

(def overdraft-percentage-fee 
     {:checking     0.100
      :savings      0.075
      :money-market 0.050})

(defn interest-percentage [{type :type}]
  ({:checking 0.02 :savings 0.04 :money-market 0.06} type))

(defn years-since [start-date]
  (-> start-date (days-between (Date. (System/currentTimeMillis))) (/ 356) int))

(defn age-profile [{start-date :start-date}]
  (let [age (years-since start-date)]
    (cond 
     (<= age 2)                 :young-age
     (and (> age 2) (< age 5))  :middle-age
     (>= age 5)                 :old-age)))

(defn balance-profile [{:keys [balance] :as account}]
  (if (< balance 500) ::low-balance ::high-balance))

(defn bonus-profile [account]
  [(age-profile account) (balance-profile account)])

(defmulti bonus-percentage bonus-profile)

(defmethod bonus-percentage [:middle-age ::low-balance] [account]
  (/ (interest-percentage account) 32))

(defmethod bonus-percentage [:middle-age ::high-balance] [account]
  (/ (interest-percentage account) 24))

(defmethod bonus-percentage [:old-age ::low-balance] [account]
  (/ (interest-percentage account) 16))

(defmethod bonus-percentage [:old-age ::high-balance] [account]
  (/ (interest-percentage account) 8))

(defmethod bonus-percentage :default [_]
  0)

(defn new-bank 
  ([overdraft-balance accounts]
     {:overall-overdraft overdraft-balance :accounts accounts})
  ([]
     (new-bank 100000 {})))

(defn new-account [account-id account-type transactions balance start-date]
  {:id account-id :type account-type :transactions transactions :balance balance :start-date start-date})

(defn add-new-account [bank account-id account-type transactions balance start-date-string]
  (->> (new-account account-id account-type transactions balance (date-from-str "MM-dd-yyyy" start-date-string))
       (assoc (:accounts bank) account-id)
       (new-bank (:overall-overdraft bank))))

(defn process-transaction [{:keys [accounts] :as bank} {:keys [account-id] :as transaction}]
  (let [account-to-update (accounts account-id)
        [updated-overdraft updated-account] (transaction-results bank account-to-update transaction)]
    (new-bank updated-overdraft (assoc accounts account-id updated-account))))

(defn process-transactions [bank transactions]
  (reduce process-transaction bank transactions))

(defn print-bank [{:keys [overall-overdraft accounts]}]
  (println "************\nOVER-DRAFT:" overall-overdraft)
  (println "ACCOUNTS:\n----------")
  (doseq [a (vals accounts)] 
    (print-account a)))


;;;;;; accounts related

(defn account-overdraft-limit-reached? [new-balance]
  (< new-balance MAX-OVERDRAWN-BALANCE))

(defn withdrawal-scenario [{overall-overdraft :overall-overdraft} account transaction new-balance overdraft-amount]
  (cond
   (pos? new-balance)                                                     :no-overdraft
   (and (neg? new-balance) 
        (not (account-overdraft-limit-reached? new-balance))
        (> overall-overdraft overdraft-amount))                           :overdraft-available
   (and (neg? new-balance) 
        (account-overdraft-limit-reached? new-balance)
        (< overall-overdraft overdraft-amount))                           :overdraft-unavailable
   (and (neg? new-balance)
        (< new-balance MAX-OVERDRAWN-BALANCE))                            :overdraft-unavailable))

(defn deposit-scenario [bank {balance :balance} transaction new-balance]
  (cond
   (or (pos? balance) (zero? balance))     :no-repayment
   (neg? balance)                          :repayment))

(defmulti run-withdrawal withdrawal-scenario)

(defmethod run-withdrawal :no-overdraft [{:keys [overall-overdraft] :as bank} account transaction new-balance overdraft-amount]
  [new-balance overall-overdraft 0])

(defmethod run-withdrawal :overdraft-available [bank account transaction new-balance overdraft-amount]
  [new-balance (- (:overall-overdraft bank) overdraft-amount) (* overdraft-amount (overdraft-percentage-fee (:type account)))])

(defmethod run-withdrawal :overdraft-unavailable [bank account transaction new-balance overdraft-amount]
  [(:balance account) (:overall-overdraft bank) BASE-OVERDRAFT-FEE])

(defn repayment-amount [balance transaction-amount]
  (let [current-overdraw (Math/abs balance)]
    (if (and (neg? balance) (< current-overdraw transaction-amount)) current-overdraw transaction-amount)))

(defmulti run-deposit deposit-scenario)

(defmethod run-deposit :no-repayment [bank account transaction new-balance]
  [new-balance (:overall-overdraft bank)])

(defmethod run-deposit :repayment [bank account transaction new-balance]
  [new-balance (+ (:overall-overdraft bank) (repayment-amount (:balance account) (:amount transaction)))])

(defn n-transactions? [{transactions :transactions} n]
  (zero? (mod (count transactions) n)))

(defn ready-for-interest [account]
  (n-transactions? account INTEREST-EVERY))

(defn ready-for-bonus [account]
  (n-transactions? account BONUS-EVERY))

(defn compute-addition [{:keys [balance] :as account} percentage-fn]
  (+ balance (* balance (percentage-fn account))))

(defn compute-interest [account]
  (compute-addition account interest-percentage))

(defn compute-bonus [account]
  (compute-addition account bonus-percentage))

(defn process-addition [addition-predicate compute-addition-fn account]
  (if-not (and (pos? (:balance account)) (addition-predicate account))
    account
    (-> account
        (assoc :balance (compute-addition-fn account)))))

(defn process-interest [account]
  (process-addition ready-for-interest compute-interest account))

(defn process-bonus [account]
  (process-addition ready-for-bonus compute-bonus account))

(defn compute-new-balance [{:keys [balance]} {:keys [transaction-type amount]}]
  (condp = transaction-type
    :withdrawal (- balance amount)
    :deposit (+ balance amount)))

(defn update-account [{:keys [transactions] :as account} new-balance new-transaction]
  (-> account
      (assoc :balance new-balance)
      (assoc :transactions (conj transactions new-transaction))
      process-interest
      process-bonus))

(defn transaction-results [bank {:keys [balance transactions] :as account} {:keys [amount] :as transaction}]
  (let [new-balance (compute-new-balance account transaction)
        overdraft-amount (if (neg? balance) amount (- amount balance))]
    (condp = (:transaction-type transaction)
      :withdrawal (let [[new-balance new-overall overdraft-fee] (run-withdrawal bank account transaction new-balance overdraft-amount)]
                    [new-overall (update-account account (- new-balance overdraft-fee) transaction)])
      :deposit    (let [[new-balance new-overall] (run-deposit bank account transaction new-balance)]
                    [new-overall (update-account account new-balance transaction)]))))

(defn print-account [{:keys [id type transactions balance start-date] :as account}]
  (println "Account ID:" id type "Age:" (years-since start-date))
  (println "Balance:" balance)
  (println "Transactions" (count transactions) "->")
  (println (str-join "\n" transactions))
  (println "----------------"))



;;;;;;;;;; TRANSACTIONS NS

(ns transactions)

(defn random-amount []
  (let [r (* 10 (rand-int 50))]
    (if (> r 100) r (random-amount))))

(defn random-amounts []
  (lazy-seq 
   (cons (random-amount) (random-amounts))))

(defn random-txn-type []
  (let [r (rand-int 10)]
    (if (odd? r) :withdrawal :deposit)))

(defn random-txn-types []
  (lazy-seq 
   (cons (random-txn-type) (random-txn-types))))

(defn random-account-id [accounts]
  (:id (accounts (nth (keys accounts) (rand-int (count accounts))))))

(defn random-account-ids [accounts]
  (lazy-seq
   (cons (random-account-id accounts) (random-account-ids accounts))))

(defn bank-transaction [transaction-id account-id txn-type amount]
  {:transaction-id transaction-id :account-id account-id :transaction-type txn-type :amount amount})

(defn random-transactions [accounts]
  (map bank-transaction (iterate inc 1) (random-account-ids accounts) (random-txn-types) (random-amounts)))



;;;;;;;;;; TEST-DATA NS

(ns test-data
  (:use bank transactions))

(def STARTING-BALANCE 500)

(def BANK (-> (new-bank 1000 {})
           (add-new-account 1 :checking     [] STARTING-BALANCE "01-01-2009")
           (add-new-account 2 :savings      [] STARTING-BALANCE "02-01-2008")
           (add-new-account 3 :money-market [] STARTING-BALANCE "03-01-2009")
           (add-new-account 4 :checking     [] STARTING-BALANCE "04-01-2009")
           (add-new-account 5 :savings      [] STARTING-BALANCE "05-01-2009")
           (add-new-account 6 :money-market [] STARTING-BALANCE "06-01-2009")))

(def RAND-TX (take 10 (random-transactions (:accounts B))))


;;;;;;;;;;;; RUNNING:

(print-bank (process-transactions BANK RAND-TX))