-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinvoice-gen.py
421 lines (365 loc) · 13.6 KB
/
invoice-gen.py
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#!/usr/bin/python
import pdfkit
import yaml
import subprocess
import argparse
import os.path
import datetime
import string
import random
import sys
now = datetime.datetime.now()
CONFIG_PATH = "config.yaml"
INVOICE_NUMBER_UID_LENGTH = 5
DEFAULT_CONFIG = {
"name": "[BUSINESS_NAME]",
"address": "[BUSINESS_ADDRESS]",
"city_province_country": "[BUSINESS_CITY_PROVINCE_COUNTRY]",
"postal_code": "[BUSINESS_POSTAL_CODE]",
"phone": "[BUSINESS_PHONE]",
"email": "[BUSINESS_EMAIL]",
"abrv": "[ABRV]",
"customers": [
{
"id": 1,
"name": "[CUSTOMER_NAME]",
"address": "[CUSTOMER_ADDRESS]",
"city_province_country": "[CUSTOMER_CITY_PROVINCE_COUNTRY]",
"postal_code": "[CUSTOMER_POSTAL_CODE]",
"phone": "[CUSTOMER_PHONE]"
}
]
}
DEFAULT_DATA = {
"customer_id": 0,
"invoice_type": "invoice",
"invoice_date": "",
"invoice_number": "",
"currency": "CAD",
"items": [
{
"desc": "[DESCRIPTION]",
"hours": 0,
"rate": 35,
}
]
}
DEFAULT_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>Invoice Gen</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Titillium+Web:200,300,400,600,700" rel="stylesheet">
<style type="text/css">
body {
font-family: "Titillium Web", "Source Sans Pro", Apple SD Gothic Neo, Nanum Barun Gothic, Nanum Gothic, Verdana, Arial, Dotum, sans-serif;
font-size: 1.2em;
color: #343a40;
background-color: #fff;
-webkit-font-smoothing: antialiased;
padding-top: 50px;
}
p {
font-weight: 300;
}
.title {
font-weight: 600;
font-size: 1.7em;
}
td, .thin {
font-weight: 300;
}
.seperator {
border-bottom: 1px solid black;
width: 500px;
}
.invoice-type {
background-color: black;
color: white;
text-align: left;
}
.invert-color {
background-color: black;
color: white;
}
.col-half {
width: 50%;
display: inline-block;
float: left;
height: 175px;
margin-top: 15px;
}
.bb-none {
border-bottom: none !important;
}
.bt-none {
border-top: none !important;
}
.bl-none {
border-left: none !important;
}
.br-none {
border-right: none !important;
}
.text-small {
font-size: 0.75em;
}
.currency {
float: left;
}
table {
font-size: 0.9em;
}
.sep {
margin: 15px 0px 30px 0px;
width: 100%;
height: 2px;
background-color: #DEE2E6;
}
.bold {
font-weight: 700;
}
.item-cell {
border: none !important;
}
</style>
</head>
<body>
<div class="row justify-content-center text-center mt-5">
<div class="col-md-12 mb-4">
<div class="title">[BUSINESS_NAME]</div>
<div class="thin">[BUSINESS_ADDRESS]</div>
<div class="thin">[BUSINESS_CITY_PROVINCE_COUNTRY]</div>
<div class="thin">[BUSINESS_POSTAL_CODE]</div>
<div class="thin text-small">[BUSINESS_PHONE]</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-sm-10 mb-4">
<div class="text-justify text-uppercase thin pl-2 invoice-type mb-2">[INVOICE_TYPE]</div>
<div class="col-half">
<h4>BILL TO:</h4>
<div class="thin">[CUSTOMER_NAME]</div>
<div class="thin">[CUSTOMER_ADDRESS]</div>
<div class="thin">[CUSTOMER_CITY_PROVINCE_COUNTRY]</div>
<div class="thin">[CUSTOMER_POSTAL_CODE]</div>
</div>
<div class="col-half">
<div><span class="thin">DATE:</span> [INVOICE_DATE]</div>
<div><span class="thin text-uppercase">[INVOICE_TYPE] #:</span> [INVOICE_NUMBER]</div>
<div><span class="thin text-uppercase">Tax #:</span> [BUSINESS_TAX_NUMBER]</div>
<div><span class="thin">CUSTOMER ID:</span> [CUSTOMER_ID]</div>
</div>
</div>
<div class="col-sm-10">
<table class="table table-bordered">
<tr>
<th>Description</th>
<th>Units</th>
<th>Rate</th>
<th>Amount ([CURRENCY])</th>
</tr>
[INVOICE_ITEMS]
<tr>
<td colspan="3" class="bb-none bl-none text-right">Subtotal</td>
<td class="bb-none text-right"><span class="currency">$</span>[INVOICE_SUBTOTAL]</td>
</tr>
<tr>
<td colspan="3" class="bb-none bt-none bl-none text-right">Sales Tax [INVOICE_SALES_TAX_DESC]</td>
<td class="bb-none bt-none text-right"><span class="currency">$</span>[INVOICE_SALES_TAX]</td>
</tr>
<tr>
<td colspan="3" class="bb-none bt-none bl-none text-right">Total</td>
<td class="text-right invert-color"><span class="currency">$</span>[INVOICE_TOTAL]</td>
</tr>
</table>
</div>
[FOLLOWUP_INFO]
<div class="col-sm-10">
<p class="text-center text-small">
If you have any questions about this [INVOICE_TYPE], please call [BUSINESS_PHONE] or email <em>[BUSINESS_EMAIL]</em>
</p>
</div>
</div>
</body>
</html>
"""
DEFAULT_FOLLOWUP_INVOICE = """
<div class="col-sm-10 mt-2">
<p class="text-center text-small">
Please process all payments within <span class="bold">15 days</span> of receiving this invoice.
</p>
<ul>
<li class="thin">Make all cheques payable to <span class="bold">[BUSINESS_OWNER]</span></li>
</ul>
</div>
<div class="col-sm-4">
<div class="sep"></div>
</div>
"""
# TODO: Make etransfers optional
# <li class="thin">eTransfers and Paypal payments are also accepted, please send to <span class="bold">[BUSINESS_EMAIL]</span></li>
parser = argparse.ArgumentParser(description='Generate invoices.')
parser.add_argument('customer_id',
help="enter customer id to initialize invoice",
nargs='?',
const=0)
parser.add_argument("-l", "--list-customers",
help="list all customers",
action='store_true')
parser.add_argument("-b", "--build",
help="build a new pdf using the specified yaml file",
metavar='YAML_FILE',
nargs=1)
args = parser.parse_args()
def main():
config = {}
if (os.path.isfile(CONFIG_PATH)):
with open(CONFIG_PATH) as raw_config:
config = yaml.safe_load(raw_config)
else:
create_yaml_file(CONFIG_PATH, DEFAULT_CONFIG)
print("Missing config, please fill it in and try again.")
open_file(CONFIG_PATH)
exit()
if args.list_customers:
list_customers(config)
elif args.build:
data = {}
if (os.path.isfile(args.build[0])):
with open(args.build[0]) as raw_data:
data = yaml.safe_load(raw_data)
build_pdf(config, data, args.build[0].replace(".yaml", ".pdf"))
else:
print("Invoice data file '%s' does not exist." % args.build[0])
elif args.customer_id:
if not args.customer_id.isdigit():
print("Invalid customer_id value '%s', please enter a number or use -l to list active customers." % args.customer_id)
elif len([customer for customer in config['customers'] if customer['id'] == int(args.customer_id)]) > 0:
init_new_invoice_data(config, get_customer_by_id(config['customers'], args.customer_id))
else:
print("Customer with id '%s' does not exist, please use -l to list active customers." % args.customer_id)
else:
parser.print_help(sys.stderr)
def list_customers(config):
for customer in config['customers']:
print("%s - %s" % (customer['id'], customer['name']))
def build_pdf(config, data, export_path):
print("Generating...")
processed_data = process_invoice_data(data)
customer = get_customer_by_id(config['customers'], data['customer_id'])
template = DEFAULT_TEMPLATE.replace("[BUSINESS_NAME]", config['name']) \
.replace("[BUSINESS_ADDRESS]", config['address']) \
.replace("[BUSINESS_CITY_PROVINCE_COUNTRY]", config['city_province_country']) \
.replace("[BUSINESS_POSTAL_CODE]", config['postal_code']) \
.replace("[BUSINESS_PHONE]", config['phone']) \
.replace("[BUSINESS_OWNER]", config['owner']) \
.replace("[BUSINESS_EMAIL]", config['email']) \
.replace("[BUSINESS_TAX_NUMBER]", config['tax_number']) \
.replace("[CUSTOMER_NAME]", customer['name']) \
.replace("[CUSTOMER_ID]", str(customer['id'])) \
.replace("[CUSTOMER_ADDRESS]", customer['address']) \
.replace("[CUSTOMER_CITY_PROVINCE_COUNTRY]", customer['city_province_country']) \
.replace("[CUSTOMER_POSTAL_CODE]", customer['postal_code']) \
.replace("[INVOICE_DATE]", data['invoice_date']) \
.replace("[INVOICE_NUMBER]", data['invoice_number']) \
.replace("[INVOICE_TYPE]", data['invoice_type']) \
.replace("[INVOICE_ITEMS]", get_invoice_items(processed_data)) \
.replace("[INVOICE_SUBTOTAL]", str(get_invoice_subtotal(processed_data))) \
.replace("[INVOICE_SALES_TAX_DESC]", str(get_sales_tax_desc(data, config))) \
.replace("[INVOICE_SALES_TAX]", str(get_invoice_sales_tax(processed_data, config))) \
.replace("[INVOICE_TOTAL]", str(get_invoice_total(processed_data, config))) \
.replace("[FOLLOWUP_INFO]", get_followup_info(data['invoice_type'], config)) \
.replace("[CURRENCY]", data['currency'])
final_export_path = export_path.replace("Invoice", data['invoice_type'].capitalize())
pdfkit.from_string(template, final_export_path)
subprocess.check_call(["open", "-a", "Preview.app", final_export_path])
print("Complete.")
def open_file(path):
subprocess.check_call(["open", "-a", "Sublime Text.app", path])
def init_new_invoice_data(config, customer):
data = DEFAULT_DATA
data['customer_id'] = customer['id']
data['invoice_date'] = get_invoice_date(now)
data['invoice_number'] = get_invoice_number(config['abrv'], now)
data['currency'] = customer['currency']
data['items'] = customer['items']
file_name = "%s_-_%s_Invoice_-_%s.yaml" % (config['name'].replace(" ", "_"),
customer['name'].replace(" ", "_"),
data['invoice_number'])
create_yaml_file(file_name, data)
open_file(file_name)
def create_yaml_file(path, data):
with open(path, 'w') as file:
yaml.dump(data, file, default_flow_style=False)
def get_customer_by_id(customers, customer_id):
for customer in customers:
if customer['id'] == int(customer_id):
return customer
return None
def get_invoice_number(abbreviation, now):
return "%s%s%s" % (abbreviation,
str(now.strftime("%d%m%Y")),
''.join(random.choices(string.ascii_uppercase + string.digits,
k=INVOICE_NUMBER_UID_LENGTH)))
def get_invoice_date(now):
return now.strftime("%b %d, %Y")
def get_invoice_items(data):
out = ""
for item in data['items']:
out += "<tr>"
out += "<td class='item-cell'>%s</td>" % process_item_desc(item['desc'])
if 'units' in item:
out += "<td class='text-center item-cell'>%s %s(s)</td>" % (item['units'], item['by'])
out += "<td class='text-right item-cell'><span class='currency'>$</span>%s / %s</td>" % (item['rate'], item['by'])
else:
out += "<td class='text-center item-cell'>-</td>"
out += "<td class='text-right item-cell'><span class='currency'>$</span>%s</td>" % (item['rate'])
out += "<td class='text-right item-cell'><span class='currency'>$</span>%s</td>" % item['total']
out += "</tr>"
return out
def process_item_desc(desc):
if isinstance(desc, list):
out = ""
for item in desc:
if item[0].isupper():
out += "%s</br>" % item
else:
out += "- %s</br>" % item
return out
return desc
def get_invoice_total(data, config):
if 'taxable' in data and data['taxable']:
return '{:.2f}'.format(
sum([float(item['total']) for item in data['items']])
+ (sum([float(item['total']) for item in data['items']]) * config['tax_rate'])
)
else:
return '{:.2f}'.format(sum([float(item['total']) for item in data['items']]))
def get_invoice_sales_tax(data, config):
if 'taxable' in data and data['taxable']:
return '{:.2f}'.format(sum([float(item['total']) for item in data['items']]) * config['tax_rate'])
else:
return '-'
def get_sales_tax_desc(data, config):
if 'taxable' in data and data['taxable']:
return '(' + config['tax_desc'] + ')'
else:
return ''
def get_invoice_subtotal(data):
return '{:.2f}'.format(sum([float(item['total']) for item in data['items']]))
def process_invoice_data(data):
for item in data['items']:
if 'units' in item:
item['total'] = '{:.2f}'.format(item['units'] * item['rate'])
else:
item['total'] = '{:.2f}'.format(item['rate'])
return data
def get_followup_info(invoice_type, config):
if invoice_type == "invoice":
return DEFAULT_FOLLOWUP_INVOICE.replace("[BUSINESS_OWNER]", config['owner']) \
.replace("[BUSINESS_EMAIL]", config['email'])
return ""
if __name__ == '__main__':
main()