clerk/journal/printer/amount.go (view raw)
Oleksandr Smirnov
Oleksandr Smirnov
olexsmir@gmail.com journal/printer: preserve original precision, 1 month ago
olexsmir@gmail.com journal/printer: preserve original precision, 1 month ago
| 1 | package printer |
| 2 | |
| 3 | import ( |
| 4 | "olexsmir.xyz/clerk/internal/decimal" |
| 5 | "olexsmir.xyz/clerk/journal/ast" |
| 6 | ) |
| 7 | |
| 8 | func (p *printer) writeAmount(a *ast.Amount, pos CommodityPos) { |
| 9 | if a == nil { |
| 10 | return |
| 11 | } |
| 12 | |
| 13 | if a.IsExpr { |
| 14 | p.buf.WriteString(a.Expr) |
| 15 | return |
| 16 | } |
| 17 | |
| 18 | prec := a.QuantityFmt.Precision |
| 19 | if prec < 2 { |
| 20 | prec = 2 |
| 21 | } |
| 22 | |
| 23 | comm := a.Commodity |
| 24 | if comm == "" { |
| 25 | p.writeDecimal(a.Quantity, a.QuantityFmt, prec) |
| 26 | return |
| 27 | } |
| 28 | |
| 29 | switch pos { |
| 30 | case CommodityBefore: |
| 31 | p.buf.WriteString(comm) |
| 32 | if a.HasSpace { |
| 33 | p.buf.WriteByte(' ') |
| 34 | } |
| 35 | p.writeDecimal(a.Quantity, a.QuantityFmt, prec) |
| 36 | case CommodityAfter: |
| 37 | p.writeDecimal(a.Quantity, a.QuantityFmt, prec) |
| 38 | if a.HasSpace { |
| 39 | p.buf.WriteByte(' ') |
| 40 | } |
| 41 | p.buf.WriteString(comm) |
| 42 | default: |
| 43 | panic("impossible CommodityPos value") |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | func (p *printer) writeCost(c *ast.Cost, pos CommodityPos) { |
| 48 | if c == nil { |
| 49 | return |
| 50 | } |
| 51 | if c.IsTotal { |
| 52 | p.buf.WriteString(" @@ ") |
| 53 | } else { |
| 54 | p.buf.WriteString(" @ ") |
| 55 | } |
| 56 | p.writeAmount(&c.Amount, pos) |
| 57 | } |
| 58 | |
| 59 | func (p *printer) writeBalanceAssertion(ba *ast.BalanceAssertion, pos CommodityPos) { |
| 60 | if ba == nil { |
| 61 | return |
| 62 | } |
| 63 | switch { |
| 64 | case ba.IsInclusive: |
| 65 | p.buf.WriteString("=== ") |
| 66 | case ba.IsStrict: |
| 67 | p.buf.WriteString("== ") |
| 68 | default: |
| 69 | p.buf.WriteString("= ") |
| 70 | } |
| 71 | p.writeAmount(&ba.Amount, pos) |
| 72 | } |
| 73 | |
| 74 | func (p *printer) writeDecimal(d decimal.Decimal, fmt ast.QuantityFormat, forcePrec int) { |
| 75 | d.WriteFixed(&p.buf, forcePrec, fmt.Decimal, fmt.Thousands) |
| 76 | } |