-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsammelbestellOutput.py
276 lines (250 loc) · 11.3 KB
/
sammelbestellOutput.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# Sammelbestellungs-Abrechnung
# https://github.com/mgmax/sammelbestellung
#
# (c) 2013 Max Gaukler <[email protected]>
# EML-Output, subdir, billing, ...(c) 2013 Patrick Kanzler <[email protected]>
#
# Licensed under the GNU/GPL version 2 or (at your option) any later version
"""
# TODO there are some unnecessary imports here
import os
import shutil
import sys
import getopt
import httplib
import socket
import urllib
import re
import time
import logging
import cookielib, urllib2
import copy
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import subprocess
import shlex
from string import Template
import locale
# local imports
import pricefetcher
import stringStuff
# TODO really refactor
logging.info("generating outputs")
def makeOutput(buyers, origin, settings, totalBasket, totalSums):
def header(s):
return "\n==================================\n" + \
s.upper() +"\n" + \
"==================================\n"
outputs={"report":""}
for (shop,[b,fileEnding]) in totalBasket.exportNativeBaskets().items():
outputs["basket export "+shop+fileEnding]=b
outputs["report"] += "Report:\n"
outputs["report"] += header("total sum")
outputs["report"] += "Name\ttotal\t(items+shipping)\n"
for b in buyers:
outputs["report"] += "%s\t%.2f\t(%.2f+%.2f)\n" % (b.name, b.finalSum,b.finalSum-b.totalShipping,b.totalShipping)
outputs["report"] += header("shops")
outputs["report"] += "Shop\tSum with shipping\t(items + shipping)\n"
for (shop, s) in totalSums.items():
outputs["report"] += "%s\t%.2f\t(%.2f+%.2f)\n" % (shop, s,s-pricefetcher.shopByName(shop).shipping,pricefetcher.shopByName(shop).shipping)
outputs["report"] += header("details")
outputs["report"] += "name\tcount\traw price each\tfactor\tpartNr\tshop\n"
for (shop, s) in b.shopFinalSums.items():
outputs["report"] += "\t\t%.2f\t1\t<Shipping>\t%s\n" % (pricefetcher.shopByName(shop).shipping,shop)
for b in buyers:
for p in b.basket.parts():
outputs["report"] += "%s\t%d\t%.3f\t%.4f\t%s\t%s\n" % (b.name,p.count,p.price,pricefetcher.shopByName(p.shop).factor,p.partNr,p.shop)
for (shop, s) in b.shopFinalSums.items():
outputs["report"] += "%s\t1\t%.3f\t1\t<ShippingPart>\t%s\n" % (b.name,b.shopShipping[shop],shop)
outputs["report"] += "%s\t\t%.3f\t1\t<ShopTotal>\t%s\n" % (b.name, s, shop)
# convert tab-separated table to text with fixed width spaces
def tabsToFixedWidth(s):
colWidth={}
for line in s.splitlines():
i=0
for col in line.split("\t"):
i+=1
length=len(col.decode("utf-8"))
try:
if colWidth[i] < length:
colWidth[i]=length
except KeyError:
# No colWidth entry yet
colWidth[i]=length
r=""
for line in s.splitlines():
i=0
for col in line.split("\t"):
i+=1
r += col.decode("utf-8").ljust(colWidth[i]+3)
r += "\n"
return r
# insert a linebreak every 5 lines
def groupLines(s):
r=""
n=0
for line in s.splitlines():
r+= line +"\n"
n=n+1
if n==5:
n=0
r+="\n"
return r
outputs["unpackinglist"]="name\t☒OK\tcount\t(total count)\tpartNr\tshop\n"
for b in buyers:
for p in b.basket.parts():
totalCount=0
# do items need to be separated?
for q in totalBasket.parts():
if (p.partNr==q.partNr and p.shop==q.shop):
totalCount=q.count
break
if totalCount==0:
raise Exception("buyer's item not found in total basket")
totalCountStr=""
if totalCount != p.count:
# buyer must share this item with others - print the total amount to notify him
totalCountStr="(of %d)" % totalCount
outputs["unpackinglist"] += "%s\t☐\t%d\t%s\t%s\t%s\n" % (b.name,p.count,totalCountStr,p.partNr,p.shop)
outputs["unpackinglist"]=groupLines(tabsToFixedWidth(outputs["unpackinglist"]))
outputs["unpackinglist"]=header("unpacking list") + outputs["unpackinglist"]
outputs["shopTotalBaskets"]="shop\t☒OK\tcount\tpartNr\n";
totalBasketsLines=[];
for i in totalBasket.parts():
totalBasketsLines.append("%s\t☐\t%s\t%s\t\n" % (i.shop, i.count, i.partNr))
totalBasketsLines.sort()
for l in totalBasketsLines:
outputs["shopTotalBaskets"] += l
outputs["shopTotalBaskets"]=groupLines(tabsToFixedWidth(outputs["shopTotalBaskets"]))
outputs["shopTotalBaskets"]=header("Complete basket for each shop (for checking if everything was received correctly)") + outputs["shopTotalBaskets"]
logging.info("generating mail")
msg = MIMEMultipart()
msg['From'] = str(origin)
msg_to = ""
for b in buyers:
msg_to += b.name + " <" + b.mail + ">, "
msg['To'] = msg_to
order_name = os.path.splitext(sys.argv[1])[0]
msg['Subject'] = order_name
try:
text = open(sys.path[0]+'/'+settings.mailtext, 'r').read()
except IOError:
text = "This text will be replaced by emailtext.txt in the same directory as sammelbestellung.py"
text += header("total sum")
text += "Name\ttotal\t(items+shipping)\n"
for b in buyers:
text += "%s\t%.2f\t(%.2f+%.2f)\n" % (b.name, b.finalSum,b.finalSum-b.totalShipping,b.totalShipping)
text += header("shops")
text += "Shop\tSum with shipping\t(items + shipping)\n"
for (shop, s) in totalSums.items():
text += "%s\t%.2f\t(%.2f+%.2f)\n" % (shop, s,s-pricefetcher.shopByName(shop).shipping,pricefetcher.shopByName(shop).shipping)
msg.attach(MIMEText(text.encode('utf-8'), 'plain', 'UTF-8'))
outputs["mail.eml"] = str(msg)
#paylist
if settings.paylist:
outputs["paylist"] = "Note who has payed yet:\n"
outputs["paylist"] += header("total sum")
outputs["paylist"] += "Name\ttotal\t(items+shipping)\n"
for b in buyers:
outputs["paylist"] += "%s\t%.2f\t(%.2f+%.2f)\t\t\t---\n" % (b.name, b.finalSum,b.finalSum-b.totalShipping,b.totalShipping)
outputs["paylist"] += header("shops")
outputs["paylist"] += "Shop\tSum with shipping\t(items + shipping)\n"
for (shop, s) in totalSums.items():
outputs["paylist"] += "%s\t%.2f\t(%.2f+%.2f)\n" % (shop, s,s-pricefetcher.shopByName(shop).shipping,pricefetcher.shopByName(shop).shipping)
if settings.billing:
logging.info("should generate bills")
try:
content = open(sys.path[0]+'/'+settings.billtemplate, 'r').read()
except IOError:
text = "This text will be replaced by billtemplate.tex (or the filename set by !billtemplate) in the same directory as sammelbestellung.py, "
for b in buyers:
logging.info("generating bill for " + b.name)
tabledata=""
#tabledata += "%s\t%.2f\t(%.2f+%.2f)\n" % (b.name, b.finalSum,b.finalSum-b.totalShipping,b.totalShipping)
totalWithoutShipping = locale.format("%.3f",b.finalSum-b.totalShipping, True, True)
for p in b.basket.parts():
#tabledata += "%d %.3f %.4f %s %s\n" % (p.count,p.price,pricefetcher.shopByName(p.shop).factor,p.partNr,p.shop)
tabledata += "%d & %s & \multicolumn{1}{r}{%s \euro} & \multicolumn{1}{r}{%s \euro} \\\\ \hline\n" % (p.count,p.partNr,locale.format("%.3f", p.price, True, True),locale.format("%.3f", p.price*p.count, True, True))
ShippingTotal=0
for (shop, s) in b.shopFinalSums.items():
ShippingTotal += pricefetcher.shopByName(shop).shipping
#tabledata += "%s\t1\t%.3f\t1\t<ShippingPart>\t%s\n" % (b.name,b.shopShipping[shop],shop)
#tabledata += "%s\t\t%.3f\t1\t<ShopTotal>\t%s\n" % (b.name, s, shop)
globalSum = 0
for (shop, s) in totalSums.items():
globalSum += s-pricefetcher.shopByName(shop).shipping
#outputs["report"] += "%s\t%.2f\t(%.2f+%.2f)\n" % (shop, s,s-pricefetcher.shopByName(shop).shipping,pricefetcher.shopByName(shop).shipping)
t = Template(content)
if b.co==None:
rco=""
else:
rco=b.co + "\\\\"
if b.street==None:
rstreet=""
else:
rstreet=b.street + "\\\\"
if b.city==None:
rcity=""
else:
rcity=b.city + "\\\\"
content_out = t.substitute({'SUBJECT': order_name,
'INVOICE': order_name,
'NAME': origin.name,
'STREET': origin.street,
'AREACODE': origin.areacode,
'CITY': origin.city,
'MAIL_S': origin.mail,
'PHONE': origin.phone,
'TABLE': tabledata,
'TOTWOSHIP': totalWithoutShipping,
'PARTSHIP': locale.format("%.3f", b.totalShipping, True, True),
'TOTALSHIP': locale.format("%.2f", ShippingTotal, True, True),
'PERCENTAGE': locale.format("%.3f",(100*b.totalShipping/ShippingTotal)),
'TOTAL': locale.format("%.2f", round(b.finalSum,2), True, True),
'KTO': origin.kto,
'BLZ': origin.blz,
'BANK': origin.bank,
'GLOBTOTAL': locale.format("%.3f", globalSum, True, True),
'RNAME': b.name,
'RCO': rco,
'RSTREET': rstreet,
'RCITY': rcity})
outputs["bill." + b.name + ".tex"] = content_out
logging.info("bill " + b.name + " done")
#id, einzelpreis, anzahl, gesamtpreis
#subtotal, versananteil von gesamt und total
#"zwischensumme 42€ (17% der gesamten bestellung), versandanteil 5,90*17%=..."
#getrennt nach shops
subdirectory=""
if (settings.subdir):
subdirectory = os.path.splitext(sys.argv[1])[0] + "-output"
try:
#TODO ordentlich machen
os.mkdir(subdirectory)
except OSError as e:
logging.info("directory seems to exist")
subdirectory = subdirectory + os.sep
#create .gitignore in subdir --> is irrelevant for dev
f=open(subdirectory+".gitignore",'w')
f.write("*")
f.close()
basename=subdirectory+sys.argv[1]+"-output-"
for (filename, content) in outputs.items():
if (not ('.' in filename)):
filename = filename + ".txt"
f=open(basename+filename,'w')
f.write(content)
f.close()
if settings.billing:
logging.info("trying to build all latexfiles")
if (settings.subdir):
os.chdir(subdirectory)
for files in os.listdir("."):
if files.endswith(".tex"):
for i in range(0, 2):
proc=subprocess.Popen(shlex.split('pdflatex "' + files + '"'))
proc.communicate()
#achtung bei non-subdir: baut ALLES (weniger greedy machen?)