1 """
2 MoinMoin - Sum Macro
3
4 Copyright (c) 2003 by Michael Schuerig <schuerig@acm.org>
5 All rights reserved, see COPYING for details.
6
7 Sum and convert money amounts.
8 Usage:
9 [[Sum(amount)]] # Add amount in the base currency
10 [[Sum(amount, currency)]] # Add amount in the given currency (three char code)
11 [[Sum]] # Insert the sum in the base currency
12
13 This macro requires the existence of page named ExchangeRates
14 with raw content like this:
15
16 #format text
17 PACIFIC Exchange Rate Service
18 YYYY/MM/DD 2003/01/17
19 EUR/DEM 0.51129
20 EUR/GBP 1.5174
21 EUR/USD 0.93788
22 (C) 2003 PACIFIC - Univ. of British Columbia
23
24 You can get the contents of that page from
25
26 http://blacktusk.commerce.ubc.ca/cgi-bin/fxdata?rd=1&f=tab&q=price&y=daily&g=z&b=EUR
27
28 If someone has an idea for regularly auto-updating that
29 page, please share it.
30 """
31
32 from MoinMoin.Page import Page
33
34 class XchRates:
35
36 def __init__(self):
37 self.__baseCurrency = "EUR"
38 self.__ratesPageName = "ExchangeRates"
39 self.rates = {}
40 self.__loadRates()
41 self.rates[self.__baseCurrency] = 1.0
42
43 def rate(self, currency):
44 if self.hasRate(currency):
45 return self.rates[currency]
46 else:
47 return 0.0
48
49 def hasRate(self, currency):
50 return self.rates.has_key(currency)
51
52 def convertFrom(self, amount, currency=None):
53 if currency == None: currency = self.__baseCurrency
54 return amount * self.rate(currency)
55
56 def formatMoney(self, amount, currency=None):
57 if currency == None: currency = self.__baseCurrency
58 if self.hasRate(currency):
59 return ("%s %.2f" % (currency, amount))
60 else:
61 return ("%s %.2f (NO EXCHANGE RATE AVAILABLE; NOT ADDED)"
62 % (currency, amount))
63
64 def __loadRates(self):
65 ratesPage = Page(self.__ratesPageName).get_raw_body().strip()
66 # ignore first line containing "#format plain"
67 self.__parseRates(ratesPage.splitlines()[1:])
68
69 def __parseRates(self, lines):
70 for l in lines[2:-1]:
71 self.__parseRate(l.strip())
72
73 def __parseRate(self, l):
74 baseByCur,rate = l.split("\t")
75 base,cur = baseByCur.split("/")
76 if rate != ".":
77 self.rates[cur] = float(rate)
78
79
80 def execute(macro, args):
81 if not hasattr(macro.request, 'sum'):
82 macro.request.sum = 0.0
83 macro.request.xch = XchRates()
84
85 xch = macro.request.xch
86
87 if not args:
88 return xch.formatMoney(macro.request.sum)
89 else:
90 # add to running sum and emit addend
91 a = args.split(",")
92 amount = float(a[0])
93 currency = None
94 if len(a) == 2:
95 currency = a[1].strip().upper()
96 macro.request.sum += xch.convertFrom(amount, currency)
97 return xch.formatMoney(amount, currency)
Problems I see:
- Attributes in the request class namespace should be a little more specific, like macro_sum_acc, macro_sum_xch
- Currency or Accumulate might be better names
- basecurrency should be a config param