module Hledger.Data.Amount (
amount,
nullamt,
missingamt,
num,
usd,
eur,
gbp,
hrs,
at,
(@@),
amountWithCommodity,
costOfAmount,
divideAmount,
sumAmounts,
amountstyle,
showAmount,
showAmountDebug,
showAmountWithoutPrice,
maxprecision,
maxprecisionwithpoint,
setAmountPrecision,
withPrecision,
canonicaliseAmount,
canonicalStyles,
nullmixedamt,
missingmixedamt,
mixed,
amounts,
normaliseMixedAmountPreservingFirstPrice,
normaliseMixedAmountPreservingPrices,
costOfMixedAmount,
divideMixedAmount,
isNegativeMixedAmount,
isZeroMixedAmount,
isReallyZeroMixedAmount,
isReallyZeroMixedAmountCost,
showMixedAmount,
showMixedAmountDebug,
showMixedAmountWithoutPrice,
showMixedAmountWithPrecision,
setMixedAmountPrecision,
canonicaliseMixedAmount,
ltraceamount,
tests_Hledger_Data_Amount
) where
import Data.Char (isDigit)
import Data.List
import Data.Map (findWithDefault)
import Data.Ord (comparing)
import Test.HUnit
import Text.Printf
import qualified Data.Map as M
import Hledger.Data.Types
import Hledger.Data.Commodity
import Hledger.Utils
deriving instance Show HistoricalPrice
amountstyle = AmountStyle L False 0 '.' ',' []
instance Show Amount where
show _a@Amount{..}
| debugLevel < 6 =
printf "Amount {acommodity=%s, aquantity=%s, ..}" (show acommodity) (show aquantity)
| otherwise =
printf "Amount {acommodity=%s, aquantity=%s, aprice=%s, astyle=%s}" (show acommodity) (show aquantity) (showPriceDebug aprice) (show astyle)
instance Num Amount where
abs a@Amount{aquantity=q} = a{aquantity=abs q}
signum a@Amount{aquantity=q} = a{aquantity=signum q}
fromInteger i = nullamt{aquantity=fromInteger i}
negate a@Amount{aquantity=q} = a{aquantity=(q)}
(+) = similarAmountsOp (+)
() = similarAmountsOp ()
(*) = similarAmountsOp (*)
amount, nullamt :: Amount
amount = Amount{acommodity="", aquantity=0, aprice=NoPrice, astyle=amountstyle}
nullamt = amount
num n = amount{acommodity="", aquantity=n}
usd n = amount{acommodity="$", aquantity=n, astyle=amountstyle{asprecision=2}}
eur n = amount{acommodity="€", aquantity=n, astyle=amountstyle{asprecision=2}}
gbp n = amount{acommodity="£", aquantity=n, astyle=amountstyle{asprecision=2}}
hrs n = amount{acommodity="h", aquantity=n, astyle=amountstyle{asprecision=1, ascommodityside=R}}
similarAmountsOp :: (Double -> Double -> Double) -> Amount -> Amount -> Amount
similarAmountsOp op Amount{acommodity=_, aquantity=aq, astyle=AmountStyle{asprecision=ap}}
Amount{acommodity=bc, aquantity=bq, astyle=bs@AmountStyle{asprecision=bp}} =
amount{acommodity=bc, aquantity=aq `op` bq, astyle=bs{asprecision=max ap bp}}
amountWithCommodity :: Commodity -> Amount -> Amount
amountWithCommodity c a = a{acommodity=c, aprice=NoPrice}
sumAmounts :: [Amount] -> MixedAmount
sumAmounts = normaliseMixedAmountPreservingPrices . Mixed
at :: Amount -> Amount -> Amount
amt `at` priceamt = amt{aprice=UnitPrice priceamt}
(@@) :: Amount -> Amount -> Amount
amt @@ priceamt = amt{aprice=TotalPrice priceamt}
tests_sumAmounts = [
"sumAmounts" ~: do
sumAmounts [usd 1 `at` eur 1, usd 1 `at` eur 1] `is` Mixed [usd 2 `at` eur 1]
sumAmounts [usd 1 @@ eur 1, usd 1 @@ eur 1] `is` Mixed [usd 1 @@ eur 1, usd 1 @@ eur 1]
]
costOfAmount :: Amount -> Amount
costOfAmount a@Amount{aquantity=q, aprice=price} =
case price of
NoPrice -> a
UnitPrice p@Amount{aquantity=pq} -> p{aquantity=pq * q}
TotalPrice p@Amount{aquantity=pq} -> p{aquantity=pq * signum q}
divideAmount :: Amount -> Double -> Amount
divideAmount a@Amount{aquantity=q} d = a{aquantity=q/d}
isNegativeAmount :: Amount -> Bool
isNegativeAmount Amount{aquantity=q} = q < 0
digits = "123456789" :: String
isZeroAmount :: Amount -> Bool
isZeroAmount a
| otherwise = (null . filter (`elem` digits) . showAmountWithoutPriceOrCommodity) a
isReallyZeroAmount :: Amount -> Bool
isReallyZeroAmount a
| otherwise = (null . filter (`elem` digits) . printf ("%."++show zeroprecision++"f") . aquantity) a
where zeroprecision = 8
showAmountWithPrecision :: Int -> Amount -> String
showAmountWithPrecision p = showAmount . setAmountPrecision p
setAmountPrecision :: Int -> Amount -> Amount
setAmountPrecision p a@Amount{astyle=s} = a{astyle=s{asprecision=p}}
withPrecision :: Amount -> Int -> Amount
withPrecision = flip setAmountPrecision
showAmountDebug :: Amount -> String
showAmountDebug Amount{acommodity="AUTO"} = "(missing)"
showAmountDebug Amount{..} = printf "Amount {acommodity=%s, aquantity=%s, aprice=%s, astyle=%s}" (show acommodity) (show aquantity) (showPriceDebug aprice) (show astyle)
showAmountWithoutPrice :: Amount -> String
showAmountWithoutPrice a = showAmount a{aprice=NoPrice}
showAmountWithoutPriceOrCommodity :: Amount -> String
showAmountWithoutPriceOrCommodity a = showAmount a{acommodity="", aprice=NoPrice}
showPrice :: Price -> String
showPrice NoPrice = ""
showPrice (UnitPrice pa) = " @ " ++ showAmount pa
showPrice (TotalPrice pa) = " @@ " ++ showAmount pa
showPriceDebug :: Price -> String
showPriceDebug NoPrice = ""
showPriceDebug (UnitPrice pa) = " @ " ++ showAmountDebug pa
showPriceDebug (TotalPrice pa) = " @@ " ++ showAmountDebug pa
showAmount :: Amount -> String
showAmount Amount{acommodity="AUTO"} = ""
showAmount a@(Amount{acommodity=c, aprice=p, astyle=AmountStyle{..}}) =
case ascommodityside of
L -> printf "%s%s%s%s" c' space quantity' price
R -> printf "%s%s%s%s" quantity' space c' price
where
quantity = showamountquantity a
displayingzero = null $ filter (`elem` digits) $ quantity
(quantity',c') | displayingzero = ("0","")
| otherwise = (quantity, quoteCommoditySymbolIfNeeded c)
space = if (not (null c') && ascommodityspaced) then " " else "" :: String
price = showPrice p
showamountquantity :: Amount -> String
showamountquantity Amount{aquantity=q, astyle=AmountStyle{asprecision=p, asdecimalpoint=d, asseparator=s, asseparatorpositions=spos}} =
punctuatenumber d s spos $ qstr
where
qstr
| p == maxprecisionwithpoint = printf "%f" q
| p == maxprecision = chopdotzero $ printf "%f" q
| otherwise = printf ("%."++show p++"f") q
punctuatenumber :: Char -> Char -> [Int] -> String -> String
punctuatenumber dec sep grps str = sign ++ reverse (addseps sep (extend grps) (reverse int)) ++ frac''
where
(sign,num) = break isDigit str
(int,frac) = break (=='.') num
frac' = dropWhile (=='.') frac
frac'' | null frac' = ""
| otherwise = dec:frac'
extend [] = []
extend gs = init gs ++ repeat (last gs)
addseps _ [] str = str
addseps sep (g:gs) str
| length str <= g = str
| otherwise = let (s,rest) = splitAt g str
in s ++ [sep] ++ addseps sep gs rest
chopdotzero str = reverse $ case reverse str of
'0':'.':s -> s
s -> s
maxprecision :: Int
maxprecision = 999998
maxprecisionwithpoint :: Int
maxprecisionwithpoint = 999999
canonicaliseAmount :: M.Map Commodity AmountStyle -> Amount -> Amount
canonicaliseAmount styles a@Amount{acommodity=c, astyle=s} = a{astyle=s'}
where
s' = findWithDefault s c styles
instance Show MixedAmount where
show
| debugLevel < 3 = intercalate "\\n" . lines . showMixedAmountWithoutPrice
| otherwise = showMixedAmountDebug
instance Num MixedAmount where
fromInteger i = Mixed [fromInteger i]
negate (Mixed as) = Mixed $ map negate as
(+) (Mixed as) (Mixed bs) = normaliseMixedAmountPreservingPrices $ Mixed $ as ++ bs
(*) = error' "programming error, mixed amounts do not support multiplication"
abs = error' "programming error, mixed amounts do not support abs"
signum = error' "programming error, mixed amounts do not support signum"
nullmixedamt :: MixedAmount
nullmixedamt = Mixed []
missingamt :: Amount
missingamt = amount{acommodity="AUTO"}
missingmixedamt :: MixedAmount
missingmixedamt = Mixed [missingamt]
mixed :: Amount -> MixedAmount
mixed a = Mixed [a]
normaliseMixedAmountPreservingPrices :: MixedAmount -> MixedAmount
normaliseMixedAmountPreservingPrices (Mixed as) = Mixed as''
where
as'' = if null nonzeros then [nullamt] else nonzeros
(_,nonzeros) = partition isReallyZeroAmount as'
as' = map sumAmountsUsingFirstPrice $ group $ sort $ filter (/= missingamt) as
sort = sortBy (\a1 a2 -> compare (acommodity a1, aprice a1) (acommodity a2, aprice a2))
group = groupBy (\a1 a2 -> acommodity a1 == acommodity a2 && sameunitprice a1 a2)
where
sameunitprice a1 a2 =
case (aprice a1, aprice a2) of
(NoPrice, NoPrice) -> True
(UnitPrice p1, UnitPrice p2) -> p1 == p2
_ -> False
tests_normaliseMixedAmountPreservingPrices = [
"normaliseMixedAmountPreservingPrices" ~: do
assertEqual "discard missing amount" (Mixed [nullamt]) (normaliseMixedAmountPreservingPrices $ Mixed [usd 0, missingamt])
assertEqual "combine unpriced same-commodity amounts" (Mixed [usd 2]) (normaliseMixedAmountPreservingPrices $ Mixed [usd 0, usd 2])
assertEqual "don't combine total-priced amounts"
(Mixed
[usd 1 @@ eur 1
,usd (2) @@ eur 1
])
(normaliseMixedAmountPreservingPrices $ Mixed
[usd 1 @@ eur 1
,usd (2) @@ eur 1
])
]
normaliseMixedAmountPreservingFirstPrice :: MixedAmount -> MixedAmount
normaliseMixedAmountPreservingFirstPrice (Mixed as) = Mixed as''
where
as'' = if null nonzeros then [nullamt] else nonzeros
(_,nonzeros) = partition (\a -> isReallyZeroAmount a && a /= missingamt) as'
as' = map sumAmountsUsingFirstPrice $ group $ sort as
sort = sortBy (\a1 a2 -> compare (acommodity a1) (acommodity a2))
group = groupBy (\a1 a2 -> acommodity a1 == acommodity a2)
sumAmountsUsingFirstPrice [] = nullamt
sumAmountsUsingFirstPrice as = (sum as){aprice=aprice $ head as}
amounts :: MixedAmount -> [Amount]
amounts (Mixed as) = as
costOfMixedAmount :: MixedAmount -> MixedAmount
costOfMixedAmount (Mixed as) = Mixed $ map costOfAmount as
divideMixedAmount :: MixedAmount -> Double -> MixedAmount
divideMixedAmount (Mixed as) d = Mixed $ map (flip divideAmount d) as
isNegativeMixedAmount :: MixedAmount -> Maybe Bool
isNegativeMixedAmount m = case as of [a] -> Just $ isNegativeAmount a
_ -> Nothing
where as = amounts $ normaliseMixedAmountPreservingFirstPrice m
isZeroMixedAmount :: MixedAmount -> Bool
isZeroMixedAmount = all isZeroAmount . amounts . normaliseMixedAmountPreservingFirstPrice
isReallyZeroMixedAmount :: MixedAmount -> Bool
isReallyZeroMixedAmount = all isReallyZeroAmount . amounts . normaliseMixedAmountPreservingFirstPrice
isReallyZeroMixedAmountCost :: MixedAmount -> Bool
isReallyZeroMixedAmountCost = isReallyZeroMixedAmount . costOfMixedAmount
showMixedAmount :: MixedAmount -> String
showMixedAmount m = vConcatRightAligned $ map showAmount $ amounts $ normaliseMixedAmountPreservingFirstPrice m
ltraceamount :: String -> MixedAmount -> MixedAmount
ltraceamount s = traceWith (((s ++ ": ") ++).showMixedAmount)
setMixedAmountPrecision :: Int -> MixedAmount -> MixedAmount
setMixedAmountPrecision p (Mixed as) = Mixed $ map (setAmountPrecision p) as
showMixedAmountWithPrecision :: Int -> MixedAmount -> String
showMixedAmountWithPrecision p m =
vConcatRightAligned $ map (showAmountWithPrecision p) $ amounts $ normaliseMixedAmountPreservingFirstPrice m
showMixedAmountDebug :: MixedAmount -> String
showMixedAmountDebug m | m == missingmixedamt = "(missing)"
| otherwise = printf "Mixed [%s]" as
where as = intercalate "\n " $ map showAmountDebug $ amounts m
showMixedAmountWithoutPrice :: MixedAmount -> String
showMixedAmountWithoutPrice m = concat $ intersperse "\n" $ map showfixedwidth as
where
(Mixed as) = normaliseMixedAmountPreservingFirstPrice $ stripPrices m
stripPrices (Mixed as) = Mixed $ map stripprice as where stripprice a = a{aprice=NoPrice}
width = maximum $ map (length . showAmount) as
showfixedwidth = printf (printf "%%%ds" width) . showAmountWithoutPrice
canonicaliseMixedAmount :: M.Map Commodity AmountStyle -> MixedAmount -> MixedAmount
canonicaliseMixedAmount styles (Mixed as) = Mixed $ map (canonicaliseAmount styles) as
canonicalStyles :: [Amount] -> M.Map Commodity AmountStyle
canonicalStyles amts = M.fromList commstyles
where
samecomm = \a1 a2 -> acommodity a1 == acommodity a2
commamts = [(acommodity $ head as, as) | as <- groupBy samecomm $ sortBy (comparing acommodity) amts]
commstyles = [(c, s)
| (c,as) <- commamts
, let styles = map astyle as
, let maxprec = maximum $ map asprecision styles
, let s = (head styles){asprecision=maxprec}
]
tests_Hledger_Data_Amount = TestList $
tests_normaliseMixedAmountPreservingPrices
++ tests_sumAmounts
++ [
"costOfAmount" ~: do
costOfAmount (eur 1) `is` eur 1
costOfAmount (eur 2){aprice=UnitPrice $ usd 2} `is` usd 4
costOfAmount (eur 1){aprice=TotalPrice $ usd 2} `is` usd 2
costOfAmount (eur (1)){aprice=TotalPrice $ usd 2} `is` usd (2)
,"isZeroAmount" ~: do
assertBool "" $ isZeroAmount $ amount
assertBool "" $ isZeroAmount $ usd 0
,"negating amounts" ~: do
let a = usd 1
negate a `is` a{aquantity=(1)}
let b = (usd 1){aprice=UnitPrice $ eur 2}
negate b `is` b{aquantity=(1)}
,"adding amounts without prices" ~: do
let a1 = usd 1.23
let a2 = usd (1.23)
let a3 = usd (1.23)
(a1 + a2) `is` usd 0
(a1 + a3) `is` usd 0
(a2 + a3) `is` usd (2.46)
(a3 + a3) `is` usd (2.46)
sum [a1,a2,a3,a3] `is` usd 0
let ap1 = usd 1 `withPrecision` 1
ap3 = usd 1 `withPrecision` 3
(asprecision $ astyle $ sum [ap1,ap3]) `is` 3
(asprecision $ astyle $ sum [ap3,ap1]) `is` 3
assertBool "" $ isZeroAmount (a1 eur 1.23)
,"showAmount" ~: do
showAmount (usd 0 + gbp 0) `is` "0"
,"normaliseMixedAmountPreservingFirstPrice" ~: do
normaliseMixedAmountPreservingFirstPrice (Mixed []) `is` Mixed [nullamt]
assertBool "" $ isZeroMixedAmount $ normaliseMixedAmountPreservingFirstPrice
(Mixed [usd 10
,usd 10 @@ eur 7
,usd (10)
,usd (10) @@ eur 7
])
,"adding mixed amounts" ~: do
(sum $ map (Mixed . (\a -> [a]))
[usd 1.25
,usd (1) `withPrecision` 0
,usd (0.25)
])
`is` Mixed [amount{aquantity=0}]
,"adding mixed amounts with total prices" ~: do
(sum $ map (Mixed . (\a -> [a]))
[usd 1 @@ eur 1
,usd (2) @@ eur 1
])
`is` (Mixed [usd 1 @@ eur 1
,usd (2) @@ eur 1
])
,"showMixedAmount" ~: do
showMixedAmount (Mixed [usd 1]) `is` "$1.00"
showMixedAmount (Mixed [usd 1 `at` eur 2]) `is` "$1.00 @ €2.00"
showMixedAmount (Mixed [usd 0]) `is` "0"
showMixedAmount (Mixed []) `is` "0"
showMixedAmount missingmixedamt `is` ""
,"showMixedAmountWithoutPrice" ~: do
let a = usd 1 `at` eur 2
showMixedAmountWithoutPrice (Mixed [a]) `is` "$1.00"
showMixedAmountWithoutPrice (Mixed [a, (a)]) `is` "0"
]