source: WAeUP_SRP/trunk/Widgets.py @ 1781

Last change on this file since 1781 was 1772, checked in by joachim, 18 years ago

some fixes for addStudent and importStudent

  • Property svn:keywords set to Id
File size: 33.5 KB
RevLine 
[47]1#-*- mode: python; mode: fold -*-
[990]2# $Id: Widgets.py 1772 2007-05-11 12:00:10Z joachim $
[295]3from cgi import escape
[502]4from types import *
[22]5from Globals import InitializeClass
[199]6##from Products.CPSSchemas.Widget import CPSWidgetType
[295]7from Products.CMFCore.utils import getToolByName
[1772]8from Products.CPSSchemas.BasicWidgets import CPSBooleanWidget, CPSWidget, CPSStringWidget, CPSEmailWidget,CPSImageWidget
[295]9from Products.CPSSchemas.BasicWidgets import renderHtmlTag,CPSSelectWidget, CPSStringWidget
[22]10from Products.CPSSchemas.ExtendedWidgets import CPSDateTimeWidget
[199]11from Products.CPSSchemas.Widget import widgetRegistry
12##from Products.CPSSchemas.WidgetTypesTool import WidgetTypeRegistry
[22]13from DateTime.DateTime import DateTime
14from AccessControl import getSecurityManager
[502]15from Products.WAeUP_SRP.Students import getStudentByRegNo
[1747]16from Products.WAeUP_SRP.Academics import makeCertificateCode
[22]17from re import compile
[952]18import logging
[22]19
[952]20#from zLOG import LOG, DEBUG
[22]21
[295]22class CPSSelectWidgetForRecord(CPSSelectWidget): ###(
23    """Select widget. with record names"""
24    meta_type = 'Select Widget for Records'
25
26    field_types = ('CPS String Field',)
27    field_inits = ({'is_searchabletext': 1,},)
28
29    _properties = CPSSelectWidget._properties + (
30        {'id': 'record_id', 'type': 'string', 'mode': 'w',
31         'label': 'Record Id', 'is_required' : 1},
32        )
33
34    def render(self, mode, datastructure, **kw):
35        """Render in mode from datastructure."""
36        value = datastructure[self.getWidgetId()]
37        vocabulary = self._getVocabulary(datastructure)
38        portal = getToolByName(self, 'portal_url').getPortalObject()
39        cpsmcat = portal.translation_service
40        if mode == 'view':
41            if self.translated:
42                return escape(cpsmcat(vocabulary.getMsgid(value, value)).encode('ISO-8859-15', 'ignore'))
43            else:
44                return escape(vocabulary.get(value, value))
45        elif mode == 'edit':
46            html_widget_id = self.getHtmlWidgetId()
[444]47            res = renderHtmlTag('select',
48                                name='%s.%s:records' % (self.record_id,html_widget_id),
[295]49                                id=html_widget_id)
50            in_selection = 0
51            for k, v in vocabulary.items():
52                if self.translated:
53                    kw = {'value': k,
54                          'contents': cpsmcat(vocabulary.getMsgid(k, k)).encode('ISO-8859-15', 'ignore')
55                          }
56                else:
57                    kw = {'value': k, 'contents': v}
58                if value == k:
59                    kw['selected'] = 'selected'
60                    in_selection = 1
61                res += renderHtmlTag('option', **kw)
62            if value and not in_selection:
63                kw = {'value': value, 'contents': 'invalid: '+ str(value),
64                      'selected': 'selected'}
65                res += renderHtmlTag('option', **kw)
66            res += '</select>'
67            return res
68        raise RuntimeError('unknown mode %s' % mode)
69
70InitializeClass(CPSSelectWidgetForRecord)
71
72widgetRegistry.register(CPSSelectWidgetForRecord)
73
74###)
75
[373]76class CPSStringWidgetForRecord(CPSStringWidget): ###(
[295]77    """String widget."""
78    meta_type = 'String Widget For Record'
79
80    field_types = ('CPS String Field',)
81    field_inits = ({'is_searchabletext': 1,},)
82    _properties = CPSStringWidget._properties + (
83        {'id': 'record_id', 'type': 'string', 'mode': 'w',
84         'label': 'Record Id', 'is_required' : 1},
85        )
86
87    def render(self, mode, datastructure, **kw):
88        """Render in mode from datastructure."""
89        value = datastructure[self.getWidgetId()]
90        if mode == 'view':
91            return escape(value)
92        elif mode == 'edit':
93            # XXX TODO should use an other name than kw !
94            # XXX change this everywhere
95            html_widget_id = self.getHtmlWidgetId()
96            kw = {'type': 'text',
97                  'id'  : html_widget_id,
[444]98                  'name': '%s.%s:records' % (self.record_id,html_widget_id),
[295]99                  'value': escape(value),
100                  'size': self.display_width,
101                  }
102            if self.size_max:
103                kw['maxlength'] = self.size_max
104            return renderHtmlTag('input', **kw)
105        raise RuntimeError('unknown mode %s' % mode)
106
107InitializeClass(CPSStringWidgetForRecord)
108
109widgetRegistry.register(CPSStringWidgetForRecord)
110
[373]111###)
112
113class CertificateCourseIdWidget(CPSStringWidget): ###(
114    """ CertificateCourseId Widget"""
115    meta_type = "CertificateCourseId Widget"
[444]116
[373]117    def validate(self, datastructure, **kw):
118        """Validate datastructure and update datamodel."""
[444]119
[373]120        valid = CPSStringWidget.validate(self, datastructure, **kw)
121        if not valid:
122            return 0
123        else:
124            widget_id = self.getWidgetId()
125            value = datastructure[widget_id].upper()
126            err = 0
127            c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
[381]128            if hasattr(self.aq_parent,value):
[444]129                err = 'Course %s already exists' % (value)
[381]130            elif value not in c_ids:
[444]131                err = 'Course %s does not exist' % (value)
[373]132            if err:
133                datastructure.setError(widget_id, err)
134            else:
135                datamodel = datastructure.getDataModel()
136                datamodel[self.fields[0]] = value
[444]137
[373]138            return not err
139
140InitializeClass(CertificateCourseIdWidget)
141
142widgetRegistry.register(CertificateCourseIdWidget)
[551]143###)
[373]144
[551]145class CourseIdWidget(CPSStringWidget): ###(
146    """ CourseId Widget"""
147    meta_type = "CourseId Widget"
148
149    def validate(self, datastructure, **kw):
150        """Validate datastructure and update datamodel."""
151
152        valid = CPSStringWidget.validate(self, datastructure, **kw)
153        if not valid:
154            return 0
155        else:
156            widget_id = self.getWidgetId()
157            value = datastructure[widget_id].upper()
158            err = 0
159            res = self.portal_catalog(meta_type= "Course",id = value)
160            if len(res) > 0:
161                err = 'Course %s already exists' % (value)
162            if err:
163                datastructure.setError(widget_id, err)
164            else:
165                datamodel = datastructure.getDataModel()
166                datamodel[self.fields[0]] = value
167
168            return not err
169
170InitializeClass(CourseIdWidget)
171
172widgetRegistry.register(CourseIdWidget)
173
174
[373]175###)
176
[714]177class WAeUPReservedRoomsWidget(CPSStringWidget): ###(
178    """ WAeUPReservedRooms Widget"""
179    meta_type = "WAeUPReservedRooms Widget"
180
181    def validate(self, datastructure, **kw):
182        """Validate datastructure and update datamodel."""
183        import re
184        valid = CPSStringWidget.validate(self, datastructure, **kw)
185        if not valid:
186            return 0
187        else:
188            widget_id = self.getWidgetId()
189            value = datastructure[widget_id]
190            err = 0
191            try:
[926]192                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
[714]193                                     if r]
[1038]194            except (ValueError,IndexError),msg:
[714]195                err = str(msg)
196            if err:
197                datastructure.setError(widget_id, err)
198            else:
199                datamodel = datastructure.getDataModel()
200                datamodel[self.fields[0]] = value
201            return not err
202
203InitializeClass(WAeUPReservedRoomsWidget)
204
205widgetRegistry.register(WAeUPReservedRoomsWidget)
206###)
207
[388]208class WAeUPIdWidget(CPSStringWidget): ###(
209    """ WAeUPId Widget"""
210    meta_type = "WAeUPId Widget"
[444]211
[388]212    def validate(self, datastructure, **kw):
213        """Validate datastructure and update datamodel."""
[444]214
[388]215        valid = CPSStringWidget.validate(self, datastructure, **kw)
[422]216        id_pat_str = r"\S"
217        inv_id_pat = compile(r"^%s$" % id_pat_str)
[388]218        if not valid:
219            return 0
220        else:
[586]221            portal_type_query = {'query':['Faculty',
222                                          'Department',
223                                          'Course',
224                                          'Certificate',
225                                          'CertificateCourse',]}
[388]226            widget_id = self.getWidgetId()
227            value = datastructure[widget_id].upper()
228            err = 0
[440]229            if len(value.split()) > 1:
[783]230                err = 'Invalid Id, Id contains space(s).'
[586]231            elif self.portal_catalog(portal_type=portal_type_query,id=value):
[1718]232                brain = self.portal_catalog(portal_type=portal_type_query,id=value)[0]
233                err = 'An %s object with the Id %s already exists at %s'\
234                      % (brain.portal_type,value,brain.getPath())
[388]235            if err:
236                datastructure.setError(widget_id, err)
237            else:
238                datamodel = datastructure.getDataModel()
239                datamodel[self.fields[0]] = value
[444]240
[388]241            return not err
242
243InitializeClass(WAeUPIdWidget)
244
245widgetRegistry.register(WAeUPIdWidget)
246
247
248###)
249
[1025]250class StudyCourseWidget(CPSStringWidget): ###(
251    """ StudyCourse Widget"""
252    meta_type = "StudyCourse Widget"
253
254    def validate(self, datastructure, **kw):
255        """Validate datastructure and update datamodel."""
256        #from Products.zdb import set_trace
257        #set_trace()
[1747]258##        valid = CPSStringWidget.validate(self, datastructure, **kw)
259##        if not valid:
260##            return 0
261        widget_id = self.getWidgetId()
262        value = makeCertificateCode(datastructure[widget_id]).upper()
[1025]263        id_pat_str = r"\S"
264        inv_id_pat = compile(r"^%s$" % id_pat_str)
[1747]265        err = 0
266        if len(value.split()) > 1:
267            err = 'Invalid Id, Id contains space(s).'
268        elif not self.portal_catalog(portal_type='Certificate',id=value):
269            err = 'No such certificate'
270        if err:
271            datastructure.setError(widget_id, err)
[1025]272        else:
[1747]273            datamodel = datastructure.getDataModel()
274            datamodel[self.fields[0]] = value
275        return not err
[1025]276
277InitializeClass(StudyCourseWidget)
278
279widgetRegistry.register(StudyCourseWidget)
280###)
281
[463]282class JambRegNoWidget(CPSStringWidget): ###(
283    """ JambRegNo Widget"""
284    meta_type = "JambRegNo Widget"
[1169]285    _properties = CPSStringWidget._properties + (
286        {'id': 'catalog', 'type': 'string', 'mode': 'w',
287         'label': 'Catalog to search'},
288         {'id': 'reference', 'type': 'string', 'mode': 'w',
289         'label': 'Reference Field'},
290         )
291    catalog = "portal_pumeresults" #the catalog to search for jamb_reg_no
292    reference = ""
[463]293    digits = 8
294    digits_str = "N"*digits
295    letters = 2
296    letters_str = "L"*letters
297    def validate(self, datastructure, **kw):
298        """Validate datastructure and update datamodel."""
299        valid = CPSStringWidget.validate(self, datastructure, **kw)
[816]300        #import pdb;pdb.set_trace()
[1169]301        jamb_nr_catalog = getattr(self,self.catalog)
302        widget_id = self.getWidgetId()
303        value = datastructure[widget_id].upper()
304        err = 0
305        if not valid: #or not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
306            #err = 'Invalid number, the expected format is: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
307            err = 'Invalid number'
308        elif self.reference == '':
309            #s = getStudentByRegNo(self,value)
310            pume = jamb_nr_catalog(jamb_reg_no = value)
311            if len(pume) < 1:
312                err = 'No Student with JAMB RegNo %s.' % (value)
313            else:
314                datastructure['pume'] = pume[0]
[463]315        else:
[1169]316            #import pdb;pdb.set_trace()
317            record = datastructure[self.reference]
318            #jamb_reg_no = getattr(record,widget_id)
319            jamb_reg_no = record.Entryregno
320            if jamb_reg_no != value:
321                err = 'Entry Registration Nr does not match.'
322        if err:
323            datastructure.setError(widget_id, err)
324        else:
325            datamodel = datastructure.getDataModel()
326            datamodel[self.fields[0]] = value
327        return not err
[463]328
329InitializeClass(JambRegNoWidget)
330
331widgetRegistry.register(JambRegNoWidget)
[47]332###)
333
[1175]334class SecretWidget(CPSStringWidget): ###(
335    """ Secret Widget"""
336    meta_type = "Secret Widget"
337    _properties = CPSStringWidget._properties + (
338        {'id': 'reference', 'type': 'string', 'mode': 'w',
339         'label': 'Reference Record'},
340         {'id': 'check_fields', 'type': 'tokens', 'mode': 'w',
341         'label': 'Fields to check'},
342         )
343    reference = "student"
[1747]344    matric_no_catalog = 'returning_import'
[1175]345    check_fields = ("Firstname", "Middlename","Lastname")
346    def validate(self, datastructure, **kw):
347        """Validate datastructure and update datamodel."""
[1571]348        logger = logging.getLogger('Widgets.SecretWidget.validate')
[1175]349        valid = CPSStringWidget.validate(self, datastructure, **kw)
350        widget_id = self.getWidgetId()
351        value = datastructure[widget_id].upper()
352        err = 0
[1189]353        record = datastructure.get(self.reference,None)
[1747]354        #import pdb;pdb.set_trace()
[1379]355        if not valid or len(value) < 2:
[1175]356            err = 'Invalid String'
[1189]357        elif not record or datastructure.errors:
[1177]358            err = 0
[1175]359        else:
360            found = False
361            cvs = []
362            for field in self.check_fields:
363                cv = getattr(record,field).upper()
[1243]364                if len(cv.split()) > 1:
365                    for splited in cv.split():
[1747]366                        cvs.append(splited.strip())
[1243]367                else:
368                    cvs.append(cv)
[1747]369            for cv in cvs:
[1175]370                if cv  == value.upper():
371                    found = True
372                    break
373            matric_no = record.matric_no
374            name = " ".join(cvs)
375            if not found:
[1573]376                logger.info('%(matric_no)s did not find %(value)s in %(name)s' % vars())
377                err = 'No name does match.'
[1175]378            else:
[1571]379                logger.info('%(matric_no)s found %(value)s in %(name)s' % vars())
[1175]380        if err:
381            datastructure.setError(widget_id, err)
382        else:
383            datamodel = datastructure.getDataModel()
384            datamodel[self.fields[0]] = value
385        return not err
386
387InitializeClass(SecretWidget)
388
389widgetRegistry.register(SecretWidget)
390###)
391
[1772]392class WAeUPSexWidget(CPSBooleanWidget):
393    """WAeUP sex widget."""
394    meta_type = 'WAeUP Sex Widget'
395
396    def validate(self, datastructure, **kw):
397        """Validate datastructure and update datamodel."""
398        value = datastructure[self.getWidgetId()]
399
400        if self.render_format not in self.render_formats:
401            self.render_format = 'select'
402
403        female = value in ('F','f','Female','female',"True",True)
404        male = value in ('M','m','Male','male','False',False)
405        if not female and not male:
406            datastructure.setError(self.getWidgetId(),
407                                   "invalid sex %s" % value)
408            return 0
409        elif female:
410            v = True
411        else:
412            v = False
413        datamodel = datastructure.getDataModel()
414        datamodel[self.fields[0]] = v
415        return 1
416
417InitializeClass(WAeUPSexWidget)
418
419widgetRegistry.register(WAeUPSexWidget)
420
[1146]421class MatricNoWidget(CPSStringWidget): ###(
422    """ MatricNo Widget"""
423    meta_type = "MatricNo Widget"
[1747]424
425    _properties = CPSStringWidget._properties + (
426        {'id': 'matric_no_catalog', 'type': 'string', 'mode': 'w',
427         'label': 'Catalog to search for MatricNo'},
428        { 'id': 'results_catalog', 'type': 'string', 'mode': 'w',
429         'label': 'Results Catalog'},
430         )
431    matric_no_catalog = "" #the catalog to search for matric_no
[1748]432    results_catalog = "results_import" #results catalog
[1747]433
[1146]434    def validate(self, datastructure, **kw):
435        """Validate datastructure and update datamodel."""
[1747]436        #import pdb;pdb.set_trace()
[1146]437        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1571]438        logger = logging.getLogger('Widgets.MatricNoWidget.validate')
[1747]439        returning = getattr(self,self.matric_no_catalog)
440        results = getattr(self,self.results_catalog,None)
[1146]441        err = 0
[1189]442        widget_id = self.getWidgetId()
443        value = datastructure[widget_id]
444        if not valid or not value:
[1571]445            err = 'Invalid matric_no string %s.' % value
[1573]446            logger.info('Invalid matric_no string %s' % value)
[1146]447        else:
[1189]448            value = value.upper()
[1177]449            datastructure['student'] = None
[1146]450            while not err:
[1151]451                res = returning(matric_no = value)
[1146]452                if len(res) < 1:
[1573]453                    logger.info('matric_no %s not found' % value)
454                    err = 'No student with matric_no %s.' % (value)
[1747]455                    break
[1146]456                datastructure['student'] = res[0]
[1747]457                if results is not None:
458                    res = results(matric_no = value)
459                    if len(res) < 1:
460                        err = 'No results with matric_no %s.' % (value)
461                        continue
462                    datastructure['results'] = res
[1146]463                break
[1189]464        if err:
465            datastructure.setError(widget_id, err)
466        else:
467            datamodel = datastructure.getDataModel()
468            datamodel[self.fields[0]] = value
469        return not err
[1146]470
471InitializeClass(MatricNoWidget)
472
473widgetRegistry.register(MatricNoWidget)
474###)
475
[1393]476class StudentIdWidget(CPSStringWidget): ###(
477    """ StudentId Widget"""
478    meta_type = "StudentId Widget"
479    def validate(self, datastructure, **kw):
480        """Validate datastructure and update datamodel."""
481        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1571]482        logger = logging.getLogger('Widgets.StudentIdWidget.validate')
[1393]483        #import pdb;pdb.set_trace()
484        s_cat = self.students_catalog
485        err = 0
486        widget_id = self.getWidgetId()
487        value = datastructure[widget_id]
488        if not valid or not value:
[1571]489            err = 'Invalid id string %s.' % value
[1573]490            logger.info('Invalid id string %s' % value)
[1449]491            datastructure['student'] = None
[1393]492        else:
493            value = value.upper()
494            res = s_cat(id = value)
495            if not res:
[1573]496                logger.info('Student id %s not found' % value)
497                err = 'No student with id %s.' % (value)
[1393]498                datastructure['student'] = None
499            else:
500                datastructure['student'] = res[0]
501        if err:
502            datastructure.setError(widget_id, err)
503        else:
504            datamodel = datastructure.getDataModel()
505            datamodel[self.fields[0]] = value
506        return not err
507
508InitializeClass(StudentIdWidget)
509
510widgetRegistry.register(StudentIdWidget)
511###)
512
[1146]513class WAeUPMultilineResultsWidget(CPSStringWidget): ###(
514    """ WAeUPMultilineResults Widget"""
515    meta_type = "WAeUp Multiline Results Widget"
516    _properties = CPSWidget._properties + (
517        {'id': 'nr_of_lines', 'type': 'int', 'mode': 'w',
518         'label': 'Nr of Lines'},
519         )
520    nr_of_lines = 5
521    def prepare(self, datastructure, **kw): ###(
522        """Prepare datastructure from datamodel."""
523        datamodel = datastructure.getDataModel()
524        #import pdb;pdb.set_trace()
525        widget_id = self.getWidgetId()
526        v = datamodel[self.fields[0]]
527        if type(v) is ListType and v:
528            nr_results = len(v)
529        else:
530            v = []
531            nr_results = 0
532        count = 1
533        for s,g in v:
534            wid = "%s%02d"% (widget_id,count)
535            datastructure[wid+'_s'] = s
536            datastructure[wid+'_g'] = g
537            count += 1
538        if nr_results < self.nr_of_lines:
539            for line in range(nr_results,self.nr_of_lines):
540                v.append(('',''))
541                wid = "%s%02d"% (widget_id,line)
542                datastructure[wid+'_s'] = ''
543                datastructure[wid+'_g'] = ''
544        datastructure[widget_id] = v
545        datastructure[widget_id+'_s'] = ''
546        datastructure[widget_id+'_g'] = ''
547    ###)
548
549    def validate(self, datastructure, **kw): ###(
550        """Validate datastructure and update datamodel."""
551        #import pdb;pdb.set_trace()
552        widget_id = self.getWidgetId()
553        err = 0
554        lines = []
555        for line in range(1,30):
556            wid = "%s%02d"% (widget_id,line)
557            if not datastructure.has_key(wid+'_s'):
558                break
559            lines.append((datastructure[wid+'_s'].strip(),
560                         datastructure[wid+'_g'].strip()))
[1155]561
[1146]562        s = datastructure[widget_id+'_s'].strip()
563        g = datastructure[widget_id+'_g'].strip()
564        if s and g:
565            lines.append((s,g))
566        active = []
567        for s,g in lines:
568            if g != "":
569                active.append((s,g))
570        if err:
571            datastructure.setError(widget_id, err)
572        else:
573            datamodel = datastructure.getDataModel()
574            datamodel[self.fields[0]] = active
575        return not err
576    ###)
577
578    def render(self, mode, datastructure, **kw): ###(
579        """Render in mode from datastructure."""
580        render_method = 'widget_waeup_multiline_result_render'
581        meth = getattr(self, render_method, None)
582        if meth is None:
583            raise RuntimeError("Unknown Render Method %s for widget type %s"
584                               % (render_method, self.getId()))
585        #import pdb;pdb.set_trace()
586        datamodel = datastructure.getDataModel()
587        widget_id = self.getWidgetId()
588        lines = datamodel[self.fields[0]]
589        if len(lines) < self.nr_of_lines:
590            for line in range(len(lines),self.nr_of_lines + 1):
591                lines.append(('',''))
592        datastructure[widget_id] = lines
593        datastructure[widget_id+'_s'] = ''
594        datastructure[widget_id+'_g'] = ''
595##        count = 1
596##        for s,g in v:
597##            wid = "%s%02d"% (widget_id,count)
598##            count += 1
599        return meth(mode=mode,
600                    datastructure=datastructure,
601                    )
602    ###)
603
604
605InitializeClass(WAeUPMultilineResultsWidget)
606widgetRegistry.register(WAeUPMultilineResultsWidget)
607###)
608
[794]609class WAeUPResultsWidget(CPSStringWidget): ###(
610    """ WAeUPResults Widget"""
611    meta_type = "WAeUp Results Widget"
612
613    def prepare(self, datastructure, **kw): ###(
614        """Prepare datastructure from datamodel."""
615        datamodel = datastructure.getDataModel()
616        v = datamodel[self.fields[0]]
617        #import pdb;pdb.set_trace()
618        widget_id = self.getWidgetId()
[807]619        datastructure[widget_id] = v
[794]620        datastructure[widget_id+'_s'] = ''
621        datastructure[widget_id+'_g'] = ''
622    ###)
623
624    def validate(self, datastructure, **kw): ###(
625        """Validate datastructure and update datamodel."""
[807]626        #import pdb;pdb.set_trace()
[794]627        widget_id = self.getWidgetId()
628        v = datastructure[widget_id]
629        err = 0
630        s = datastructure[widget_id+'_s'].strip()
631        g = datastructure[widget_id+'_g'].strip()
[807]632        while 1:
633            if not s and g:
634                err = "no subject grad for subject %s " % s
635                break
636            i = 0
637            done = False
638            for sv,gv in v:
639                if sv == s:
640                    done = True
641                    if not g:
642                        v.pop(i)
643                        break
644                    v[i] = (s,g)
645                    break
646                i += 1
647            if done:
648                break
649            if s and g:
650                v.append((s,g))
651            break
[794]652        if err:
653            datastructure.setError(widget_id, err)
654        else:
655            datamodel = datastructure.getDataModel()
656            datamodel[self.fields[0]] = v
657            datastructure[widget_id+'_s'] = s
658            datastructure[widget_id+'_g'] = g
659        return not err
660    ###)
661
662    def render(self, mode, datastructure, **kw): ###(
663        """Render in mode from datastructure."""
664        render_method = 'widget_waeup_result_render'
665        meth = getattr(self, render_method, None)
666        if meth is None:
667            raise RuntimeError("Unknown Render Method %s for widget type %s"
668                               % (render_method, self.getId()))
669        #import pdb;pdb.set_trace()
670        datamodel = datastructure.getDataModel()
671        widget_id = self.getWidgetId()
672        datastructure[widget_id+'_s'] = ''
673        datastructure[widget_id+'_g'] = ''
674        return meth(mode=mode,
675                    datastructure=datastructure,
676                    )
677    ###)
678
679
680InitializeClass(WAeUPResultsWidget)
681widgetRegistry.register(WAeUPResultsWidget)
682###)
683
[488]684class ScratchCardPin: ###(
685    """the ScratchCardPin"""
686    def __init__(self,prefix,batch_no,number):
[990]687        if not batch_no and not number:
688            s = prefix
[996]689            if len(s) > 3:
[990]690                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
691            else:
[996]692                prefix,batch_no,number = s,'',''
[488]693        self.p = prefix
694        self.b = batch_no
695        self.n = number
696
697    def __str__(self):
698        return "%s-%s-%s" % (self.p,self.b,self.n)
[1146]699
700    def __repr__(self):
701        return "%s%s%s" % (self.p,self.b,self.n)
[488]702###)
703
[47]704class ScratchcardPinWidget(CPSStringWidget): ###(
[22]705    """ ScratchcardPin Widget"""
[199]706    meta_type = "Scratchcard Pin Widget"
[488]707    _properties = CPSWidget._properties + (
708        {'id': 'prefix', 'type': 'string', 'mode': 'w',
709         'label': 'Prefix'},
710         {'id': 'reference', 'type': 'string', 'mode': 'w',
711         'label': 'Reference Field'},
712        )
713    prefix = ''
714    reference = ''
[502]715    def prepare(self, datastructure, **kw): ###(
[488]716        """Prepare datastructure from datamodel."""
717        datamodel = datastructure.getDataModel()
718        v = datamodel[self.fields[0]]
719        widget_id = self.getWidgetId()
[742]720        #import pdb;pdb.set_trace()
[747]721        if v and type(v) is StringType:
[990]722            try:
723                p,b,n = v.split('-')
724                v = ScratchCardPin(p,b,n)
725            except ValueError:
726                v = ScratchCardPin(v,'','')
[488]727        if v:
[742]728            p = '%s' % v.p
[488]729            b = '%s' % v.b
730            n = '%s' % v.n
731        else:
[742]732            p = self.prefix
733            if p.startswith('@'):
734                p = getattr(self,self.prefix[1:])()
[488]735            b = n = ''
[742]736            v = ScratchCardPin(p,b,n)
[488]737        datastructure[widget_id] = v
[742]738        datastructure[widget_id+'_p'] = p
[488]739        datastructure[widget_id+'_b'] = b
740        datastructure[widget_id+'_n'] = n
[1376]741    ###)
[758]742
[1169]743    def validate(self, datastructure, **kw): ###(
[22]744        """Validate datastructure and update datamodel."""
[1571]745        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
[488]746        widget_id = self.getWidgetId()
747        v = datastructure[widget_id]
[996]748        #import pdb;pdb.set_trace()
[488]749        err = 0
[742]750        prefix= self.prefix
751        if prefix.startswith('@'):
752            prefix= getattr(self,self.prefix[1:])()
[488]753        b = datastructure[widget_id+'_b'].strip()
754        n = datastructure[widget_id+'_n'].strip()
[502]755        pins = self.portal_pins
[742]756        pin = "%(prefix)s%(b)s%(n)s" % vars()
[1376]757        pin_str = "%(prefix)s-%(b)-s%(n)s" % vars()
[816]758        do = 1
[1025]759        s_id = str(self.portal_membership.getAuthenticatedMember())
[1326]760        #import pdb;pdb.set_trace()
[1343]761        if self.isStaff():
[1326]762            do = 0
763            err ='You are not a Student. PIN neither checked nor used.'
[1571]764            s_logger.info('%s tried to use scratch card %s' % (s_id,pin_str))
[1557]765        elif len(b) > 1 and b.find('-') > -1:
766            do = 0
[1573]767            err = 'PIN must not contain "-"'
768            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1557]769        elif n.find('-') > -1:
770            do = 0
[1573]771            err = 'PIN must not contain "-"'
772            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1376]773        elif len(n) != 10:
774            do = 0
[1573]775            err = 'Invalid PIN length %d' % len(n)
776            s_logger.info('%s entered invalid PIN with length %d' % (s_id,len(n)))
[1326]777        elif self.reference == "":
[1030]778            ref = s_id
[635]779        else:
780            ref = datastructure[self.reference]
[843]781            if datastructure.errors:
[816]782                do = 0
[1571]783                datastructure.setError(widget_id, 'errors in other data, PIN neither checked nor used')
784                s_logger.info('%s/%s entered wrong data together with PIN %s' % (s_id,ref,pin_str))
[816]785        while do:
786            ok = pins.searchAndSetRecord(pin,ref,prefix)
[1030]787            if ok < -2 or ok > 2:
788                err = 'Unknown error, please report!'
[1571]789                s_logger.info('%s/%s caused unknown error with PIN %s' % (s_id,ref,pin_str))
[1030]790                break
791            elif ok == -2:
[819]792                err = 'Service already activated but with a different PIN.'
[1571]793                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (s_id,ref,pin_str))
[710]794                break
795            elif ok == -1:
[783]796                err = 'Invalid PIN'
[1571]797                s_logger.info('%s/%s entered invalid PIN %s' % (s_id,ref,pin_str))
[502]798                break
799            if ok == 0:
[1571]800                err = 'PIN already used'
801                s_logger.info('%s/%s entered used PIN %s' % (s_id,ref,pin_str))
[502]802                break
803            if ok >= 1:
[710]804                #import pdb;pdb.set_trace()
[635]805                if self.isStudent():
[992]806                    if self.reference == "jamb_reg_no":
[997]807                        err = "You are already logged in."
[1573]808                        s_logger.info('%s/%s checked admission with PIN %s though logged in' % (s_id,ref,pin_str))
[992]809                        break
[1082]810                    if ok == 1:
[1571]811                        s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[1032]812                    else:
[1571]813                        s_logger.info('%s/%s repeatedly used PIN %s' % (s_id,ref,pin_str))
[637]814                    break
[635]815                else:
816                    student = getStudentByRegNo(self,ref)
[1571]817                    s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[502]818                if student is None:
[796]819                    err = "Student not found."
[1571]820                    s_logger.info('%s not found in admission list' % (ref))
[502]821                    break
[648]822                s_id = student.getId()
[502]823                if ok == 2:
[990]824                    if self.reference == "jamb_reg_no":
825                        if hasattr(self.portal_directories.students,s_id):
826                            err = "Please login with your Student Id %s and 10-digit PIN." % s_id
[1571]827                            s_logger.info('%s/%s repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]828                            break
829                        else:
[1571]830                            s_logger.info('%s/%s (non-member) repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]831                    else:
[1030]832                        err = "Unknown error" % s_id
[1571]833                        s_logger.info('%s/%s repeatedly activated service with PIN %s' % (s_id,ref,pin_str))
[986]834                        break
835                try:
836                    student.getContent().makeStudentMember(s_id,password=pin[4:])
[1571]837                    s_logger.info('%s/%s has been created using PIN %s' % (s_id,ref,pin_str))
[986]838                except:
[989]839                    err = "Please login with your Student Id %s and 10-digit PIN." % s_id
[1571]840                    s_logger.info('%s/%s could not be made a member with PIN %s' % (s_id,ref,pin_str))
[986]841                    break
[502]842            break
[488]843        if err:
844            datastructure.setError(widget_id, err)
845        else:
846            datamodel = datastructure.getDataModel()
[742]847            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
848            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
849            datastructure[widget_id+'_p'] = prefix
[488]850            datastructure[widget_id+'_b'] = b
851            datastructure[widget_id+'_n'] = n
[502]852            datastructure['s_id'] = s_id
[488]853        return not err
[444]854
[1169]855###)
856
[502]857    def render(self, mode, datastructure, **kw): ###(
[488]858        """Render in mode from datastructure."""
859        render_method = 'widget_scratch_card_pin_render'
860        meth = getattr(self, render_method, None)
861        if meth is None:
862            raise RuntimeError("Unknown Render Method %s for widget type %s"
863                               % (render_method, self.getId()))
864
865        # XXX AT: datastructure has to be set again here, in case we're in edit
866        # or create mode, because a default value has to be provided.
867        #import pdb;pdb.set_trace()
868        datamodel = datastructure.getDataModel()
869        v = datamodel[self.fields[0]]
[502]870        if v and type(v) is StringType:
[990]871            try:
872                p,b,n = v.split('-')
873                v = ScratchCardPin(p,b,n)
874            except ValueError:
[996]875                v = ScratchCardPin(self.prefix,'1',v)
876                pass
[488]877        if v:
[742]878            prefix= '%s' % v.p
[488]879            b = '%s' % v.b
880            n = '%s' % v.n
[22]881        else:
[742]882            prefix= self.prefix
883            if prefix.startswith('@'):
884                prefix= getattr(self,self.prefix[1:])()
[488]885            b = n = ''
[742]886            v = ScratchCardPin(prefix,b,n)
887        widget_id = self.getWidgetId()
888        datastructure[widget_id] = v
889        datastructure[widget_id+'_p'] = prefix
890        datastructure[widget_id+'_b'] = b
891        datastructure[widget_id+'_n'] = n
[758]892        return meth(mode=mode,
893                    datastructure=datastructure,
[488]894                    )
[523]895    ###)
[488]896
897
[22]898InitializeClass(ScratchcardPinWidget)
[199]899widgetRegistry.register(ScratchcardPinWidget)
[22]900
[47]901
902###)
903
[1169]904class WAeUPImageWidget(CPSImageWidget): ###(
[537]905    """Photo widget."""
906    meta_type = 'WAeUP Image Widget'
907
908    def render(self, mode, datastructure, **kw):
909        render_method = 'widget_waeup_image_render'
910        meth = getattr(self, render_method, None)
911        if meth is None:
912            raise RuntimeError("Unknown Render Method %s for widget type %s"
913                               % (render_method, self.getId()))
914        img_info = self.getImageInfo(datastructure)
915        return meth(mode=mode, datastructure=datastructure, **img_info)
916
[1169]917###)
[537]918
919
[1169]920
[537]921InitializeClass(WAeUPImageWidget)
922
923widgetRegistry.register(WAeUPImageWidget)
924
925
[22]926###########
927
Note: See TracBrowser for help on using the repository browser.