summaryrefslogtreecommitdiff
path: root/lasku.py
blob: 8f9e1851949dad0f1ef23e5ef75effaf7acf1c14 (plain)
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
#!/usr/bin/env python3


import sys

import yaml


def euros(cents):
    return '%.02f' % (cents / 100.0)


class Item:

    def __init__(self, itemdict):
        self.dict = itemdict

        count = itemdict['count']
        unit_cents = int(itemdict['unit'] * 100)
        vatpc = float(itemdict['vatpc']) / 100.0

        self.total_cents = count * unit_cents
        self.vat_cents = int(unit_cents * vatpc)

        self.dict.update({
            'total_cents': self.total_cents,
            'total': euros(self.total_cents),
            'vat_cents': self.vat_cents,
            'vat': euros(self.vat_cents),
            'vatsum': euros(self.vat_cents * count),
            'totalwithvat': euros(count * (unit_cents + self.vat_cents)),
        })


item_template = (
    r'\raggedbottom #number# & '
    r'\parbox[t]{5.5cm}{#desc#\\#date#} & '
    r'\raggedbottom #count# & '
    r'\raggedbottom #unit# & '
    r'\raggedbottom #vat# & '
    r'\raggedbottom #vatpc#\% & '
    r'\raggedbottom #total# & '
    r'\raggedbottom #vatsum# & '
    r'\raggedbottom #totalwithvat# \\[2.2ex]'
)


def cat(filename):
    with open(filename) as f:
        return f.read()


def substitute_all(text, subst):
    for key, value in subst.items():
        pattern = '#{}#'.format(key)
        text = str(value).join(text.split(pattern))
    return text


text = cat('template.tex')

with open(sys.argv[1]) as f:
    company = yaml.safe_load(f)
with open(sys.argv[2]) as f:
    invoice = yaml.safe_load(f)

items = invoice['invoiceitems']
values = dict(company)
values.update(invoice)

itemtext = ''
total_cents = 0
total_vat = 0
total_sum = 0

for item in items:
    it = Item(item)
    itemtext += substitute_all(item_template, it.dict)
    total_cents += it.total_cents
    total_vat += it.vat_cents
    total_sum += it.total_cents + it.vat_cents

values['itemtext'] = itemtext
values['totalraw'] = euros(total_cents)
values['totalvat'] = euros(total_vat)
values['totalsum'] = euros(total_sum)

values['amount'] = values['totalsum']

text = substitute_all(text, values)
sys.stdout.write(text)