-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
277 lines (239 loc) · 7.59 KB
/
main.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
class Sales:
import codecs as __codecs
import csv as __csv
import re as re
import datetime
import time
import difflib
from QuadraNpy._graphFunc import getLabelsX
from matplotlib import pyplot as __plt
from QuadraNpy.style import ownStyle
import pickle
db={}
oldestDay=None
newestDay=None
itemsList=None
dataRange=None
graphObject=__plt
labelsX=None
itemSoldCount=0
class Payment:
def updateOldestNewestDay(self,date):
if Sales.oldestDay == None:
Sales.oldestDay=date
Sales.newestDay=date
if date < Sales.oldestDay:
Sales.oldestDay=date
if date > Sales.newestDay:
Sales.newestDay=date
def __init__(self,l,db):
billId=l[1]
self.pay=float(Sales.re.sub(",","",l[12]))
self.type=l[9]
self.service=0
if l[11]:
self.service=float(Sales.re.sub(",","",l[11]))
self.netPay=self.pay-self.service
if billId not in Sales.db:
#create bill if doesnt exist yet
print(f'new exntry {billId}')
Sales.db[billId]=Sales.Billy(billId)
date=Sales.datetime.datetime.strptime(l[6],'%d %b %Y %H:%M:%S')
self.updateOldestNewestDay(date)
Sales.db[billId].date=date
Sales.db[billId].serviceTotal+=self.service
Sales.db[billId].loc=l[5]
class Deposit:
def __init__(self,row):
self.pay=float(Sales.re.sub(",","",row[12]))
self.name=row[16]
class Billy():
def __init__(self,billID):
self.ID=billID
self.totalNet=0
self.total=0
self.serviceTotal=0
self.loc=None
self.date=None
self.items=[]
self.payments=[]
self.deposits=[]
class Item:
def strToNum(self,n):
if n:
return float(Sales.re.sub('[£,", ]','',n))
else:
return 0
def __init__(self,list):
self.name=list[3]
self.server=list[5]
self.amount=list[6]
if list[7]=='(£0.01)'or list[7]=='(£0.02)':
self.tPrice=0.0
else:
try:
self.tPrice=self.strToNum(list[7])
except IndexError:
self.tPrice=self.strToNum((list[9]))
Sales.db[list[4]].total+=self.tPrice
def saveDB(self):
Sales.pickle.dump(Sales.db,open(f'savedDB.pickle','wb'))
def loadDB(self):
Sales.db=Sales.pickle.load(open(f'savedDB.pickle','rb'))
Sales.updateOldestNewestDayV2(self)
print(f'Loaded {len(Sales.db)} items with date range of {Sales.oldestDay} to {Sales.newestDay}')
def updateOldestNewestDayV2(self):
dates=[Sales.db[v].date for v in self.db if Sales.db[v].date]
Sales.oldestDay=min(dates)
Sales.newestDay=max(dates)
def countEODValues(self):
values={}
for t in Sales.db:
if Sales.db[t].date:
day=Sales.db[t].date.date()
dailyTotal=Sales.db[t].total
if day not in values:
values[day]=0
values[day]+=dailyTotal
return values
def exportToSQL(self):
import sqlite3
db=sqlite3.connect('db.db')
cur=db.cursor()
#cur.execute('CREATE TABLE ITEMS (uniqueid TEXT,id TEXT,date INT,name TEXT,amount INT,server TEXT,price REAL,loc TEXT)')
uniqueID=0
for iD in Sales.db:
date=Sales.db[iD].date
if date:
price=Sales.db[iD].total
loc=Sales.db[iD].loc
for item in Sales.db[iD].items:
sqlObjectValues=(uniqueID,iD,date.timestamp(),item.name,int(item.amount),item.server,price,loc)
cur.execute('INSERT INTO ITEMS VALUES (?,?,?,?,?,?,?,?)',sqlObjectValues)
uniqueID+=1
db.commit()
cur.close()
db.close()
def loadFolder(self,path):
import os
directory=os.fsencode(path)
files = [str(f).split("'")[1] for f in os.listdir(directory)]
for f in files:
if f.endswith('.csv'):
fullPath=f'{path}/{f}'
with open(fullPath,'r') as file:
#Assign correct file to its processing function Sales/Payment reports
data=file.readlines()[0].split(',')
if data[4] == 'PaymentName':
self.paymentData(fullPath)
elif data[4] == 'Description':
self.salesData(fullPath)
else:
print(f'Unrecognised file {f}')
print(f'Loaded {f}')
def addSalesNPayments(self,mmYY:str):
Sales.salesData("Reports/SalesDetailed"+mmYY)
Sales.paymentData("Reports/PaymentData"+mmYY)
print(f"Data range is from {Sales.oldestDay} to {Sales.newestDay}")
def salesData(self,path):
count=0
raw=Sales.__codecs.open(path,"r",encoding='utf-8').readlines()
data=[Sales.__breakCSV__(l)[1:9] for l in raw[1:]]
for row in data:
if row:
billID=row[4]
if billID not in Sales.db:
Sales.db[billID]=Sales.Billy(billID)
Sales.db[billID].items.append(Sales.Item(row))
Sales.itemSoldCount+=1
def paymentData(self,paymentsPath):
def addDeposit(billID,line):
deposit=line
print(line)
raw=self.__codecs.open(paymentsPath,"r",encoding="utf-8").readlines()
data=[Sales.__breakCSV__(l)[2:] for l in raw][1:]
for row in data:
if row:
# protection against empty rows in report
billID=row[1]
transType=row[2]
if billID in Sales.db:
#if transaction exists
if transType == 'Payment':
Sales.db[billID].payments.append(Sales.Payment(row,Sales.db))
elif transType == 'DepositRedeemed':
Sales.db[billID].deposits.append(Sales.Deposit(row))
else:
Sales.db[billID]=Sales.Billy(billID)
if transType == 'Payment':
Sales.db[billID].payments.append(Sales.Payment(row,Sales.db))
elif transType == 'DepositRedeemed':
#Sales.db[billID]=self.Billy(billID)
Sales.db[billID].deposits.append(Sales.Deposit(row))
Sales.dataRange=(Sales.newestDay-Sales.oldestDay).days
def __breakCSV__(text):
return ['{}'.format(x) for x in list(Sales.__csv.reader([text], delimiter=','))[0]]
def loadWholeYear(self,YY):
if type(YY) is int:
YY=str(YY)
for m in range(1,13):
month=f"{m:02d}"
Sales.salesData(self,"Reports/SalesDetailed"+month+YY)
Sales.paymentData(self,"Reports/PaymentData"+month+YY)
print(month)
def getItemsList(db=db):
print("Getting Items List")
items=[]
start=Sales.time.time()
for t in Sales.db:
for i in range(len(Sales.db[t].items)):
items.append(Sales.db[t].items[i].name)
uniqueItems=list(dict.fromkeys(items))
finish=Sales.time.time()-start
uniqueItems.sort()
print(finish)
Sales.itemsList = uniqueItems
return uniqueItems
def findTotal(self,searchedItem,fromDate=oldestDay,toDate=newestDay):
if Sales.itemsList is None:
Sales.getItemsList()
if fromDate is None:
fromDate=Sales.oldestDay
else:
fromDate=Sales.datetime.datetime.strptime(fromDate,'%d.%m.%Y').date()
if toDate is None:
toDate=Sales.newestDay
else:
toDate=Sales.datetime.datetime.strptime(toDate,'%d.%m.%Y').date()
searchedItem=Sales.difflib.get_close_matches(searchedItem,Sales.itemsList)[0]
print(f"Searching for {searchedItem}.")
start=Sales.time.time()
datesNValues={}
totalCount=0
for t in Sales.db:
if Sales.db[t].date:
date=Sales.db[t].date.date()
if date>=fromDate.date() and date<=toDate.date():
if date not in datesNValues:
datesNValues[date]=0
for i in range(len(Sales.db[t].items)):
if searchedItem in Sales.db[t].items[i].name:
datesNValues[date]+=1
totalCount+=1
dates=[d for d in datesNValues.keys()]
dates.sort()
values=[datesNValues[v] for v in dates]
finish=Sales.time.time()-start
print(finish)
print(f"Total sold {totalCount} of {searchedItem}")
Sales.ownStyle(Sales.graphObject)
if Sales.labelsX is None:
Sales.labelsX=Sales.getLabelsX(dates)
fig = Sales.graphObject.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xticklabels(labels=Sales.labelsX)
Sales.graphObject.grid(which='minor', linestyle=':', linewidth='0.5', color='#9E807E')
Sales.graphObject.grid(which='major', linestyle=':', linewidth='0.5', color='#9E807E')
Sales.graphObject.plot(values,label=searchedItem)
Sales.graphObject.legend()
Sales.graphObject.show()