1 ! Copyright (C) 2008 Alex Chapman
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors calendar kernel math math.order money sequences ;
6 TUPLE: account name interest-rate interest-payment-day opening-date transactions unpaid-interest interest-last-paid ;
8 : <account> ( name interest-rate interest-payment-day opening-date -- account )
9 V{ } clone 0 pick account boa ;
11 TUPLE: transaction date amount description ;
12 C: <transaction> transaction
14 : >>transaction ( account transaction -- account )
15 over transactions>> push ;
17 : total ( transactions -- balance )
18 0 [ amount>> + ] reduce ;
20 : balance>> ( account -- balance ) transactions>> total ;
22 : open-account ( name interest-rate interest-payment-day opening-date opening-balance -- account )
23 [ [ <account> ] keep ] dip "Account Opened" <transaction> >>transaction ;
25 : daily-rate ( yearly-rate day -- daily-rate )
28 : daily-rate>> ( account date -- rate )
29 [ interest-rate>> ] dip daily-rate ;
31 : transactions-on-date ( account date -- transactions )
32 [ before? ] curry filter ;
34 : balance-on-date ( account date -- balance )
35 transactions-on-date total ;
37 : pay-interest ( account date -- )
38 over unpaid-interest>> "Interest Credit" <transaction>
39 >>transaction 0 >>unpaid-interest drop ;
41 : interest-payment-day? ( account date -- ? )
42 day>> swap interest-payment-day>> = ;
44 : ?pay-interest ( account date -- )
45 2dup interest-payment-day? [ pay-interest ] [ 2drop ] if ;
47 : unpaid-interest+ ( account amount -- account )
48 over unpaid-interest>> + >>unpaid-interest ;
50 : accumulate-interest ( account date -- )
51 [ dupd daily-rate>> over balance>> * unpaid-interest+ ] keep
52 >>interest-last-paid drop ;
54 : process-day ( account date -- )
55 2dup accumulate-interest ?pay-interest ;
57 : each-day ( quot start end -- )
59 [ dup [ over [ swap call ] dip ] dip 1 days time+ ] dip each-day
64 : process-to-date ( account date -- account )
65 over interest-last-paid>> 1 days time+
66 [ dupd process-day ] spin each-day ;
68 : inserting-transactions ( account transactions -- account )
69 [ [ date>> process-to-date ] keep >>transaction ] each ;