source: main/waeup.sirp/trunk/src/waeup/sirp/accesscodes/accesscode.py @ 6774

Last change on this file since 6774 was 6632, checked in by Henrik Bettermann, 13 years ago

Rename applicants.py, accesscodes.py and students.py modules. Their names should be singular like in the university package.

File size: 17.2 KB
RevLine 
[5068]1"""Components to handle access codes.
[6495]2
3Access codes (aka PINs) in waeup sites are organized in batches. That
4means a certain accesscode must be part of a batch. As a site (or
5university) can hold an arbitrary number of batches, we also provide a
6batch container. Each university has one batch container that holds
7all access code batches of which each one can hold several thousands
8of access codes.
[5068]9"""
[5110]10import csv
[5068]11import grok
[5110]12import os
[5118]13from datetime import datetime
[6432]14from hurry.workflow.interfaces import IWorkflowInfo, IWorkflowState
[5068]15from random import SystemRandom as random
[6423]16from waeup.sirp.interfaces import IWAeUPSIRPPluggable, IObjectHistory
[5079]17from waeup.sirp.accesscodes.interfaces import (
18    IAccessCode, IAccessCodeBatch, IAccessCodeBatchContainer
19    )
[6413]20from waeup.sirp.accesscodes.workflow import DISABLED, USED
[5068]21
[5102]22class ManageACBatches(grok.Permission):
23    grok.name('waeup.manageACBatches')
24
[6359]25class AccessCode(grok.Model):
[6495]26    """An access code (aka PIN).
[6499]27
28    Implements
29    :class:`waeup.sirp.accesscodes.interfaces.IAccessCode`. :class:`AccessCode`
30    instances are normally part of an :class:`AccessCodeBatch` so
31    their representation (or code) is built with the containing batch
32    involved.
33
34    `batch_serial`
35       the serial number of the new :class:`AccessCode` inside its batch.
36
37    `random_num`
38       a 10-digit number representing the main part of the code.
39
40    :class:`AccessCode` instances normally have a representation (or
41    code) like
42
43      ``APP-XXX-YYYYYYYYYY``
44
45    where ``APP`` is the prefix of the containing batch, ``XXX`` is
46    the batch number and ``YYYYYYYYYY`` is the real code. The complete
47    PIN is portal-wide unique.
48
49    Access code instances are far more than simple strings. They have
50    a state, a history (so that all changes can be tracked) and a
51    cost (given as a float number).
52
53    The state of an access code is something like 'used', 'disabled',
54    etc. and determined by the workflow defined in
55    :mod:`waeup.sirp.accesscodes.workflow`. This also means that
56    instead of setting the status of an access code directly (you
57    can't do that easily, and yes, that's intentionally), you have to
58    trigger a transition (that might fail, if the transition is not
59    allowed in terms of logic or permissions). See
60    :mod:`waeup.sirp.accesscodes.workflow` for details.
61
[6495]62    """
[5068]63    grok.implements(IAccessCode)
64
[6386]65    def __init__(self, batch_serial, random_num):
[6623]66        super(AccessCode, self).__init__()
[5068]67        self.batch_serial = batch_serial
68        self.random_num = random_num
[6359]69        IWorkflowInfo(self).fireTransition('init')
[5068]70
71    @property
72    def representation(self):
[6499]73        """A string representation of the :class:`AccessCode`.
74
75        It has format ``APP-XXX-YYYYYYYYYY`` as described above.
76        """
[5068]77        return '%s-%s-%s' % (
78            self.batch_prefix, self.batch_num, self.random_num)
79
[5079]80    @property
81    def batch(self):
[6499]82        """The batch this :class:`AccessCode` is contained.
83        """
[5079]84        return getattr(self, '__parent__', None)
[5086]85
[5079]86    @property
87    def batch_prefix(self):
[6499]88        """The prefix of the batch this :class:`AccessCode` belongs to.
89        """
[5079]90        if self.batch is None:
91            return ''
92        return self.batch.prefix
[5086]93
[5079]94    @property
95    def batch_num(self):
[6499]96        """The number of the batch this :class:`AccessCode` belongs to. A
97        read-only attribute.
98        """
[5079]99        if self.batch is None:
100            return ''
101        return self.batch.num
[5068]102
[5118]103    @property
104    def cost(self):
[6499]105        """A float representing the price or ``None``. A read-only attribute.
106        """
[5118]107        if self.batch is None:
108            return None
109        return self.batch.cost
110
[6413]111    @property
[6470]112    def state(self):
[6499]113        """The workflow state. A read-only attribute.
114        """
[6450]115        return IWorkflowState(self).getState()
116
117    @property
[6423]118    def history(self):
[6495]119        """A :class:`waeup.sirp.objecthistory.ObjectHistory` instance.
120        """
[6423]121        history = IObjectHistory(self)
[6453]122        return '||'.join(history.messages)
[6423]123
[6417]124class AccessCodeBatch(grok.Container):
[5068]125    """A batch of access codes.
126    """
127    grok.implements(IAccessCodeBatch)
128
[5086]129    def __init__(self, creation_date, creator, batch_prefix, cost,
130                 entry_num, num=None):
[5079]131        super(AccessCodeBatch, self).__init__()
[5068]132        self.creation_date = creation_date
133        self.creator = creator
[5116]134        self.prefix = batch_prefix.upper()
[5068]135        self.cost = cost
136        self.entry_num = entry_num
[5086]137        self.num = num
[6425]138        self.used_num = 0
[5149]139        self.disabled_num = 0
[5079]140
[5118]141    def _createEntries(self):
[5079]142        """Create the entries for this batch.
143        """
[5118]144        for num, pin in enumerate(self._getNewRandomNum(num=self.entry_num)):
[5121]145            self.addAccessCode(num, pin)
[5112]146        return
[5118]147
148    def _getNewRandomNum(self, num=1):
[5112]149        """Create a set of ``num`` random numbers of 10 digits each.
[5086]150
[5068]151        The number is returned as string.
152        """
[5118]153        curr = 1
154        while curr <= num:
[5112]155            pin = ''
[5068]156            for x in range(10):
[5112]157                pin += str(random().randint(0, 9))
[6417]158            if not '%s-%s-%s' % (self.prefix, self.num, pin) in self.keys():
[5127]159                curr += 1
160                yield pin
161            # PIN already in use
[5073]162
[5118]163    def _getStoragePath(self):
164        """Get the directory, where we store all batch-related CSV files.
165        """
166        site = grok.getSite()
167        storagepath = site['datacenter'].storage
168        ac_storage = os.path.join(storagepath, 'accesscodes')
169        if not os.path.exists(ac_storage):
170            os.mkdir(ac_storage)
171        return ac_storage
172
173    def getAccessCode(self, ac_id):
174        """Get the AccessCode with ID ``ac_id`` or ``KeyError``.
175        """
[6417]176        return self[ac_id]
[5118]177
[5121]178    def addAccessCode(self, num, pin):
179        """Add an access-code.
180        """
181        ac = AccessCode(num, pin)
182        ac.__parent__ = self
[6417]183        self[ac.representation] = ac
[5121]184        return
185
[5110]186    def createCSVLogFile(self):
187        """Create a CSV file with data in batch.
188
189        Data will not contain invalidation date nor student ids.  File
190        will be created in ``accesscodes`` subdir of data center
191        storage path.
192
193        Returns name of created file.
194        """
195        date = self.creation_date.strftime('%Y_%m_%d_%H_%M_%S')
[5118]196        ac_storage = self._getStoragePath()
[5110]197        csv_path = os.path.join(
198            ac_storage, '%s-%s-%s-%s.csv' % (
199                self.prefix, self.num, date, self.creator)
200            )
201        writer = csv.writer(open(csv_path, 'w'), quoting=csv.QUOTE_ALL)
202        writer.writerow(['serial', 'ac', 'cost'])
203        writer.writerow([self.prefix, str(self.num), "%0.2f" % self.cost])
[5118]204
[6424]205        for value in sorted(self.values(),
206                            cmp=lambda x, y: cmp(
207                x.batch_serial, y.batch_serial)):
[5110]208            writer.writerow(
209                [str(value.batch_serial), str(value.representation)]
210                )
[5118]211        site = grok.getSite()
[5112]212        logger = site.logger
213        logger.info(
214            "Created batch %s-%s" % (self.prefix, self.num))
215        logger.info(
216            "Written batch CSV to %s" % csv_path)
[5110]217        return os.path.basename(csv_path)
218
[5118]219    def archive(self):
220        """Create a CSV file for archive.
221        """
222        ac_storage = self._getStoragePath()
223        now = datetime.now()
224        timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')
225        csv_path = os.path.join(
226            ac_storage, '%s-%s_archive-%s-%s.csv' % (
227                self.prefix, self.num, timestamp, self.creator)
228            )
229        writer = csv.writer(open(csv_path, 'w'), quoting=csv.QUOTE_ALL)
[6470]230        writer.writerow(['prefix', 'serial', 'ac', 'state', 'history'])
[5118]231        writer.writerow([self.prefix, '%0.2f' % self.cost, str(self.num),
232                         str(self.entry_num)])
[6424]233        for value in sorted(
234            self.values(),
235            cmp = lambda x, y: cmp(x.batch_serial, y.batch_serial)
236            ):
[5118]237            writer.writerow([
238                    self.prefix, value.batch_serial, value.representation,
[6470]239                    value.state, value.history
[5118]240                    ])
241        return os.path.basename(csv_path)
242
[6417]243@grok.subscribe(IAccessCodeBatch, grok.IObjectAddedEvent)
[6418]244def handle_batch_added(batch, event):
[6417]245    # A (maybe dirty?) workaround to make batch containers work
246    # without self-maintained acids: as batches should contain their
247    # set of data immediately after creation, but we cannot add
248    # subobjects as long as the batch was not added already to the
249    # ZODB, we trigger the item creation for the time after the batch
250    # was added to the ZODB.
251    batch._createEntries()
252    return
253
254
[5079]255class AccessCodeBatchContainer(grok.Container):
256    grok.implements(IAccessCodeBatchContainer)
[5073]257
[5132]258    def _getStoragePath(self):
259        """Get the directory, where batch import files are stored.
[6542]260
261        If the path does not exist yet, it is created. The path is
262        normally ``accesscodes/imports`` below the datacenter storage
263        path (see :data:`waeup.sirp.accesscodes.Datacenter.storage`).
[5132]264        """
265        site = grok.getSite()
266        storagepath = site['datacenter'].storage
267        ac_storage = os.path.join(storagepath, 'accesscodes')
268        import_path = os.path.join(ac_storage, 'imports')
[6542]269        for path in [ac_storage, import_path]:
270            if not os.path.exists(path):
271                os.mkdir(path)
272                site.logger.info('created path %s' % path)
[5132]273        return import_path
274
[5079]275    def addBatch(self, batch):
[6542]276        """Add an already created `batch`.
[5086]277        """
278        batch.num = self.getNum(batch.prefix)
279        key = "%s-%s" % (batch.prefix, batch.num)
[5079]280        self[key] = batch
[5086]281        self._p_changed = True
[5079]282
[6417]283    def createBatch(self, creation_date, creator, prefix, cost,
[5127]284                    entry_num):
285        """Create and add a batch.
286        """
[6417]287        batch_num = self.getNum(prefix)
288        batch = AccessCodeBatch(creation_date, creator, prefix,
[5127]289                                cost, entry_num, num=batch_num)
290        self.addBatch(batch)
291        return batch
[6124]292
[5086]293    def getNum(self, prefix):
294        """Get next unused num for given prefix.
295        """
296        num = 1
[5116]297        while self.get('%s-%s' % (prefix, num), None) is not None:
[5086]298            num += 1
299        return num
[5095]300
[5132]301    def getImportFiles(self):
302        """Return a generator with basenames of available import files.
303        """
304        path = self._getStoragePath()
305        for filename in sorted(os.listdir(path)):
306            yield filename
[6124]307
[6449]308    # This is temporary reimport solution. Access codes will be imported
[6470]309    # with state initialized no matter if they have been used before.
[5132]310    def reimport(self, filename, creator=u'UNKNOWN'):
311        """Reimport a batch given in CSV file.
312
313        CSV file must be of format as generated by createCSVLogFile
314        method.
315        """
316        path = os.path.join(self._getStoragePath(), filename)
317        reader = csv.DictReader(open(path, 'rb'), quoting=csv.QUOTE_ALL)
318        entry = reader.next()
[6449]319        cost = float(entry['serial'])
[5132]320        num = int(entry['ac'])
[6449]321        prefix = entry['prefix']
322        batch_name = '%s-%s' % (prefix, num)
[5132]323        if batch_name in self.keys():
324            raise KeyError('Batch already exists: %s' % batch_name)
325        batch = AccessCodeBatch(
[6449]326            datetime.now(), creator, prefix, cost, 0, num=num)
[5132]327        num_entries = 0
[6417]328        self[batch_name] = batch
[5132]329        for row in reader:
330            pin = row['ac']
331            serial = int(row['serial'])
332            rand_num = pin.rsplit('-', 1)[-1]
333            batch.addAccessCode(serial, rand_num)
334            num_entries += 1
335        batch.entry_num = num_entries
[6417]336
[5132]337        batch.createCSVLogFile()
338        return
[5149]339
[5153]340    def getAccessCode(self, ac_id):
341        """Get the AccessCode with ID ``ac_id`` or ``KeyError``.
342        """
343        for batchname in self.keys():
344            batch = self[batchname]
345            try:
346                return batch.getAccessCode(ac_id)
347            except KeyError:
348                continue
349        return None
[6124]350
[6458]351    def disable(self, ac_id, comment=None):
[5153]352        """Disable the AC with ID ``ac_id``.
353
354        ``user_id`` is the user ID of the user triggering the
355        process. Already disabled ACs are left untouched.
356        """
357        ac = self.getAccessCode(ac_id)
358        if ac is None:
359            return
[6458]360        disable_accesscode(ac_id, comment)
[5153]361        return
362
[6458]363    def enable(self, ac_id, comment=None):
[5153]364        """(Re-)enable the AC with ID ``ac_id``.
365
366        This leaves the given AC in state ``unused``. Already enabled
367        ACs are left untouched.
368        """
369        ac = self.getAccessCode(ac_id)
370        if ac is None:
371            return
[6458]372        reenable_accesscode(ac_id, comment)
[5153]373        return
374
[5073]375class AccessCodePlugin(grok.GlobalUtility):
376    grok.name('accesscodes')
377    grok.implements(IWAeUPSIRPPluggable)
378
379    def setup(self, site, name, logger):
[5079]380        site['accesscodes'] = AccessCodeBatchContainer()
381        logger.info('Installed container for access code batches.')
382        return
[5073]383
384    def update(self, site, name, logger):
[5107]385        if not 'accesscodes' in site.keys():
386            logger.info('Updating site at %s. Installing access codes.' % (
387                    site,))
388            self.setup(site, name, logger)
389        else:
390            logger.info(
391                'AccessCodePlugin: Updating site at %s: Nothing to do.' % (
392                    site, ))
393        return
[5447]394
395def get_access_code(access_code):
396    """Get an access code instance.
397
398    An access code here is a string like ``PUDE-1-1234567890``.
[6124]399
[5447]400    Returns ``None`` if the given code cannot be found.
401
402    This is a convenicence function that is faster than looking up a
403    batch container for the approriate access code.
404    """
405    site = grok.getSite()
406    if not isinstance(access_code, basestring):
407        return None
408    try:
409        batch_id, ac_id = access_code.rsplit('-', 1)
410    except:
411        return None
[5467]412    batch = site['accesscodes'].get(batch_id, None)
413    if batch is None:
[5447]414        return None
415    try:
416        code = batch.getAccessCode(access_code)
417    except KeyError:
418        return None
419    return code
[6359]420
[6420]421def fire_transition(access_code, arg, toward=False, comment=None):
[6408]422    """Fire workflow transition for access code.
423
424    The access code instance is looked up via `access_code` (a string
425    like ``APP-1-12345678``).
426
427    `arg` tells what kind of transition to trigger. This will be a
428    transition id like ``'use'`` or ``'init'``, or some transition
[6493]429    target like :data:`waeup.sirp.accesscodes.workflow.INITIALIZED`.
[6408]430
431    If `toward` is ``False`` (the default) you have to pass a
432    transition id as `arg`, otherwise you must give a transition
433    target.
434
[6420]435    If `comment` is specified (default is ``None``) the given string
436    will be passed along as transition comment. It will appear in the
437    history of the changed access code. You can use this to place
438    remarks like for which object the access code was used or similar.
439
[6408]440    :func:`fire_transition` might raise exceptions depending on the
441    reason why the requested transition cannot be performed.
442
443    The following exceptions can occur during processing:
444
445    :exc:`KeyError`:
446      signals not existent access code, batch or site.
447
448    :exc:`ValueError`:
449      signals illegal format of `access_code` string. The regular format is
450      ``APP-N-XXXXXXXX``.
451
452    :exc:`hurry.workflow.interfaces.InvalidTransitionError`:
453      the transition requested cannot be performed because the workflow
454      rules forbid it.
455
456    :exc:`Unauthorized`:
457      the current user is not allowed to perform the requested transition.
458
459    """
[6374]460    try:
[6408]461        batch_id, ac_id = access_code.rsplit('-', 1)
462    except ValueError:
[6588]463        raise ValueError(
464            'Invalid access code format: %s (use: APP-N-XXXXXXXX)' % (
465                access_code,))
[6408]466    try:
467        ac = grok.getSite()['accesscodes'][batch_id].getAccessCode(access_code)
[6588]468    except TypeError:
469        raise KeyError(
470            'No site available for looking up accesscodes')
[6408]471    info = IWorkflowInfo(ac)
472    if toward:
[6420]473        info.fireTransitionToward(arg, comment=comment)
[6408]474    else:
[6420]475        info.fireTransition(arg, comment=comment)
[6374]476    return True
477
[6420]478def invalidate_accesscode(access_code, comment=None):
[6374]479    """Invalidate AccessCode denoted by string ``access_code``.
480
481    Fires an appropriate transition to perform the task.
482
[6420]483    `comment` is a string that will appear in the access code
484    history.
485
[6408]486    See :func:`fire_transition` for possible exceptions and their
487    meanings.
[6374]488    """
[6588]489    try:
490        fire_transition(access_code, 'use', comment=comment)
491        return True
492    except:
493        return False
[6359]494
[6420]495def disable_accesscode(access_code, comment=None):
[6374]496    """Disable AccessCode denoted by string ``access_code``.
497
498    Fires an appropriate transition to perform the task.
499
[6420]500    `comment` is a string that will appear in the access code
501    history.
502
[6408]503    See :func:`fire_transition` for possible exceptions and their
504    meanings.
[6374]505    """
[6420]506    return fire_transition(
507        access_code, DISABLED, toward=True, comment=comment)
[6359]508
[6420]509def reenable_accesscode(access_code, comment=None):
[6374]510    """Reenable AccessCode denoted by string ``access_code``.
511
512    Fires an appropriate transition to perform the task.
513
[6420]514    `comment` is a string that will appear in the access code
515    history.
516
[6408]517    See :func:`fire_transition` for possible exceptions and their
518    meanings.
[6374]519    """
[6420]520    return fire_transition(access_code, 'reenable', comment=comment)
Note: See TracBrowser for help on using the repository browser.