[5068] | 1 | """Components to handle access codes. |
---|
[6495] | 2 | |
---|
| 3 | Access codes (aka PINs) in waeup sites are organized in batches. That |
---|
| 4 | means a certain accesscode must be part of a batch. As a site (or |
---|
| 5 | university) can hold an arbitrary number of batches, we also provide a |
---|
| 6 | batch container. Each university has one batch container that holds |
---|
| 7 | all access code batches of which each one can hold several thousands |
---|
| 8 | of access codes. |
---|
[5068] | 9 | """ |
---|
[5110] | 10 | import csv |
---|
[5068] | 11 | import grok |
---|
[5110] | 12 | import os |
---|
[5118] | 13 | from datetime import datetime |
---|
[6432] | 14 | from hurry.workflow.interfaces import IWorkflowInfo, IWorkflowState |
---|
[5068] | 15 | from random import SystemRandom as random |
---|
[6423] | 16 | from waeup.sirp.interfaces import IWAeUPSIRPPluggable, IObjectHistory |
---|
[5079] | 17 | from waeup.sirp.accesscodes.interfaces import ( |
---|
| 18 | IAccessCode, IAccessCodeBatch, IAccessCodeBatchContainer |
---|
| 19 | ) |
---|
[6413] | 20 | from waeup.sirp.accesscodes.workflow import DISABLED, USED |
---|
[5068] | 21 | |
---|
[6359] | 22 | class AccessCode(grok.Model): |
---|
[6495] | 23 | """An access code (aka PIN). |
---|
[6499] | 24 | |
---|
| 25 | Implements |
---|
| 26 | :class:`waeup.sirp.accesscodes.interfaces.IAccessCode`. :class:`AccessCode` |
---|
| 27 | instances are normally part of an :class:`AccessCodeBatch` so |
---|
| 28 | their representation (or code) is built with the containing batch |
---|
| 29 | involved. |
---|
| 30 | |
---|
| 31 | `batch_serial` |
---|
| 32 | the serial number of the new :class:`AccessCode` inside its batch. |
---|
| 33 | |
---|
| 34 | `random_num` |
---|
| 35 | a 10-digit number representing the main part of the code. |
---|
| 36 | |
---|
| 37 | :class:`AccessCode` instances normally have a representation (or |
---|
| 38 | code) like |
---|
| 39 | |
---|
| 40 | ``APP-XXX-YYYYYYYYYY`` |
---|
| 41 | |
---|
| 42 | where ``APP`` is the prefix of the containing batch, ``XXX`` is |
---|
| 43 | the batch number and ``YYYYYYYYYY`` is the real code. The complete |
---|
| 44 | PIN is portal-wide unique. |
---|
| 45 | |
---|
| 46 | Access code instances are far more than simple strings. They have |
---|
| 47 | a state, a history (so that all changes can be tracked) and a |
---|
| 48 | cost (given as a float number). |
---|
| 49 | |
---|
| 50 | The state of an access code is something like 'used', 'disabled', |
---|
| 51 | etc. and determined by the workflow defined in |
---|
| 52 | :mod:`waeup.sirp.accesscodes.workflow`. This also means that |
---|
| 53 | instead of setting the status of an access code directly (you |
---|
| 54 | can't do that easily, and yes, that's intentionally), you have to |
---|
| 55 | trigger a transition (that might fail, if the transition is not |
---|
| 56 | allowed in terms of logic or permissions). See |
---|
| 57 | :mod:`waeup.sirp.accesscodes.workflow` for details. |
---|
| 58 | |
---|
[6495] | 59 | """ |
---|
[5068] | 60 | grok.implements(IAccessCode) |
---|
| 61 | |
---|
[6386] | 62 | def __init__(self, batch_serial, random_num): |
---|
[6623] | 63 | super(AccessCode, self).__init__() |
---|
[5068] | 64 | self.batch_serial = batch_serial |
---|
| 65 | self.random_num = random_num |
---|
[6927] | 66 | self.owner = None |
---|
[6359] | 67 | IWorkflowInfo(self).fireTransition('init') |
---|
[5068] | 68 | |
---|
| 69 | @property |
---|
| 70 | def representation(self): |
---|
[6499] | 71 | """A string representation of the :class:`AccessCode`. |
---|
| 72 | |
---|
| 73 | It has format ``APP-XXX-YYYYYYYYYY`` as described above. |
---|
| 74 | """ |
---|
[5068] | 75 | return '%s-%s-%s' % ( |
---|
| 76 | self.batch_prefix, self.batch_num, self.random_num) |
---|
| 77 | |
---|
[5079] | 78 | @property |
---|
| 79 | def batch(self): |
---|
[6499] | 80 | """The batch this :class:`AccessCode` is contained. |
---|
| 81 | """ |
---|
[5079] | 82 | return getattr(self, '__parent__', None) |
---|
[5086] | 83 | |
---|
[5079] | 84 | @property |
---|
| 85 | def batch_prefix(self): |
---|
[6499] | 86 | """The prefix of the batch this :class:`AccessCode` belongs to. |
---|
| 87 | """ |
---|
[5079] | 88 | if self.batch is None: |
---|
| 89 | return '' |
---|
| 90 | return self.batch.prefix |
---|
[5086] | 91 | |
---|
[5079] | 92 | @property |
---|
| 93 | def batch_num(self): |
---|
[6499] | 94 | """The number of the batch this :class:`AccessCode` belongs to. A |
---|
| 95 | read-only attribute. |
---|
| 96 | """ |
---|
[5079] | 97 | if self.batch is None: |
---|
| 98 | return '' |
---|
| 99 | return self.batch.num |
---|
[5068] | 100 | |
---|
[5118] | 101 | @property |
---|
| 102 | def cost(self): |
---|
[6499] | 103 | """A float representing the price or ``None``. A read-only attribute. |
---|
| 104 | """ |
---|
[5118] | 105 | if self.batch is None: |
---|
| 106 | return None |
---|
| 107 | return self.batch.cost |
---|
| 108 | |
---|
[6413] | 109 | @property |
---|
[6470] | 110 | def state(self): |
---|
[6499] | 111 | """The workflow state. A read-only attribute. |
---|
| 112 | """ |
---|
[6450] | 113 | return IWorkflowState(self).getState() |
---|
| 114 | |
---|
| 115 | @property |
---|
[6423] | 116 | def history(self): |
---|
[6495] | 117 | """A :class:`waeup.sirp.objecthistory.ObjectHistory` instance. |
---|
| 118 | """ |
---|
[6423] | 119 | history = IObjectHistory(self) |
---|
[6453] | 120 | return '||'.join(history.messages) |
---|
[6423] | 121 | |
---|
[6417] | 122 | class AccessCodeBatch(grok.Container): |
---|
[5068] | 123 | """A batch of access codes. |
---|
| 124 | """ |
---|
| 125 | grok.implements(IAccessCodeBatch) |
---|
| 126 | |
---|
[5086] | 127 | def __init__(self, creation_date, creator, batch_prefix, cost, |
---|
| 128 | entry_num, num=None): |
---|
[5079] | 129 | super(AccessCodeBatch, self).__init__() |
---|
[5068] | 130 | self.creation_date = creation_date |
---|
| 131 | self.creator = creator |
---|
[5116] | 132 | self.prefix = batch_prefix.upper() |
---|
[5068] | 133 | self.cost = cost |
---|
| 134 | self.entry_num = entry_num |
---|
[5086] | 135 | self.num = num |
---|
[6425] | 136 | self.used_num = 0 |
---|
[5149] | 137 | self.disabled_num = 0 |
---|
[5079] | 138 | |
---|
[5118] | 139 | def _createEntries(self): |
---|
[5079] | 140 | """Create the entries for this batch. |
---|
| 141 | """ |
---|
[6936] | 142 | for num, pin in enumerate(self.getNewRandomNum(num=self.entry_num)): |
---|
[5121] | 143 | self.addAccessCode(num, pin) |
---|
[5112] | 144 | return |
---|
[5118] | 145 | |
---|
[6936] | 146 | def getNewRandomNum(self, num=1): |
---|
[5112] | 147 | """Create a set of ``num`` random numbers of 10 digits each. |
---|
[5086] | 148 | |
---|
[5068] | 149 | The number is returned as string. |
---|
| 150 | """ |
---|
[5118] | 151 | curr = 1 |
---|
| 152 | while curr <= num: |
---|
[5112] | 153 | pin = '' |
---|
[5068] | 154 | for x in range(10): |
---|
[5112] | 155 | pin += str(random().randint(0, 9)) |
---|
[6417] | 156 | if not '%s-%s-%s' % (self.prefix, self.num, pin) in self.keys(): |
---|
[5127] | 157 | curr += 1 |
---|
| 158 | yield pin |
---|
| 159 | # PIN already in use |
---|
[5073] | 160 | |
---|
[5118] | 161 | def _getStoragePath(self): |
---|
| 162 | """Get the directory, where we store all batch-related CSV files. |
---|
| 163 | """ |
---|
| 164 | site = grok.getSite() |
---|
| 165 | storagepath = site['datacenter'].storage |
---|
| 166 | ac_storage = os.path.join(storagepath, 'accesscodes') |
---|
| 167 | if not os.path.exists(ac_storage): |
---|
| 168 | os.mkdir(ac_storage) |
---|
| 169 | return ac_storage |
---|
| 170 | |
---|
| 171 | def getAccessCode(self, ac_id): |
---|
| 172 | """Get the AccessCode with ID ``ac_id`` or ``KeyError``. |
---|
| 173 | """ |
---|
[6417] | 174 | return self[ac_id] |
---|
[5118] | 175 | |
---|
[6936] | 176 | def addAccessCode(self, num, pin, owner=None): |
---|
[5121] | 177 | """Add an access-code. |
---|
| 178 | """ |
---|
| 179 | ac = AccessCode(num, pin) |
---|
[6936] | 180 | if owner: |
---|
| 181 | ac.owner = owner |
---|
[5121] | 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] | 244 | def 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] | 255 | class 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 | """ |
---|
[6932] | 296 | # School fee, clearance and hostel application batches start with 0. |
---|
| 297 | # These batches are being emptily created during initialization of the |
---|
| 298 | # university instance. |
---|
| 299 | if prefix in ('CLR', 'SFE', 'HOS'): |
---|
| 300 | num = 0 |
---|
| 301 | else: |
---|
| 302 | num = 1 |
---|
[5116] | 303 | while self.get('%s-%s' % (prefix, num), None) is not None: |
---|
[5086] | 304 | num += 1 |
---|
| 305 | return num |
---|
[5095] | 306 | |
---|
[5132] | 307 | def getImportFiles(self): |
---|
| 308 | """Return a generator with basenames of available import files. |
---|
| 309 | """ |
---|
| 310 | path = self._getStoragePath() |
---|
| 311 | for filename in sorted(os.listdir(path)): |
---|
| 312 | yield filename |
---|
[6124] | 313 | |
---|
[6449] | 314 | # This is temporary reimport solution. Access codes will be imported |
---|
[6470] | 315 | # with state initialized no matter if they have been used before. |
---|
[5132] | 316 | def reimport(self, filename, creator=u'UNKNOWN'): |
---|
| 317 | """Reimport a batch given in CSV file. |
---|
| 318 | |
---|
| 319 | CSV file must be of format as generated by createCSVLogFile |
---|
| 320 | method. |
---|
| 321 | """ |
---|
| 322 | path = os.path.join(self._getStoragePath(), filename) |
---|
| 323 | reader = csv.DictReader(open(path, 'rb'), quoting=csv.QUOTE_ALL) |
---|
| 324 | entry = reader.next() |
---|
[6449] | 325 | cost = float(entry['serial']) |
---|
[5132] | 326 | num = int(entry['ac']) |
---|
[6449] | 327 | prefix = entry['prefix'] |
---|
| 328 | batch_name = '%s-%s' % (prefix, num) |
---|
[5132] | 329 | if batch_name in self.keys(): |
---|
| 330 | raise KeyError('Batch already exists: %s' % batch_name) |
---|
| 331 | batch = AccessCodeBatch( |
---|
[6449] | 332 | datetime.now(), creator, prefix, cost, 0, num=num) |
---|
[5132] | 333 | num_entries = 0 |
---|
[6417] | 334 | self[batch_name] = batch |
---|
[5132] | 335 | for row in reader: |
---|
| 336 | pin = row['ac'] |
---|
| 337 | serial = int(row['serial']) |
---|
| 338 | rand_num = pin.rsplit('-', 1)[-1] |
---|
| 339 | batch.addAccessCode(serial, rand_num) |
---|
| 340 | num_entries += 1 |
---|
| 341 | batch.entry_num = num_entries |
---|
[6417] | 342 | |
---|
[5132] | 343 | batch.createCSVLogFile() |
---|
| 344 | return |
---|
[5149] | 345 | |
---|
[5153] | 346 | def getAccessCode(self, ac_id): |
---|
| 347 | """Get the AccessCode with ID ``ac_id`` or ``KeyError``. |
---|
| 348 | """ |
---|
| 349 | for batchname in self.keys(): |
---|
| 350 | batch = self[batchname] |
---|
| 351 | try: |
---|
| 352 | return batch.getAccessCode(ac_id) |
---|
| 353 | except KeyError: |
---|
| 354 | continue |
---|
| 355 | return None |
---|
[6124] | 356 | |
---|
[6458] | 357 | def disable(self, ac_id, comment=None): |
---|
[5153] | 358 | """Disable the AC with ID ``ac_id``. |
---|
| 359 | |
---|
| 360 | ``user_id`` is the user ID of the user triggering the |
---|
| 361 | process. Already disabled ACs are left untouched. |
---|
| 362 | """ |
---|
| 363 | ac = self.getAccessCode(ac_id) |
---|
| 364 | if ac is None: |
---|
| 365 | return |
---|
[6458] | 366 | disable_accesscode(ac_id, comment) |
---|
[5153] | 367 | return |
---|
| 368 | |
---|
[6458] | 369 | def enable(self, ac_id, comment=None): |
---|
[5153] | 370 | """(Re-)enable the AC with ID ``ac_id``. |
---|
| 371 | |
---|
| 372 | This leaves the given AC in state ``unused``. Already enabled |
---|
| 373 | ACs are left untouched. |
---|
| 374 | """ |
---|
| 375 | ac = self.getAccessCode(ac_id) |
---|
| 376 | if ac is None: |
---|
| 377 | return |
---|
[6458] | 378 | reenable_accesscode(ac_id, comment) |
---|
[5153] | 379 | return |
---|
| 380 | |
---|
[5073] | 381 | class AccessCodePlugin(grok.GlobalUtility): |
---|
| 382 | grok.name('accesscodes') |
---|
| 383 | grok.implements(IWAeUPSIRPPluggable) |
---|
| 384 | |
---|
| 385 | def setup(self, site, name, logger): |
---|
[6932] | 386 | basecontainer = AccessCodeBatchContainer() |
---|
| 387 | site['accesscodes'] = basecontainer |
---|
[5079] | 388 | logger.info('Installed container for access code batches.') |
---|
[6933] | 389 | # Create empty school fee, clearance and hostel application AC |
---|
| 390 | # batches during initialization of university instance. |
---|
[6932] | 391 | cost = 0.0 |
---|
| 392 | creator = 'system' |
---|
| 393 | entry_num = 0 |
---|
| 394 | creation_date = datetime.now() |
---|
| 395 | basecontainer.createBatch(creation_date, creator, |
---|
[6933] | 396 | 'SFE', cost, entry_num) |
---|
[6932] | 397 | basecontainer.createBatch(creation_date, creator, |
---|
[6933] | 398 | 'CLR', cost, entry_num) |
---|
[6932] | 399 | basecontainer.createBatch(creation_date, creator, |
---|
[6933] | 400 | 'HOS', cost, entry_num) |
---|
| 401 | logger.info('Installed empty SFE, CLR and HOS access code batches.') |
---|
[5079] | 402 | return |
---|
[5073] | 403 | |
---|
| 404 | def update(self, site, name, logger): |
---|
[5107] | 405 | if not 'accesscodes' in site.keys(): |
---|
| 406 | logger.info('Updating site at %s. Installing access codes.' % ( |
---|
| 407 | site,)) |
---|
| 408 | self.setup(site, name, logger) |
---|
| 409 | else: |
---|
| 410 | logger.info( |
---|
| 411 | 'AccessCodePlugin: Updating site at %s: Nothing to do.' % ( |
---|
| 412 | site, )) |
---|
| 413 | return |
---|
[5447] | 414 | |
---|
| 415 | def get_access_code(access_code): |
---|
| 416 | """Get an access code instance. |
---|
| 417 | |
---|
| 418 | An access code here is a string like ``PUDE-1-1234567890``. |
---|
[6124] | 419 | |
---|
[5447] | 420 | Returns ``None`` if the given code cannot be found. |
---|
| 421 | |
---|
| 422 | This is a convenicence function that is faster than looking up a |
---|
| 423 | batch container for the approriate access code. |
---|
| 424 | """ |
---|
| 425 | site = grok.getSite() |
---|
| 426 | if not isinstance(access_code, basestring): |
---|
| 427 | return None |
---|
| 428 | try: |
---|
| 429 | batch_id, ac_id = access_code.rsplit('-', 1) |
---|
| 430 | except: |
---|
| 431 | return None |
---|
[5467] | 432 | batch = site['accesscodes'].get(batch_id, None) |
---|
| 433 | if batch is None: |
---|
[5447] | 434 | return None |
---|
| 435 | try: |
---|
| 436 | code = batch.getAccessCode(access_code) |
---|
| 437 | except KeyError: |
---|
| 438 | return None |
---|
| 439 | return code |
---|
[6359] | 440 | |
---|
[6927] | 441 | def fire_transition(access_code, arg, toward=False, comment=None, owner=None): |
---|
[6408] | 442 | """Fire workflow transition for access code. |
---|
| 443 | |
---|
| 444 | The access code instance is looked up via `access_code` (a string |
---|
| 445 | like ``APP-1-12345678``). |
---|
| 446 | |
---|
| 447 | `arg` tells what kind of transition to trigger. This will be a |
---|
| 448 | transition id like ``'use'`` or ``'init'``, or some transition |
---|
[6493] | 449 | target like :data:`waeup.sirp.accesscodes.workflow.INITIALIZED`. |
---|
[6408] | 450 | |
---|
| 451 | If `toward` is ``False`` (the default) you have to pass a |
---|
| 452 | transition id as `arg`, otherwise you must give a transition |
---|
| 453 | target. |
---|
| 454 | |
---|
[6420] | 455 | If `comment` is specified (default is ``None``) the given string |
---|
| 456 | will be passed along as transition comment. It will appear in the |
---|
| 457 | history of the changed access code. You can use this to place |
---|
| 458 | remarks like for which object the access code was used or similar. |
---|
| 459 | |
---|
[6927] | 460 | If `owner` is specified, the owner attribute of the access code is checked. |
---|
| 461 | If the owner is different :func:`fire_transition` fails and returns False. |
---|
| 462 | |
---|
[6408] | 463 | :func:`fire_transition` might raise exceptions depending on the |
---|
| 464 | reason why the requested transition cannot be performed. |
---|
| 465 | |
---|
| 466 | The following exceptions can occur during processing: |
---|
| 467 | |
---|
| 468 | :exc:`KeyError`: |
---|
| 469 | signals not existent access code, batch or site. |
---|
| 470 | |
---|
| 471 | :exc:`ValueError`: |
---|
| 472 | signals illegal format of `access_code` string. The regular format is |
---|
| 473 | ``APP-N-XXXXXXXX``. |
---|
| 474 | |
---|
| 475 | :exc:`hurry.workflow.interfaces.InvalidTransitionError`: |
---|
| 476 | the transition requested cannot be performed because the workflow |
---|
| 477 | rules forbid it. |
---|
| 478 | |
---|
| 479 | :exc:`Unauthorized`: |
---|
| 480 | the current user is not allowed to perform the requested transition. |
---|
| 481 | |
---|
| 482 | """ |
---|
[6374] | 483 | try: |
---|
[6408] | 484 | batch_id, ac_id = access_code.rsplit('-', 1) |
---|
| 485 | except ValueError: |
---|
[6588] | 486 | raise ValueError( |
---|
| 487 | 'Invalid access code format: %s (use: APP-N-XXXXXXXX)' % ( |
---|
| 488 | access_code,)) |
---|
[6408] | 489 | try: |
---|
| 490 | ac = grok.getSite()['accesscodes'][batch_id].getAccessCode(access_code) |
---|
[6588] | 491 | except TypeError: |
---|
| 492 | raise KeyError( |
---|
| 493 | 'No site available for looking up accesscodes') |
---|
[6927] | 494 | if owner: |
---|
| 495 | ac_owner = getattr(ac, 'owner', None) |
---|
| 496 | if ac_owner and ac_owner != owner: |
---|
| 497 | return False |
---|
[6408] | 498 | info = IWorkflowInfo(ac) |
---|
| 499 | if toward: |
---|
[6420] | 500 | info.fireTransitionToward(arg, comment=comment) |
---|
[6408] | 501 | else: |
---|
[6420] | 502 | info.fireTransition(arg, comment=comment) |
---|
[6374] | 503 | return True |
---|
| 504 | |
---|
[6927] | 505 | def invalidate_accesscode(access_code, comment=None, owner=None): |
---|
[6374] | 506 | """Invalidate AccessCode denoted by string ``access_code``. |
---|
| 507 | |
---|
| 508 | Fires an appropriate transition to perform the task. |
---|
| 509 | |
---|
[6420] | 510 | `comment` is a string that will appear in the access code |
---|
| 511 | history. |
---|
| 512 | |
---|
[6408] | 513 | See :func:`fire_transition` for possible exceptions and their |
---|
| 514 | meanings. |
---|
[6374] | 515 | """ |
---|
[6588] | 516 | try: |
---|
[6927] | 517 | return fire_transition(access_code, 'use', comment=comment, owner=owner) |
---|
[6588] | 518 | except: |
---|
| 519 | return False |
---|
[6359] | 520 | |
---|
[6420] | 521 | def disable_accesscode(access_code, comment=None): |
---|
[6374] | 522 | """Disable AccessCode denoted by string ``access_code``. |
---|
| 523 | |
---|
| 524 | Fires an appropriate transition to perform the task. |
---|
| 525 | |
---|
[6420] | 526 | `comment` is a string that will appear in the access code |
---|
| 527 | history. |
---|
| 528 | |
---|
[6408] | 529 | See :func:`fire_transition` for possible exceptions and their |
---|
| 530 | meanings. |
---|
[6374] | 531 | """ |
---|
[6420] | 532 | return fire_transition( |
---|
| 533 | access_code, DISABLED, toward=True, comment=comment) |
---|
[6359] | 534 | |
---|
[6420] | 535 | def reenable_accesscode(access_code, comment=None): |
---|
[6374] | 536 | """Reenable AccessCode denoted by string ``access_code``. |
---|
| 537 | |
---|
| 538 | Fires an appropriate transition to perform the task. |
---|
| 539 | |
---|
[6420] | 540 | `comment` is a string that will appear in the access code |
---|
| 541 | history. |
---|
| 542 | |
---|
[6408] | 543 | See :func:`fire_transition` for possible exceptions and their |
---|
| 544 | meanings. |
---|
[6374] | 545 | """ |
---|
[6420] | 546 | return fire_transition(access_code, 'reenable', comment=comment) |
---|
[6936] | 547 | |
---|
[6937] | 548 | def create_accesscode(batch_prefix, batch_num, owner): |
---|
[6936] | 549 | """ |
---|
| 550 | """ |
---|
| 551 | batch_id = '%s-%s' % (batch_prefix, batch_num) |
---|
| 552 | try: |
---|
| 553 | batch = grok.getSite()['accesscodes'][batch_id] |
---|
| 554 | except KeyError: |
---|
[6939] | 555 | return None, u'No AC batch available.' |
---|
[6936] | 556 | rand_num = list(batch.getNewRandomNum())[0] |
---|
| 557 | #import pdb; pdb.set_trace() |
---|
| 558 | num = len(batch) + 1 |
---|
| 559 | batch.addAccessCode(num, rand_num, owner) |
---|
[6945] | 560 | batch.entry_num += 1 |
---|
[6936] | 561 | pin = u'%s-%s-%s' % (batch_prefix,batch_num,rand_num) |
---|
| 562 | return pin, None |
---|