source: stamper/stamper/stamper.py@ 0:4cc6fc51063c

Last change on this file since 0:4cc6fc51063c was 0:4cc6fc51063c, checked in by Borja Lopez <borja@…>, 10 years ago

Initial commit, including basic structure of the project and initial features

File size: 3.0 KB
Line 
1
2import json
3from datetime import datetime, timedelta
4from os.path import expanduser, exists
5
6STAMPS_FILE = expanduser('~/.workstamps.json')
7DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
8
9
10class Stamper(object):
11
12 def __init__(self, stamps_file=STAMPS_FILE):
13 self.stamps_file = STAMPS_FILE
14 self.ensure_stamps_file()
15 self.stamps = []
16
17 def ensure_stamps_file(self):
18 if not exists(self.stamps_file):
19 with open(self.stamps_file, 'w') as stamps_file:
20 stamps_file.write('')
21
22 def load_stamps(self):
23 with open(self.stamps_file, 'r') as stamps_file:
24 try:
25 self.stamps = json.load(stamps_file)
26 except ValueError:
27 self.stamps = []
28
29 def save_stamps(self):
30 with open(self.stamps_file, 'w') as stamps_file:
31 json.dump(self.stamps, stamps_file, indent=4)
32
33 def stamp(self, start, end, customer, action):
34 self.stamps.append({
35 'start': start,
36 'end': end,
37 'customer': customer,
38 'action': action,
39 })
40
41 def last_stamp(self):
42 if not self.stamps:
43 return None
44 return self.stamps[-1]
45
46 def worktime(self, start, end):
47 worktime = (datetime.strptime(end, DATE_FORMAT) -
48 datetime.strptime(start, DATE_FORMAT))
49 return worktime.seconds
50
51 def customers(self):
52 customers = []
53 for stamp in self.stamps:
54 if stamp['customer'] not in customers:
55 customers.append(stamp['customer'])
56 customers.remove(None)
57 return customers
58
59 def total_by_customer(self, customer):
60 total = 0
61 for stamp in self.stamps:
62 if stamp['customer'] == customer:
63 total += self.worktime(stamp['start'], stamp['end'])
64 total = timedelta(seconds=total)
65 return str(total)
66
67 def totals(self):
68 totals = {}
69 for customer in self.customers():
70 totals[customer] = self.total_by_customer(customer)
71 return totals
72
73 def details_by_customer(self, customer):
74 details = {}
75 totals = {}
76 for stamp in self.stamps:
77 if stamp['customer'] == customer:
78 start_day = stamp['start'].split(' ')[0]
79 if start_day not in details:
80 details[start_day] = []
81 if start_day not in totals:
82 totals[start_day] = 0
83 worktime = self.worktime(stamp['start'], stamp['end'])
84 details[start_day].append(
85 ' -> %(worktime)s %(customer)s %(action)s' % {
86 'worktime': str(timedelta(seconds=worktime)),
87 'customer': stamp['customer'],
88 'action': stamp['action']
89 })
90 totals[start_day] += worktime
91 for day in totals:
92 totals[day] = str(timedelta(seconds=totals[day]))
93 return details, totals
Note: See TracBrowser for help on using the repository browser.