1 | """Components to handle access codes. |
---|
2 | """ |
---|
3 | import grok |
---|
4 | from random import SystemRandom as random |
---|
5 | from waeup.sirp.accesscodes.interfaces import IAccessCode, IAccessCodeBatch |
---|
6 | |
---|
7 | class AccessCode(grok.Model): |
---|
8 | grok.implements(IAccessCode) |
---|
9 | |
---|
10 | def __init__(self, batch_serial, batch_prefix, batch_num, random_num, |
---|
11 | cost, invalidation_date=None, student_id=None): |
---|
12 | self.batch_serial = batch_serial |
---|
13 | self.batch_prefix = batch_prefix.upper() |
---|
14 | self.batch_num = str(batch_num) |
---|
15 | self.random_num = random_num |
---|
16 | self.cost = cost |
---|
17 | self.invalidation_date = invalidation_date |
---|
18 | self.student_id = student_id |
---|
19 | |
---|
20 | @property |
---|
21 | def representation(self): |
---|
22 | return '%s-%s-%s' % ( |
---|
23 | self.batch_prefix, self.batch_num, self.random_num) |
---|
24 | |
---|
25 | |
---|
26 | class AccessCodeBatch(object): |
---|
27 | """A batch of access codes. |
---|
28 | """ |
---|
29 | grok.implements(IAccessCodeBatch) |
---|
30 | |
---|
31 | def __init__(self, creation_date, creator, batch_num, batch_prefix, cost, |
---|
32 | entry_num): |
---|
33 | self.creation_date = creation_date |
---|
34 | self.creator = creator |
---|
35 | self.batch_num = batch_num |
---|
36 | self.batch_prefix = batch_prefix |
---|
37 | self.cost = cost |
---|
38 | self.entry_num = entry_num |
---|
39 | self._used = [] |
---|
40 | |
---|
41 | def __iter__(self): |
---|
42 | if len(self._used) >= self.entry_num: |
---|
43 | for num in range(self.entry_num): |
---|
44 | random_num = self._used[num] |
---|
45 | ac = AccessCode(len(self._used), self.batch_prefix, |
---|
46 | self.batch_num, random_num, self.cost) |
---|
47 | yield ac |
---|
48 | else: |
---|
49 | while len(self._used) < self.entry_num: |
---|
50 | random_num = self.getNewRandomNum() |
---|
51 | ac = AccessCode(len(self._used), self.batch_prefix, |
---|
52 | self.batch_num, random_num, self.cost) |
---|
53 | self._used.append(random_num) |
---|
54 | yield ac |
---|
55 | |
---|
56 | def getNewRandomNum(self): |
---|
57 | """Create a random number of 10 digits. |
---|
58 | |
---|
59 | The number is returned as string. |
---|
60 | """ |
---|
61 | result = '' |
---|
62 | while result == '' or result in self._used: |
---|
63 | result = '' |
---|
64 | for x in range(10): |
---|
65 | result += str(random().randint(0, 9)) |
---|
66 | return result |
---|