-
Notifications
You must be signed in to change notification settings - Fork 0
/
radioman.py
executable file
·887 lines (690 loc) · 25.3 KB
/
radioman.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
#!/usr/bin/env python3
import re
import json
import time
import flask
import jinja2
import datetime
from flask import request
try:
import urllib.parse as urllib
except ImportError:
import urllib
try:
import html
except ImportError:
import cgi as html
#from rpctools.jsonrpc import ServerProxy
try:
raise FileNotFoundError()
except NameError:
FileNotFoundError = IOError
except FileNotFoundError:
pass
APP = flask.Flask(__name__)
ENV = jinja2.Environment(loader=jinja2.FileSystemLoader('./templates'))
CONFIG = {
'db': 'radios.json',
}
LIMITS = {}
UNLIMITED = None
TEMPLATE_INDEX = "index.jinja.html"
TEMPLATE_RADIO = "radio.jinja.html"
TEMPLATE_PERSON = "person.jinja.html"
TEMPLATE_DEPT = "dept.jinja.html"
TEMPLATE_PRINTABLE = "print.jinja.html"
TEMPLATE_BULK_ADD = "bulk.jinja.html"
BARCODE_RE = re.compile('^[A-Za-z0-9+=-]{6}$')
CHECKED_IN = 'CHECKED_IN'
CHECKED_OUT = 'CHECKED_OUT'
LOCKED = 'LOCKED'
ALLOW_MISSING_HEADSET = 'ALLOW_MISSING_HEADSET'
ALLOW_EXTRA_HEADSET = 'ALLOW_EXTRA_HEADSET'
ALLOW_DOUBLE_CHECKOUT = 'ALLOW_DOUBLE_CHECKOUT'
ALLOW_DOUBLE_RETURN = 'ALLOW_DOUBLE_RETURN'
ALLOW_LOCKED_CHECKOUT = 'ALLOW_LOCKED_CHECKOUT'
ALLOW_NEGATIVE_HEADSETS = 'ALLOW_NEGATIVE_HEADSETS'
ALLOW_DEPARTMENT_OVERDRAFT = 'ALLOW_DEPARTMENT_OVERDRAFT'
ALLOW_WRONG_PERSON = 'ALLOW_WRONG_PERSON'
RADIOS = {}
AUDIT_LOG = []
LAST_OPER = None
HEADSET_TOTAL = 0
HEADSETS = []
HEADSET_HISTORY = []
BATTERY_TOTAL = 0
BATTERIES = []
BATTERY_HISTORY = []
UBER = None
class RadioNotFound(Exception):
pass
class CreateRadioException(Exception):
pass
class RadioExists(CreateRadioException):
pass
class InvalidID(CreateRadioException):
pass
class OverrideException(Exception):
override = None
class RadioUnavailable(OverrideException):
override = ALLOW_DOUBLE_CHECKOUT
class HeadsetUnavailable(OverrideException):
override = ALLOW_NEGATIVE_HEADSETS
class HeadsetRequired(OverrideException):
override = ALLOW_MISSING_HEADSET
class UnexpectedHeadset(OverrideException):
override = ALLOW_EXTRA_HEADSET
class NotCheckedOut(OverrideException):
override = ALLOW_DOUBLE_RETURN
class RadioLocked(OverrideException):
override = ALLOW_LOCKED_CHECKOUT
class DepartmentOverLimit(OverrideException):
override = ALLOW_DEPARTMENT_OVERDRAFT
class WrongPerson(OverrideException):
override = ALLOW_WRONG_PERSON
def fmt_date(timestamp):
return datetime.datetime.fromtimestamp(timestamp).strftime('%H:%M %a') if timestamp else '…'
def full_date(timestamp):
return datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
def timesince(dt, default="just now"):
"""
Returns string representing "time since" e.g.
3 days ago, 5 hours ago etc.
"""
now = datetime.datetime.now()
diff = now - datetime.datetime.fromtimestamp(dt)
periods = (
(diff.days // 365, "year", "years"),
(diff.days // 30, "month", "months"),
(diff.days // 7, "week", "weeks"),
(diff.days, "day", "days"),
(diff.seconds // 3600, "hour", "hours"),
(diff.seconds // 60, "minute", "minutes"),
(diff.seconds, "second", "seconds"),
)
for period, singular, plural in periods:
if period:
return "%d %s ago" % (period, singular if period == 1 else plural)
return default
URLS = {
'radio': '/radio/{}',
'person': '/person/{}',
'dept': '/dept/{}',
}
TRUNC_MAX = 128
TRUNC_END = 16
def trunc(str):
return str if len(str) < TRUNC_MAX else str[:TRUNC_MAX-TRUNC_END] + '...' + str[-TRUNC_END:]
def link(key, type='radio', title=None):
if key:
prefix = 'Radio ' if type == 'radio' else ''
return '<a{title} href="{url}">{prefix}{text}</a>'.format(title='title="{}"'.format(title) if title else '',
url=URLS[type].format(urllib.quote(key)), prefix=prefix, text=html.escape(trunc(key)))
else:
return key
ENV.filters['fmt_date'] = fmt_date
ENV.filters['full_date'] = full_date
ENV.filters['rel_date'] = timesince
ENV.filters['link'] = link
ENV.filters['quote'] = urllib.quote
ENV.filters['formquote'] = html.escape
def load_db():
data = {}
radiofile = CONFIG['db']
try:
with open(radiofile) as f:
data = json.load(f)
global HEADSETS, AUDIT_LOG, RADIOS, HEADSET_HISTORY, BATTERY_HISTORY, BATTERIES, PEOPLE
RADIOS = data.get('radios', {})
HEADSETS = data.get('headsets', [])
if isinstance(HEADSETS, int):
HEADSETS = []
BATTERIES = data.get('batteries', [])
HEADSET_HISTORY = data.get('headset_history', [])
BATTERY_HISTORY = data.get('battery_history', [])
PEOPLE = data.get('people', {})
AUDIT_LOG = data.get('audits', [])
except FileNotFoundError:
with open(radiofile, 'w') as f:
json.dump({}, f)
def save_db():
with open(CONFIG['db'], 'w') as f:
json.dump({'radios': RADIOS, 'headsets': HEADSETS, 'audits': AUDIT_LOG, 'batteries': BATTERIES, 'headset_history': HEADSET_HISTORY, 'battery_history': BATTERY_HISTORY, 'people': PEOPLE}, f)
def get_blank_radio():
return {
'status': CHECKED_IN,
'last_activity': 0,
'history': [{'status': CHECKED_IN,
'department': None,
'borrower': None,
'badge': None,
'headset': None,
'time': 0,
}],
'checkout': {
'status': CHECKED_IN,
'department': None,
'borrower': None,
'badge': None,
'headset': None,
'time': 0,
},
}
def configure(f):
global CONFIG, RADIOS, HEADSET_TOTAL, BATTERY_TOTAL
with open(f) as conf:
CONFIG.update(json.load(conf))
load_db()
for radio in CONFIG.get('radios', []):
if str(radio) not in RADIOS:
RADIOS[radio] = get_blank_radio()
for name, dept in CONFIG.get('departments', {}).items():
LIMITS[name] = dept.get('limit', UNLIMITED)
HEADSET_TOTAL = CONFIG.get('headsets', 0)
BATTERY_TOTAL = CONFIG.get('batteries', 0)
save_db()
global UBER
if 'uber' in CONFIG:
uber = CONFIG.get('uber', {})
key = uber.get('key', './client.key')
cert = uber.get('cert', './client.crt')
uri = uber.get('uri', 'https://magfest.uber.org/jsonrpc')
if uber.get('auth', False):
UBER = ServerProxy(uri=uri,
key_file=key,
cert_file=cert)
else:
UBER = ServerProxy(uri)
else:
print('Security not configured, probably won\'t be able to use barcodes')
def log(*fields):
logfile = CONFIG.get('log', 'radios.log')
with open(logfile, 'a+') as f:
f.write(','.join((str(f) for f in fields)) + '\n')
def log_audit(*fields):
logfile = CONFIG.get('audit_log', 'audits.log')
with open(logfile, 'a+') as f:
f.write(','.join((str(f) for f in fields)) + '\n')
def department_total(dept):
radio_count = 0
headset_count = 0
battery_count = 0
for radio in RADIOS.values():
if radio['status'] == CHECKED_OUT and \
radio['checkout']['department'] == dept:
radio_count += 1
for headset in HEADSETS:
if headset['status'] == CHECKED_OUT and \
headset['department'] == dept:
headset_count += 1
for battery in BATTERIES:
if battery['status'] == CHECKED_OUT and \
battery['department'] == dept:
battery_count += 1
return radio_count, headset_count, battery_count
def filter_items(model, **kwargs):
if model == "radios":
return {id: radio for radio in RADIOS if all((attr in radio['checkout'] and radio['checkout'][attr] == val for attr, val in kwargs.items()))}
if model == "headsets":
target = HEADSETS
elif model == "batteries":
target = BATTERIES
else:
target = []
return [item for item in target if all((attr in item and item[attr] == val for attr, val in kwargs.items()))]
def filter_radios(**kwargs):
return filter_items("radios", **kwargs)
def filter_headsets(**kwargs):
return filter_items("headsets", **kwargs)
def filter_batteries(**kwargs):
return filter_items("batteries", **kwargs)
def checkout_battery(dept, name=None, badge=None, barcode=None, overrides=[]):
if dept in LIMITS and LIMITS[dept] != UNLIMITED and department_total(dept)[2] >= LIMITS[dept]:
raise DepartmentOverLimit("{} has already checked out too many batteries".format(dept))
entry = {
"department": dept,
"borrower": name,
"time": time.time(),
"status": CHECKED_OUT,
"badge": badge
}
BATTERIES.append(entry)
BATTERY_HISTORY.append(entry)
save_db()
def checkout_headset(dept, name=None, badge=None, barcode=None, overrides=[ALLOW_NEGATIVE_HEADSETS]):
if len(HEADSETS) >= HEADSET_TOTAL and \
ALLOW_NEGATIVE_HEADSETS not in overrides:
raise HeadsetUnavailable("No headsets left")
if dept in LIMITS and LIMITS[dept] != UNLIMITED and department_total(dept)[1] >= LIMITS[dept]:
raise DepartmentOverLimit("{} has already checked out too many headsets".format(dept))
entry = {
"department": dept,
"borrower": name,
"time": time.time(),
"status": CHECKED_OUT,
"badge": badge
}
HEADSETS.append(entry)
HEADSET_HISTORY.append(entry)
save_db()
def checkout_radio(id, dept, name=None, badge=None, barcode=None, headset=False, overrides=[]):
try:
radio = RADIOS[id]
if radio['status'] == LOCKED:
raise RadioLocked("Radio is locked")
if radio['status'] == CHECKED_OUT and \
ALLOW_DOUBLE_CHECKOUT not in overrides:
raise RadioUnavailable("Already checked out")
if dept in LIMITS and \
(LIMITS[dept] != UNLIMITED and
department_total(dept)[0] >= LIMITS[dept]) and \
ALLOW_DEPARTMENT_OVERDRAFT not in overrides:
raise DepartmentOverLimit("Department has already received all allocated radios ({})".format(LIMITS[dept]))
if headset:
checkout_headset(dept, name=name, badge=badge, barcode=barcode, overrides=overrides + [ALLOW_NEGATIVE_HEADSETS])
radio['status'] = CHECKED_OUT
radio['last_activity'] = time.time()
radio['checkout'] = {
'status': radio['status'],
'time': radio['last_activity'],
'borrower': name,
'department': dept,
'badge': badge,
'barcode': barcode,
'headset': headset,
}
radio['history'].append(radio['checkout'])
log(CHECKED_OUT, radio['last_activity'], id, name, badge, dept, headset)
save_db()
except IndexError:
raise RadioNotFound("Radio does not exist")
def return_battery(barcode=None, name=None, badge=None, dept=None, overrides=[]):
global BATTERIES
for i, headset in enumerate(BATTERIES):
if headset['borrower'] == name:
del BATTERIES[i]
BATTERY_HISTORY.append({
'status': CHECKED_IN,
'borrower': name,
'time': time.time(),
'department': dept,
'badge': badge,
'barcode': barcode,
})
save_db()
return
raise HeadsetUnavailable("No battery was found to check in")
def return_headset(barcode=None, name=None, badge=None, dept=None, overrides=[]):
global HEADSETS
for i, headset in enumerate(HEADSETS):
if headset['borrower'] == name:
del HEADSETS[i]
HEADSET_HISTORY.append({
'status': CHECKED_IN,
'borrower': name,
'time': time.time(),
'department': dept,
'badge': badge,
'barcode': barcode,
})
save_db()
return
raise HeadsetUnavailable("No headset was found to check in")
def return_radio(id, headset, barcode=None, name=None, badge=None, overrides=[ALLOW_MISSING_HEADSET, ALLOW_EXTRA_HEADSET, ALLOW_WRONG_PERSON]):
try:
radio = RADIOS[id]
headset_returned = False
if radio['status'] == CHECKED_IN and \
ALLOW_DOUBLE_RETURN not in overrides:
raise NotCheckedOut("Radio was already checked in")
elif name != radio['checkout']['borrower'] and \
ALLOW_WRONG_PERSON not in overrides:
raise WrongPerson("Radio was checked out by '{}'".format(radio['checkout']['borrower']))
name = name or radio['checkout']['borrower']
radio['status'] = CHECKED_IN
radio['last_activity'] = time.time()
radio['checkout'] = {
'status': radio['status'],
'time': radio['last_activity'],
'borrower': name or radio['checkout']['borrower'],
'department': radio['checkout']['department'],
'badge': badge or radio['checkout']['badge'],
'headset': None,
'barcode': barcode or radio['checkout']['barcode'],
}
if headset:
return_headset(barcode=radio['checkout']['barcode'],
name=radio['checkout']['borrower'],
badge=radio['checkout']['badge'],
dept=radio['checkout']['department'])
headset_returned = True
radio['history'].append(radio['checkout'])
RADIOS[id] = radio
log(CHECKED_IN, radio['last_activity'], id, '', '', '', headset)
save_db()
_, headsets_out, batteries_out = get_totals(get_person_history(name))
return headset_returned, headsets_out, batteries_out
except IndexError:
raise RadioNotFound("Radio does not exist")
def lookup_badge(barcode):
if UBER:
res = UBER.barcode.lookup_attendee_from_barcode(barcode_value=barcode)
if 'error' in res:
raise ValueError(res['error'])
return res['full_name'], res['badge_num']
else:
raise ValueError('Uber not set up')
def get_person_info():
barcode, name, badge = None, None, None
data = get_person()
if BARCODE_RE.match(data.strip()):
barcode = data
while True:
try:
name, badge = lookup_badge(barcode)
break
except Exception as e:
print(e)
barcode = None
name = data
break
else:
name = data
return barcode, name, badge
configure('config.json')
@APP.route('/headsetin', methods=['POST'])
def headset_in():
args = request.form
if args.get('borrower'):
try:
return_headset(name=args.get('borrower'), dept=args.get('department'))
return flask.redirect(request.args.get('page', '/') + '?ok')
except OverrideException as e:
return flask.redirect('/?err=' + str(urllib.quote_plus(e.args[0])))
else:
return flask.redirect('/?err=Name+and+department+are+required')
@APP.route('/headsetout', methods=['POST'])
def headset_out():
args = request.form
if args.get('borrower') and args.get('department'):
try:
checkout_headset(name=args.get('borrower'), dept=args.get('department'))
return flask.redirect(request.args.get('page', '/') + '?ok')
except OverrideException as e:
return flask.redirect('/?err=' + str(urllib.quote_plus(e.args[0])))
else:
return flask.redirect('/?err=Name+and+department+are+required')
@APP.route('/batteryin', methods=['POST'])
def battery_in():
args = request.form
if args.get('borrower'):
try:
return_battery(name=args.get('borrower'), dept=args.get('department'))
return flask.redirect(request.args.get('page', '/') + '?ok')
except OverrideException as e:
return flask.redirect('/?err=' + str(urllib.quote_plus(e.args[0])))
else:
return flask.redirect('/?err=Name+and+department+are+required')
@APP.route('/batteryout', methods=['POST'])
def battery_out():
args = request.form
if args.get('borrower') and args.get('department'):
try:
checkout_battery(name=args.get('borrower'), dept=args.get('department'))
return flask.redirect(request.args.get('page', '/') + '?ok')
except OverrideException as e:
return flask.redirect('/?err=' + str(urllib.quote_plus(e.args[0])))
else:
return flask.redirect('/?err=Name+and+department+are+required')
@APP.route('/checkin', methods=['POST'])
def checkin():
args = request.form
if args.get('id'):
try:
headset_returned, has_headset, has_battery = return_radio(args.get('id'), False)
if has_headset or has_battery or headset_returned:
return flask.redirect('/?check')
return flask.redirect(request.args.get('page', '/') + '?ok')
except OverrideException as e:
if e.args:
return flask.redirect('/?err=' + str(e.args[0]).replace(' ', '+'))
else:
return flask.redirect('/?err=Stop+messing+with+stuff')
@APP.route('/checkout', methods=['POST'])
def checkout():
args = request.form
id = args.get('id', '')
name = args.get('name', '').replace('/', '')
dept = args.get('department', '')
headset = args.get('headset', '')
if not name:
return flask.redirect('/?err=Name+is+required')
if not id:
return flask.redirect('/?err=Stop+messing+with+stuff')
try:
checkout_radio(id, dept, name=name, headset=bool(headset), overrides=[])
except OverrideException as e:
if e.args:
return flask.redirect('/?err=' + str(e.args[0]).replace(' ', '+'))
return flask.redirect(request.args.get('page', '/') + '?ok')
def set_locked(radio, locked):
pass
@APP.route('/lock', methods=['POST'])
def lock():
args = request.form
radio = args.get('id', '')
@APP.route('/newradio', methods=['POST'])
def newradio():
args = request.form
radio = args.get('id', '')
if not radio:
return flask.redirect('/?err=ID+is+required')
try:
try:
assert int(radio) > 0
except:
raise InvalidID("Invalid radio ID")
if str(radio) in RADIOS:
raise RadioExists("Radio {} already exists".format(radio))
RADIOS[radio] = get_blank_radio()
save_db()
except (OverrideException, CreateRadioException) as e:
if e.args:
return flask.redirect('/?err=' + str(e.args[0]).replace(' ', '+'))
return flask.redirect(request.args.get('page', '/') + '?ok')
@APP.route('/bulkadd', methods=['GET', 'POST'])
def bulkadd():
if request.method == 'GET':
template = ENV.get_template(TEMPLATE_BULK_ADD)
return template.render()
args = request.form
radios = args.get('radios', '').split()
try:
for radio in radios:
try:
assert int(radio) > 0
except:
raise InvalidID("Invalid radio ID")
if str(radio) in RADIOS:
raise RadioExists("Radio {} already exists".format(radio))
RADIOS[radio] = get_blank_radio()
save_db()
except (OverrideException, CreateRadioException) as e:
if e.args:
return flask.redirect('?err=' + str(e.args[0]).replace(' ', '+'))
return flask.redirect(request.args.get('page', '/') + '?ok')
@APP.route('/radio/<id>')
def radios(id):
if id not in RADIOS:
return flask.redirect('/?err=Radio+does+not+exist')
radio = RADIOS[str(id)]
template = ENV.get_template(TEMPLATE_RADIO)
return template.render(
id=id,
radio=radio,
)
@APP.route('/radio/<id>.json')
def radio_json(id):
if id not in RADIOS:
return flask.jsonify({"error": 404, "message": "Radio does not exist"}), 404
return flask.jsonify(RADIOS[str(id)])
@APP.route('/radios.json')
def radios_json():
return flask.jsonify(RADIOS)
@APP.route('/people.json')
def people_json():
return flask.jsonify(PEOPLE)
@APP.route('/associate', methods=['POST'])
def associate():
new_id = request.args.get('id', None)
new_owner = request.args.get('name', None)
if not new_id:
return flask.jsonify({"error": 400, "message": "'id' parameter must be set"}), 400
if not new_owner:
return flask.jsonify({"error": 400, "message": "'name' parameter must be set"}), 400
old_owner = PEOPLE.get(str(new_id), None)
PEOPLE[str(new_id)] = new_owner
save_db()
return flask.jsonify({"prev_name": old_owner, "name": new_owner, "id": new_id})
def get_person_history(name):
evts = []
for id, radio in RADIOS.items():
for evt in radio['history']:
if evt['borrower'] == name:
newevt = {'type': 'radio', 'id': id}
newevt.update(evt)
evts.append(newevt)
for evt in HEADSET_HISTORY:
if evt['borrower'] == name:
newevt = {'type': 'headset'}
newevt.update(evt)
evts.append(newevt)
for evt in BATTERY_HISTORY:
if evt['borrower'] == name:
newevt = {'type': 'battery'}
newevt.update(evt)
evts.append(newevt)
return evts
def get_dept_history(name):
evts = []
for id, radio in RADIOS.items():
for evt in radio['history']:
if evt['department'] == name:
newevt = {'type': 'radio', 'id': id}
newevt.update(evt)
evts.append(newevt)
for evt in HEADSET_HISTORY:
if evt['department'] == name:
newevt = {'type': 'headset'}
newevt.update(evt)
evts.append(newevt)
for evt in BATTERY_HISTORY:
if evt['department'] == name:
newevt = {'type': 'battery'}
newevt.update(evt)
evts.append(newevt)
return evts
def get_totals(evts):
radios, headsets, batteries = 0, 0, 0
for evt in evts:
if evt['type'] == 'radio':
if evt['status'] == CHECKED_IN:
radios -= 1
elif evt['status'] == CHECKED_OUT:
radios += 1
elif evt['type'] == 'headset':
if evt['status'] == CHECKED_IN:
headsets -= 1
elif evt['status'] == CHECKED_OUT:
headsets += 1
elif evt['type'] == 'battery':
if evt['status'] == CHECKED_IN:
batteries -= 1
elif evt['status'] == CHECKED_OUT:
batteries += 1
return radios, headsets, batteries
@APP.route('/person/<name>')
def person(name):
evts = get_person_history(name)
radios, headsets, batteries = get_totals(evts)
out_radios = []
for id, radio in RADIOS.items():
if radio['status'] == CHECKED_OUT and radio['checkout']['borrower'] == name:
out_radios.append((id, radio['checkout']))
template = ENV.get_template(TEMPLATE_PERSON)
return template.render(
name=name,
history=evts,
radios=radios,
headsets=headsets,
batteries=batteries,
out_radios=out_radios,
)
@APP.route('/dept/<name>')
def dept(name):
evts = get_dept_history(name)
radios, headsets, batteries = 0, 0, 0
out_radios = []
for id, radio in RADIOS.items():
if radio['status'] == CHECKED_OUT and radio['checkout']['department'] == name:
out_radios.append((id, radio['checkout']))
for evt in evts:
if evt['type'] == 'radio':
if evt['status'] == CHECKED_IN:
radios -= 1
elif evt['status'] == CHECKED_OUT:
radios += 1
elif evt['type'] == 'headset':
if evt['status'] == CHECKED_IN:
headsets -= 1
elif evt['status'] == CHECKED_OUT:
radios += 1
elif evt['type'] == 'battery':
if evt['status'] == CHECKED_IN:
batteries -= 1
elif evt['status'] == CHECKED_OUT:
batteries += 1
template = ENV.get_template(TEMPLATE_DEPT)
return template.render(
name=name,
history=evts,
radios=radios,
headsets=headsets,
batteries=batteries,
out_radios=out_radios,
)
@APP.route('/printable')
def printable():
template = ENV.get_template(TEMPLATE_PRINTABLE)
return template.render(
radios=sorted(RADIOS.items(), key=lambda k:int(k[0])),
headsets=HEADSET_TOTAL-len(HEADSETS),
batteries=BATTERY_TOTAL-len(BATTERIES),
headsets_out=HEADSETS,
batteries_out=BATTERIES,
departments=CONFIG.get("departments", {})
)
@APP.route('/')
def index():
args = request.args
msg = None
err = None
warn = None
if 'ok' in args:
msg = "Success"
if 'err' in args:
err = args['err']
if 'check' in args:
warn = "Success! Please check in user's remaining accessories."
template = ENV.get_template(TEMPLATE_INDEX)
return template.render(
msg=msg, error=err, warn=warn,
radios=sorted(RADIOS.items(), key=lambda k:int(k[0])),
headsets=HEADSET_TOTAL-len(HEADSETS),
batteries=BATTERY_TOTAL-len(BATTERIES),
headsets_out=HEADSETS,
batteries_out=BATTERIES,
departments=CONFIG.get("departments", {})
)
if __name__ == "__main__":
APP.run('0.0.0.0', port=80, debug=True)