source: WAeUP_SRP/trunk/Widgets.py @ 1813

Last change on this file since 1813 was 1805, checked in by Henrik Bettermann, 18 years ago

preparations for viewing CEST results

  • Property svn:keywords set to Id
File size: 41.0 KB
RevLine 
[47]1#-*- mode: python; mode: fold -*-
[990]2# $Id: Widgets.py 1805 2007-05-22 20:46:45Z henrik $
[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):
[1793]129                err = 'Course %s already exists' % (value)
[381]130            elif value not in c_ids:
[1793]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:
[1793]161                err = 'Course %s already exists' % (value)
[551]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
[1804]177class WAeUPSessionWidget(CPSSelectWidget): ###(
178    """WAeUP Session widget."""
179    meta_type = 'WAeUP Session Widget'
180
181    def _getSessions(self):
182        current_year = DateTime().year()
183        d = {'xx': 'unknown'}
184        for y in range(current_year - 9,current_year + 1):
185            d['%s' % str(y)[-2:]] = '%4d/%4d' % (y,y+1)
186        return d
187
188    def validate(self, datastructure, **kw):
189        """Validate datastructure and update datamodel."""
190        widget_id = self.getWidgetId()
191        value = datastructure[widget_id]
192        try:
193            v = str(value)
194        except ValueError:
195            datastructure.setError(widget_id, "'%s' not a valid session key" % value)
196            return 0
[1805]197
[1804]198        if len(v) == 1:
199            v = value = '0%c' % v
200        elif not value:
201            v = value = self.getSessionId()[-2:]
202        #import pdb;pdb.set_trace()
203        sessions = self._getSessions()
204        if not sessions.has_key(value):
205            datastructure.setError(widget_id, "'%s' not a valid session key" % v)
206            return 0
207        if self.is_required and not len(v):
208            datastructure.setError(widget_id, "session key required")
209            return 0
210
211        datamodel = datastructure.getDataModel()
212        datamodel[self.fields[0]] = v
213        return 1
214
215    def render(self, mode, datastructure, **kw):
216        """Render in mode from datastructure."""
217        value = datastructure[self.getWidgetId()]
218        sessions = self._getSessions()
219        if mode == 'view':
220            return escape(sessions.get(value, value))
221        elif mode == 'edit':
222            html_widget_id = self.getHtmlWidgetId()
223            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
224            in_selection = 0
225            vocabulary_items = sessions.items()
226            if self.sorted:
227                vocabulary_items.sort(key=operator.itemgetter(1))
228            for k, v in vocabulary_items:
229                kw = {'value': k, 'contents': v}
230                if value == k:
231                    kw['selected'] = 'selected'
232                    in_selection = 1
233                res += renderHtmlTag('option', **kw)
234            if value and not in_selection:
235                kw = {'value': value, 'contents': 'invalid: '+ str(value),
236                      'selected': 'selected'}
237                res += renderHtmlTag('option', **kw)
238            res += '</select>'
239            return res
240        raise RuntimeError('unknown mode %s' % mode)
241
242InitializeClass(WAeUPSessionWidget)
243
244widgetRegistry.register(WAeUPSessionWidget)
245
246###)
247
248class WAeUPLevelWidget(CPSSelectWidget): ###(
249    """WAeUP Level Widget."""
250    meta_type = 'WAeUP Level Widget'
251
252    def _getLevels(self):
253        d = {'999':'unknown'}
254        for y in range(100,800,100):
255            d['%s' % str(y)] = 'Year %1d (%3d Level)' % (y/100,y)
256        return d
257
258    def validate(self, datastructure, **kw):
259        """Validate datastructure and update datamodel."""
260        widget_id = self.getWidgetId()
261        value = datastructure[widget_id]
262        try:
263            v = str(value)
264        except ValueError:
265            datastructure.setError(widget_id, "'%s' not a valid level key" % value)
266            return 0
[1805]267
268        if not value:
[1804]269            v = value = '100'
270        #import pdb;pdb.set_trace()
271        levels = self._getLevels()
272        if not levels.has_key(value):
273            datastructure.setError(widget_id, "'%s' not a valid level" % v)
274            return 0
275        if self.is_required and not len(v):
276            datastructure.setError(widget_id, "level key required")
277            return 0
278
279        datamodel = datastructure.getDataModel()
280        datamodel[self.fields[0]] = v
281        return 1
282
283    def render(self, mode, datastructure, **kw):
284        """Render in mode from datastructure."""
285        value = datastructure[self.getWidgetId()]
286        levels = self._getLevels()
287        if mode == 'view':
288            return escape(levels.get(value, value))
289        elif mode == 'edit':
290            html_widget_id = self.getHtmlWidgetId()
291            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
292            in_selection = 0
293            vocabulary_items = levels.items()
294            if self.sorted:
295                vocabulary_items.sort(key=operator.itemgetter(1))
296            for k, v in vocabulary_items:
297                kw = {'value': k, 'contents': v}
298                if value == k:
299                    kw['selected'] = 'selected'
300                    in_selection = 1
301                res += renderHtmlTag('option', **kw)
302            if value and not in_selection:
303                kw = {'value': value, 'contents': 'invalid: '+ str(value),
304                      'selected': 'selected'}
305                res += renderHtmlTag('option', **kw)
306            res += '</select>'
307            return res
308        raise RuntimeError('unknown mode %s' % mode)
309
310InitializeClass(WAeUPLevelWidget)
311
312widgetRegistry.register(WAeUPLevelWidget)
313
314###)
315
316class WAeUPVerdictWidget(CPSSelectWidget): ###(
317    """WAeUP Verdict widget."""
318    meta_type = 'WAeUP Verdict Widget'
319
320    # XXX make a menu for the vocabulary.
321    vocabulary = 'verdicts'
322    translated = False
323    sorted = False
324
325    # Associating the widget label with an input area to improve the widget
326    # accessibility.
327    has_input_area = True
328
329    def _getVerdicts(self,datastructure):
330        voc = getattr(self.portal_vocabularies,self.vocabulary)
331        d = {}
332        for k,v in voc.items():
333            d[k] = v
334        return d
335
336    def validate(self, datastructure, **kw):
337        """Validate datastructure and update datamodel."""
338        widget_id = self.getWidgetId()
339        value = datastructure[widget_id]
340        try:
341            v = str(value)
342        except ValueError:
343            datastructure.setError(widget_id, "'%s' not a valid verdict key" % value)
344            return 0
345        #import pdb;pdb.set_trace()
346        verdicts = self._getVerdicts(datastructure)
347        if not value:
348            v = value = verdicts['N/A']
349        if not verdicts.has_key(value):
350            datastructure.setError(widget_id, "'%s' not a valid verdict key" % v)
351            return 0
352        if self.is_required and not len(v):
353            datastructure.setError(widget_id, "verdict required")
354            return 0
355
356        datamodel = datastructure.getDataModel()
357        datamodel[self.fields[0]] = v
358        return 1
359
360    def render(self, mode, datastructure, **kw):
361        """Render in mode from datastructure."""
362        value = datastructure[self.getWidgetId()]
363        verdicts = self._getVerdicts(datastructure)
364        if mode == 'view':
365            return escape(verdicts.get(value, value))
366        elif mode == 'edit':
367            html_widget_id = self.getHtmlWidgetId()
368            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
369            in_selection = 0
370            vocabulary_items = verdicts.items()
371            if self.sorted:
372                vocabulary_items.sort(key=operator.itemgetter(1))
373            for k, v in vocabulary_items:
374                kw = {'value': k, 'contents': v}
375                if value == k:
376                    kw['selected'] = 'selected'
377                    in_selection = 1
378                res += renderHtmlTag('option', **kw)
379            if value and not in_selection:
380                kw = {'value': value, 'contents': 'invalid: '+ str(value),
381                      'selected': 'selected'}
382                res += renderHtmlTag('option', **kw)
383            res += '</select>'
384            return res
385        raise RuntimeError('unknown mode %s' % mode)
386
387InitializeClass(WAeUPVerdictWidget)
388
389widgetRegistry.register(WAeUPVerdictWidget)
390
391###)
392
[714]393class WAeUPReservedRoomsWidget(CPSStringWidget): ###(
394    """ WAeUPReservedRooms Widget"""
395    meta_type = "WAeUPReservedRooms Widget"
396
397    def validate(self, datastructure, **kw):
398        """Validate datastructure and update datamodel."""
399        import re
400        valid = CPSStringWidget.validate(self, datastructure, **kw)
401        if not valid:
402            return 0
403        else:
404            widget_id = self.getWidgetId()
405            value = datastructure[widget_id]
406            err = 0
407            try:
[926]408                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
[714]409                                     if r]
[1038]410            except (ValueError,IndexError),msg:
[714]411                err = str(msg)
412            if err:
413                datastructure.setError(widget_id, err)
414            else:
415                datamodel = datastructure.getDataModel()
416                datamodel[self.fields[0]] = value
417            return not err
418
419InitializeClass(WAeUPReservedRoomsWidget)
420
421widgetRegistry.register(WAeUPReservedRoomsWidget)
422###)
423
[388]424class WAeUPIdWidget(CPSStringWidget): ###(
425    """ WAeUPId Widget"""
426    meta_type = "WAeUPId Widget"
[444]427
[388]428    def validate(self, datastructure, **kw):
429        """Validate datastructure and update datamodel."""
[444]430
[388]431        valid = CPSStringWidget.validate(self, datastructure, **kw)
[422]432        id_pat_str = r"\S"
433        inv_id_pat = compile(r"^%s$" % id_pat_str)
[388]434        if not valid:
435            return 0
436        else:
[586]437            portal_type_query = {'query':['Faculty',
438                                          'Department',
439                                          'Course',
440                                          'Certificate',
441                                          'CertificateCourse',]}
[388]442            widget_id = self.getWidgetId()
443            value = datastructure[widget_id].upper()
444            err = 0
[440]445            if len(value.split()) > 1:
[783]446                err = 'Invalid Id, Id contains space(s).'
[586]447            elif self.portal_catalog(portal_type=portal_type_query,id=value):
[1718]448                brain = self.portal_catalog(portal_type=portal_type_query,id=value)[0]
[1783]449                err = 'An %s object with the Id %s already exists at %s.'\
[1718]450                      % (brain.portal_type,value,brain.getPath())
[388]451            if err:
452                datastructure.setError(widget_id, err)
453            else:
454                datamodel = datastructure.getDataModel()
455                datamodel[self.fields[0]] = value
[444]456
[388]457            return not err
458
459InitializeClass(WAeUPIdWidget)
460
461widgetRegistry.register(WAeUPIdWidget)
462
463
464###)
465
[1025]466class StudyCourseWidget(CPSStringWidget): ###(
467    """ StudyCourse Widget"""
468    meta_type = "StudyCourse Widget"
469
470    def validate(self, datastructure, **kw):
471        """Validate datastructure and update datamodel."""
472        #from Products.zdb import set_trace
473        #set_trace()
[1747]474##        valid = CPSStringWidget.validate(self, datastructure, **kw)
475##        if not valid:
476##            return 0
477        widget_id = self.getWidgetId()
478        value = makeCertificateCode(datastructure[widget_id]).upper()
[1025]479        id_pat_str = r"\S"
480        inv_id_pat = compile(r"^%s$" % id_pat_str)
[1747]481        err = 0
482        if len(value.split()) > 1:
483            err = 'Invalid Id, Id contains space(s).'
484        elif not self.portal_catalog(portal_type='Certificate',id=value):
485            err = 'No such certificate'
486        if err:
487            datastructure.setError(widget_id, err)
[1025]488        else:
[1747]489            datamodel = datastructure.getDataModel()
490            datamodel[self.fields[0]] = value
491        return not err
[1025]492
493InitializeClass(StudyCourseWidget)
494
495widgetRegistry.register(StudyCourseWidget)
496###)
497
[463]498class JambRegNoWidget(CPSStringWidget): ###(
499    """ JambRegNo Widget"""
500    meta_type = "JambRegNo Widget"
[1169]501    _properties = CPSStringWidget._properties + (
502        {'id': 'catalog', 'type': 'string', 'mode': 'w',
503         'label': 'Catalog to search'},
504         {'id': 'reference', 'type': 'string', 'mode': 'w',
505         'label': 'Reference Field'},
506         )
507    catalog = "portal_pumeresults" #the catalog to search for jamb_reg_no
508    reference = ""
[463]509    digits = 8
510    digits_str = "N"*digits
511    letters = 2
512    letters_str = "L"*letters
513    def validate(self, datastructure, **kw):
514        """Validate datastructure and update datamodel."""
515        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1169]516        jamb_nr_catalog = getattr(self,self.catalog)
517        widget_id = self.getWidgetId()
518        value = datastructure[widget_id].upper()
519        err = 0
520        if not valid: #or not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
521            #err = 'Invalid number, the expected format is: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
[1793]522            err = 'Invalid number'
[1169]523        elif self.reference == '':
524            #s = getStudentByRegNo(self,value)
525            pume = jamb_nr_catalog(jamb_reg_no = value)
526            if len(pume) < 1:
[1805]527                err = 'No student record with registration number %s.' %value
[1169]528            else:
529                datastructure['pume'] = pume[0]
[463]530        else:
[1169]531            #import pdb;pdb.set_trace()
532            record = datastructure[self.reference]
533            #jamb_reg_no = getattr(record,widget_id)
534            jamb_reg_no = record.Entryregno
535            if jamb_reg_no != value:
[1783]536                err = 'Registration number does not match.'
[1169]537        if err:
538            datastructure.setError(widget_id, err)
539        else:
540            datamodel = datastructure.getDataModel()
541            datamodel[self.fields[0]] = value
542        return not err
[463]543
544InitializeClass(JambRegNoWidget)
545
546widgetRegistry.register(JambRegNoWidget)
[47]547###)
548
[1175]549class SecretWidget(CPSStringWidget): ###(
550    """ Secret Widget"""
551    meta_type = "Secret Widget"
552    _properties = CPSStringWidget._properties + (
553        {'id': 'reference', 'type': 'string', 'mode': 'w',
554         'label': 'Reference Record'},
555         {'id': 'check_fields', 'type': 'tokens', 'mode': 'w',
556         'label': 'Fields to check'},
557         )
558    reference = "student"
[1747]559    matric_no_catalog = 'returning_import'
[1175]560    check_fields = ("Firstname", "Middlename","Lastname")
561    def validate(self, datastructure, **kw):
562        """Validate datastructure and update datamodel."""
[1571]563        logger = logging.getLogger('Widgets.SecretWidget.validate')
[1175]564        valid = CPSStringWidget.validate(self, datastructure, **kw)
565        widget_id = self.getWidgetId()
566        value = datastructure[widget_id].upper()
567        err = 0
[1189]568        record = datastructure.get(self.reference,None)
[1747]569        #import pdb;pdb.set_trace()
[1379]570        if not valid or len(value) < 2:
[1793]571            err = 'Invalid string'
[1189]572        elif not record or datastructure.errors:
[1177]573            err = 0
[1175]574        else:
575            found = False
576            cvs = []
577            for field in self.check_fields:
578                cv = getattr(record,field).upper()
[1243]579                if len(cv.split()) > 1:
580                    for splited in cv.split():
[1747]581                        cvs.append(splited.strip())
[1243]582                else:
583                    cvs.append(cv)
[1747]584            for cv in cvs:
[1175]585                if cv  == value.upper():
586                    found = True
587                    break
588            matric_no = record.matric_no
589            name = " ".join(cvs)
590            if not found:
[1573]591                logger.info('%(matric_no)s did not find %(value)s in %(name)s' % vars())
592                err = 'No name does match.'
[1175]593            else:
[1571]594                logger.info('%(matric_no)s found %(value)s in %(name)s' % vars())
[1175]595        if err:
596            datastructure.setError(widget_id, err)
597        else:
598            datamodel = datastructure.getDataModel()
599            datamodel[self.fields[0]] = value
600        return not err
601
602InitializeClass(SecretWidget)
603
604widgetRegistry.register(SecretWidget)
605###)
606
[1804]607class WAeUPSexWidget(CPSBooleanWidget): ###(
[1772]608    """WAeUP sex widget."""
609    meta_type = 'WAeUP Sex Widget'
610
611    def validate(self, datastructure, **kw):
612        """Validate datastructure and update datamodel."""
613        value = datastructure[self.getWidgetId()]
614
615        if self.render_format not in self.render_formats:
616            self.render_format = 'select'
617
618        female = value in ('F','f','Female','female',"True",True)
619        male = value in ('M','m','Male','male','False',False)
620        if not female and not male:
621            datastructure.setError(self.getWidgetId(),
622                                   "invalid sex %s" % value)
623            return 0
624        elif female:
625            v = True
626        else:
627            v = False
628        datamodel = datastructure.getDataModel()
629        datamodel[self.fields[0]] = v
630        return 1
631
632InitializeClass(WAeUPSexWidget)
633
634widgetRegistry.register(WAeUPSexWidget)
635
[1804]636###)
637
[1146]638class MatricNoWidget(CPSStringWidget): ###(
639    """ MatricNo Widget"""
640    meta_type = "MatricNo Widget"
[1747]641
642    _properties = CPSStringWidget._properties + (
643        {'id': 'matric_no_catalog', 'type': 'string', 'mode': 'w',
644         'label': 'Catalog to search for MatricNo'},
645        { 'id': 'results_catalog', 'type': 'string', 'mode': 'w',
646         'label': 'Results Catalog'},
647         )
648    matric_no_catalog = "" #the catalog to search for matric_no
[1748]649    results_catalog = "results_import" #results catalog
[1747]650
[1146]651    def validate(self, datastructure, **kw):
652        """Validate datastructure and update datamodel."""
[1747]653        #import pdb;pdb.set_trace()
[1146]654        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1571]655        logger = logging.getLogger('Widgets.MatricNoWidget.validate')
[1747]656        returning = getattr(self,self.matric_no_catalog)
657        results = getattr(self,self.results_catalog,None)
[1146]658        err = 0
[1189]659        widget_id = self.getWidgetId()
660        value = datastructure[widget_id]
661        if not valid or not value:
[1793]662            err = 'Invalid string %s' % value
[1573]663            logger.info('Invalid matric_no string %s' % value)
[1146]664        else:
[1189]665            value = value.upper()
[1177]666            datastructure['student'] = None
[1146]667            while not err:
[1151]668                res = returning(matric_no = value)
[1146]669                if len(res) < 1:
[1573]670                    logger.info('matric_no %s not found' % value)
[1793]671                    err = 'No student with Matriculation Number %s' % (value)
[1747]672                    break
[1146]673                datastructure['student'] = res[0]
[1747]674                if results is not None:
675                    res = results(matric_no = value)
676                    if len(res) < 1:
[1793]677                        err = 'No results for Matriculation Number %s' % (value)
[1747]678                        continue
679                    datastructure['results'] = res
[1146]680                break
[1189]681        if err:
682            datastructure.setError(widget_id, err)
683        else:
684            datamodel = datastructure.getDataModel()
685            datamodel[self.fields[0]] = value
686        return not err
[1146]687
688InitializeClass(MatricNoWidget)
689
690widgetRegistry.register(MatricNoWidget)
691###)
692
[1393]693class StudentIdWidget(CPSStringWidget): ###(
694    """ StudentId Widget"""
695    meta_type = "StudentId Widget"
696    def validate(self, datastructure, **kw):
697        """Validate datastructure and update datamodel."""
698        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1571]699        logger = logging.getLogger('Widgets.StudentIdWidget.validate')
[1393]700        #import pdb;pdb.set_trace()
701        s_cat = self.students_catalog
702        err = 0
703        widget_id = self.getWidgetId()
704        value = datastructure[widget_id]
705        if not valid or not value:
[1793]706            err = 'Invalid Id string %s' % value
[1573]707            logger.info('Invalid id string %s' % value)
[1449]708            datastructure['student'] = None
[1393]709        else:
710            value = value.upper()
711            res = s_cat(id = value)
712            if not res:
[1573]713                logger.info('Student id %s not found' % value)
[1793]714                err = 'No student with Id %s' % (value)
[1393]715                datastructure['student'] = None
716            else:
717                datastructure['student'] = res[0]
718        if err:
719            datastructure.setError(widget_id, err)
720        else:
721            datamodel = datastructure.getDataModel()
722            datamodel[self.fields[0]] = value
723        return not err
724
725InitializeClass(StudentIdWidget)
726
727widgetRegistry.register(StudentIdWidget)
728###)
729
[1146]730class WAeUPMultilineResultsWidget(CPSStringWidget): ###(
731    """ WAeUPMultilineResults Widget"""
732    meta_type = "WAeUp Multiline Results Widget"
733    _properties = CPSWidget._properties + (
734        {'id': 'nr_of_lines', 'type': 'int', 'mode': 'w',
735         'label': 'Nr of Lines'},
736         )
737    nr_of_lines = 5
738    def prepare(self, datastructure, **kw): ###(
739        """Prepare datastructure from datamodel."""
740        datamodel = datastructure.getDataModel()
741        #import pdb;pdb.set_trace()
742        widget_id = self.getWidgetId()
743        v = datamodel[self.fields[0]]
744        if type(v) is ListType and v:
745            nr_results = len(v)
746        else:
747            v = []
748            nr_results = 0
749        count = 1
750        for s,g in v:
751            wid = "%s%02d"% (widget_id,count)
752            datastructure[wid+'_s'] = s
753            datastructure[wid+'_g'] = g
754            count += 1
755        if nr_results < self.nr_of_lines:
756            for line in range(nr_results,self.nr_of_lines):
757                v.append(('',''))
758                wid = "%s%02d"% (widget_id,line)
759                datastructure[wid+'_s'] = ''
760                datastructure[wid+'_g'] = ''
761        datastructure[widget_id] = v
762        datastructure[widget_id+'_s'] = ''
763        datastructure[widget_id+'_g'] = ''
764    ###)
765
766    def validate(self, datastructure, **kw): ###(
767        """Validate datastructure and update datamodel."""
768        #import pdb;pdb.set_trace()
769        widget_id = self.getWidgetId()
770        err = 0
771        lines = []
772        for line in range(1,30):
773            wid = "%s%02d"% (widget_id,line)
774            if not datastructure.has_key(wid+'_s'):
775                break
776            lines.append((datastructure[wid+'_s'].strip(),
777                         datastructure[wid+'_g'].strip()))
[1155]778
[1146]779        s = datastructure[widget_id+'_s'].strip()
780        g = datastructure[widget_id+'_g'].strip()
781        if s and g:
782            lines.append((s,g))
783        active = []
784        for s,g in lines:
785            if g != "":
786                active.append((s,g))
787        if err:
788            datastructure.setError(widget_id, err)
789        else:
790            datamodel = datastructure.getDataModel()
791            datamodel[self.fields[0]] = active
792        return not err
793    ###)
794
795    def render(self, mode, datastructure, **kw): ###(
796        """Render in mode from datastructure."""
797        render_method = 'widget_waeup_multiline_result_render'
798        meth = getattr(self, render_method, None)
799        if meth is None:
800            raise RuntimeError("Unknown Render Method %s for widget type %s"
801                               % (render_method, self.getId()))
802        #import pdb;pdb.set_trace()
803        datamodel = datastructure.getDataModel()
804        widget_id = self.getWidgetId()
805        lines = datamodel[self.fields[0]]
806        if len(lines) < self.nr_of_lines:
807            for line in range(len(lines),self.nr_of_lines + 1):
808                lines.append(('',''))
809        datastructure[widget_id] = lines
810        datastructure[widget_id+'_s'] = ''
811        datastructure[widget_id+'_g'] = ''
812##        count = 1
813##        for s,g in v:
814##            wid = "%s%02d"% (widget_id,count)
815##            count += 1
816        return meth(mode=mode,
817                    datastructure=datastructure,
818                    )
819    ###)
820
821
822InitializeClass(WAeUPMultilineResultsWidget)
823widgetRegistry.register(WAeUPMultilineResultsWidget)
824###)
825
[794]826class WAeUPResultsWidget(CPSStringWidget): ###(
827    """ WAeUPResults Widget"""
828    meta_type = "WAeUp Results Widget"
829
830    def prepare(self, datastructure, **kw): ###(
831        """Prepare datastructure from datamodel."""
832        datamodel = datastructure.getDataModel()
833        v = datamodel[self.fields[0]]
834        #import pdb;pdb.set_trace()
835        widget_id = self.getWidgetId()
[807]836        datastructure[widget_id] = v
[794]837        datastructure[widget_id+'_s'] = ''
838        datastructure[widget_id+'_g'] = ''
839    ###)
840
841    def validate(self, datastructure, **kw): ###(
842        """Validate datastructure and update datamodel."""
[807]843        #import pdb;pdb.set_trace()
[794]844        widget_id = self.getWidgetId()
845        v = datastructure[widget_id]
846        err = 0
847        s = datastructure[widget_id+'_s'].strip()
848        g = datastructure[widget_id+'_g'].strip()
[807]849        while 1:
850            if not s and g:
[1793]851                err = "No subject grade for subject %s " % s
[807]852                break
853            i = 0
854            done = False
855            for sv,gv in v:
856                if sv == s:
857                    done = True
858                    if not g:
859                        v.pop(i)
860                        break
861                    v[i] = (s,g)
862                    break
863                i += 1
864            if done:
865                break
866            if s and g:
867                v.append((s,g))
868            break
[794]869        if err:
870            datastructure.setError(widget_id, err)
871        else:
872            datamodel = datastructure.getDataModel()
873            datamodel[self.fields[0]] = v
874            datastructure[widget_id+'_s'] = s
875            datastructure[widget_id+'_g'] = g
876        return not err
877    ###)
878
879    def render(self, mode, datastructure, **kw): ###(
880        """Render in mode from datastructure."""
881        render_method = 'widget_waeup_result_render'
882        meth = getattr(self, render_method, None)
883        if meth is None:
884            raise RuntimeError("Unknown Render Method %s for widget type %s"
885                               % (render_method, self.getId()))
886        #import pdb;pdb.set_trace()
887        datamodel = datastructure.getDataModel()
888        widget_id = self.getWidgetId()
889        datastructure[widget_id+'_s'] = ''
890        datastructure[widget_id+'_g'] = ''
891        return meth(mode=mode,
892                    datastructure=datastructure,
893                    )
894    ###)
895
896
897InitializeClass(WAeUPResultsWidget)
898widgetRegistry.register(WAeUPResultsWidget)
899###)
900
[488]901class ScratchCardPin: ###(
902    """the ScratchCardPin"""
903    def __init__(self,prefix,batch_no,number):
[990]904        if not batch_no and not number:
905            s = prefix
[996]906            if len(s) > 3:
[990]907                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
908            else:
[996]909                prefix,batch_no,number = s,'',''
[488]910        self.p = prefix
911        self.b = batch_no
912        self.n = number
913
914    def __str__(self):
915        return "%s-%s-%s" % (self.p,self.b,self.n)
[1146]916
917    def __repr__(self):
918        return "%s%s%s" % (self.p,self.b,self.n)
[488]919###)
920
[47]921class ScratchcardPinWidget(CPSStringWidget): ###(
[22]922    """ ScratchcardPin Widget"""
[199]923    meta_type = "Scratchcard Pin Widget"
[488]924    _properties = CPSWidget._properties + (
925        {'id': 'prefix', 'type': 'string', 'mode': 'w',
926         'label': 'Prefix'},
927         {'id': 'reference', 'type': 'string', 'mode': 'w',
928         'label': 'Reference Field'},
929        )
930    prefix = ''
931    reference = ''
[502]932    def prepare(self, datastructure, **kw): ###(
[488]933        """Prepare datastructure from datamodel."""
934        datamodel = datastructure.getDataModel()
935        v = datamodel[self.fields[0]]
936        widget_id = self.getWidgetId()
[742]937        #import pdb;pdb.set_trace()
[747]938        if v and type(v) is StringType:
[990]939            try:
940                p,b,n = v.split('-')
941                v = ScratchCardPin(p,b,n)
942            except ValueError:
943                v = ScratchCardPin(v,'','')
[488]944        if v:
[742]945            p = '%s' % v.p
[488]946            b = '%s' % v.b
947            n = '%s' % v.n
948        else:
[742]949            p = self.prefix
950            if p.startswith('@'):
951                p = getattr(self,self.prefix[1:])()
[488]952            b = n = ''
[742]953            v = ScratchCardPin(p,b,n)
[488]954        datastructure[widget_id] = v
[742]955        datastructure[widget_id+'_p'] = p
[488]956        datastructure[widget_id+'_b'] = b
957        datastructure[widget_id+'_n'] = n
[1376]958    ###)
[758]959
[1169]960    def validate(self, datastructure, **kw): ###(
[22]961        """Validate datastructure and update datamodel."""
[1571]962        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
[488]963        widget_id = self.getWidgetId()
964        v = datastructure[widget_id]
[996]965        #import pdb;pdb.set_trace()
[488]966        err = 0
[742]967        prefix= self.prefix
968        if prefix.startswith('@'):
969            prefix= getattr(self,self.prefix[1:])()
[488]970        b = datastructure[widget_id+'_b'].strip()
971        n = datastructure[widget_id+'_n'].strip()
[502]972        pins = self.portal_pins
[742]973        pin = "%(prefix)s%(b)s%(n)s" % vars()
[1376]974        pin_str = "%(prefix)s-%(b)-s%(n)s" % vars()
[816]975        do = 1
[1025]976        s_id = str(self.portal_membership.getAuthenticatedMember())
[1326]977        #import pdb;pdb.set_trace()
[1343]978        if self.isStaff():
[1326]979            do = 0
980            err ='You are not a Student. PIN neither checked nor used.'
[1571]981            s_logger.info('%s tried to use scratch card %s' % (s_id,pin_str))
[1557]982        elif len(b) > 1 and b.find('-') > -1:
983            do = 0
[1573]984            err = 'PIN must not contain "-"'
985            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1557]986        elif n.find('-') > -1:
987            do = 0
[1573]988            err = 'PIN must not contain "-"'
989            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1376]990        elif len(n) != 10:
991            do = 0
[1793]992            err = 'Invalid PIN length %d' % len(n)
[1573]993            s_logger.info('%s entered invalid PIN with length %d' % (s_id,len(n)))
[1326]994        elif self.reference == "":
[1030]995            ref = s_id
[635]996        else:
997            ref = datastructure[self.reference]
[843]998            if datastructure.errors:
[816]999                do = 0
[1805]1000                datastructure.setError(widget_id, 'PIN neither checked nor used.')
[1571]1001                s_logger.info('%s/%s entered wrong data together with PIN %s' % (s_id,ref,pin_str))
[816]1002        while do:
1003            ok = pins.searchAndSetRecord(pin,ref,prefix)
[1030]1004            if ok < -2 or ok > 2:
1005                err = 'Unknown error, please report!'
[1571]1006                s_logger.info('%s/%s caused unknown error with PIN %s' % (s_id,ref,pin_str))
[1030]1007                break
1008            elif ok == -2:
[1783]1009                err = 'Service already is activated but with a different PIN.'
[1571]1010                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (s_id,ref,pin_str))
[710]1011                break
1012            elif ok == -1:
[1793]1013                err = 'Invalid PIN'
[1571]1014                s_logger.info('%s/%s entered invalid PIN %s' % (s_id,ref,pin_str))
[502]1015                break
1016            if ok == 0:
[1571]1017                err = 'PIN already used'
1018                s_logger.info('%s/%s entered used PIN %s' % (s_id,ref,pin_str))
[502]1019                break
1020            if ok >= 1:
[710]1021                #import pdb;pdb.set_trace()
[635]1022                if self.isStudent():
[992]1023                    if self.reference == "jamb_reg_no":
[997]1024                        err = "You are already logged in."
[1573]1025                        s_logger.info('%s/%s checked admission with PIN %s though logged in' % (s_id,ref,pin_str))
[992]1026                        break
[1082]1027                    if ok == 1:
[1571]1028                        s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[1032]1029                    else:
[1571]1030                        s_logger.info('%s/%s repeatedly used PIN %s' % (s_id,ref,pin_str))
[637]1031                    break
[635]1032                else:
1033                    student = getStudentByRegNo(self,ref)
[1571]1034                    s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[502]1035                if student is None:
[1793]1036                    err = "Student not found"
[1571]1037                    s_logger.info('%s not found in admission list' % (ref))
[502]1038                    break
[648]1039                s_id = student.getId()
[502]1040                if ok == 2:
[990]1041                    if self.reference == "jamb_reg_no":
1042                        if hasattr(self.portal_directories.students,s_id):
1043                            err = "Please login with your Student Id %s and 10-digit PIN." % s_id
[1571]1044                            s_logger.info('%s/%s repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]1045                            break
1046                        else:
[1571]1047                            s_logger.info('%s/%s (non-member) repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]1048                    else:
[1793]1049                        err = "Unknown error" % s_id
[1571]1050                        s_logger.info('%s/%s repeatedly activated service with PIN %s' % (s_id,ref,pin_str))
[986]1051                        break
1052                try:
1053                    student.getContent().makeStudentMember(s_id,password=pin[4:])
[1571]1054                    s_logger.info('%s/%s has been created using PIN %s' % (s_id,ref,pin_str))
[986]1055                except:
[989]1056                    err = "Please login with your Student Id %s and 10-digit PIN." % s_id
[1571]1057                    s_logger.info('%s/%s could not be made a member with PIN %s' % (s_id,ref,pin_str))
[986]1058                    break
[502]1059            break
[488]1060        if err:
1061            datastructure.setError(widget_id, err)
1062        else:
1063            datamodel = datastructure.getDataModel()
[742]1064            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
1065            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
1066            datastructure[widget_id+'_p'] = prefix
[488]1067            datastructure[widget_id+'_b'] = b
1068            datastructure[widget_id+'_n'] = n
[502]1069            datastructure['s_id'] = s_id
[488]1070        return not err
[444]1071
[1169]1072###)
1073
[502]1074    def render(self, mode, datastructure, **kw): ###(
[488]1075        """Render in mode from datastructure."""
1076        render_method = 'widget_scratch_card_pin_render'
1077        meth = getattr(self, render_method, None)
1078        if meth is None:
1079            raise RuntimeError("Unknown Render Method %s for widget type %s"
1080                               % (render_method, self.getId()))
1081
1082        # XXX AT: datastructure has to be set again here, in case we're in edit
1083        # or create mode, because a default value has to be provided.
1084        #import pdb;pdb.set_trace()
1085        datamodel = datastructure.getDataModel()
1086        v = datamodel[self.fields[0]]
[502]1087        if v and type(v) is StringType:
[990]1088            try:
1089                p,b,n = v.split('-')
1090                v = ScratchCardPin(p,b,n)
1091            except ValueError:
[996]1092                v = ScratchCardPin(self.prefix,'1',v)
1093                pass
[488]1094        if v:
[742]1095            prefix= '%s' % v.p
[488]1096            b = '%s' % v.b
1097            n = '%s' % v.n
[22]1098        else:
[742]1099            prefix= self.prefix
1100            if prefix.startswith('@'):
1101                prefix= getattr(self,self.prefix[1:])()
[488]1102            b = n = ''
[742]1103            v = ScratchCardPin(prefix,b,n)
1104        widget_id = self.getWidgetId()
1105        datastructure[widget_id] = v
1106        datastructure[widget_id+'_p'] = prefix
1107        datastructure[widget_id+'_b'] = b
1108        datastructure[widget_id+'_n'] = n
[758]1109        return meth(mode=mode,
1110                    datastructure=datastructure,
[488]1111                    )
[523]1112    ###)
[488]1113
1114
[22]1115InitializeClass(ScratchcardPinWidget)
[199]1116widgetRegistry.register(ScratchcardPinWidget)
[22]1117
[47]1118
1119###)
1120
[1169]1121class WAeUPImageWidget(CPSImageWidget): ###(
[537]1122    """Photo widget."""
1123    meta_type = 'WAeUP Image Widget'
1124
1125    def render(self, mode, datastructure, **kw):
1126        render_method = 'widget_waeup_image_render'
1127        meth = getattr(self, render_method, None)
1128        if meth is None:
1129            raise RuntimeError("Unknown Render Method %s for widget type %s"
1130                               % (render_method, self.getId()))
1131        img_info = self.getImageInfo(datastructure)
1132        return meth(mode=mode, datastructure=datastructure, **img_info)
1133
1134InitializeClass(WAeUPImageWidget)
1135
1136widgetRegistry.register(WAeUPImageWidget)
[1804]1137###)
[537]1138
1139
[22]1140###########
1141
Note: See TracBrowser for help on using the repository browser.