source: WAeUP_SRP/trunk/Widgets.py @ 1804

Last change on this file since 1804 was 1804, checked in by joachim, 17 years ago

fix for #205, add more widgets for import_data

  • Property svn:keywords set to Id
File size: 41.0 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Widgets.py 1804 2007-05-22 17:55:24Z joachim $
3from cgi import escape
4from types import *
5from Globals import InitializeClass
6##from Products.CPSSchemas.Widget import CPSWidgetType
7from Products.CMFCore.utils import getToolByName
8from Products.CPSSchemas.BasicWidgets import CPSBooleanWidget, CPSWidget, CPSStringWidget, CPSEmailWidget,CPSImageWidget
9from Products.CPSSchemas.BasicWidgets import renderHtmlTag,CPSSelectWidget, CPSStringWidget
10from Products.CPSSchemas.ExtendedWidgets import CPSDateTimeWidget
11from Products.CPSSchemas.Widget import widgetRegistry
12##from Products.CPSSchemas.WidgetTypesTool import WidgetTypeRegistry
13from DateTime.DateTime import DateTime
14from AccessControl import getSecurityManager
15from Products.WAeUP_SRP.Students import getStudentByRegNo
16from Products.WAeUP_SRP.Academics import makeCertificateCode
17from re import compile
18import logging
19
20#from zLOG import LOG, DEBUG
21
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()
47            res = renderHtmlTag('select',
48                                name='%s.%s:records' % (self.record_id,html_widget_id),
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
76class CPSStringWidgetForRecord(CPSStringWidget): ###(
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,
98                  'name': '%s.%s:records' % (self.record_id,html_widget_id),
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
111###)
112
113class CertificateCourseIdWidget(CPSStringWidget): ###(
114    """ CertificateCourseId Widget"""
115    meta_type = "CertificateCourseId Widget"
116
117    def validate(self, datastructure, **kw):
118        """Validate datastructure and update datamodel."""
119
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"})]
128            if hasattr(self.aq_parent,value):
129                err = 'Course %s already exists' % (value)
130            elif value not in c_ids:
131                err = 'Course %s does not exist' % (value)
132            if err:
133                datastructure.setError(widget_id, err)
134            else:
135                datamodel = datastructure.getDataModel()
136                datamodel[self.fields[0]] = value
137
138            return not err
139
140InitializeClass(CertificateCourseIdWidget)
141
142widgetRegistry.register(CertificateCourseIdWidget)
143###)
144
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
175###)
176
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
197       
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
267       
268        if not value:
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
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:
408                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
409                                     if r]
410            except (ValueError,IndexError),msg:
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
424class WAeUPIdWidget(CPSStringWidget): ###(
425    """ WAeUPId Widget"""
426    meta_type = "WAeUPId Widget"
427
428    def validate(self, datastructure, **kw):
429        """Validate datastructure and update datamodel."""
430
431        valid = CPSStringWidget.validate(self, datastructure, **kw)
432        id_pat_str = r"\S"
433        inv_id_pat = compile(r"^%s$" % id_pat_str)
434        if not valid:
435            return 0
436        else:
437            portal_type_query = {'query':['Faculty',
438                                          'Department',
439                                          'Course',
440                                          'Certificate',
441                                          'CertificateCourse',]}
442            widget_id = self.getWidgetId()
443            value = datastructure[widget_id].upper()
444            err = 0
445            if len(value.split()) > 1:
446                err = 'Invalid Id, Id contains space(s).'
447            elif self.portal_catalog(portal_type=portal_type_query,id=value):
448                brain = self.portal_catalog(portal_type=portal_type_query,id=value)[0]
449                err = 'An %s object with the Id %s already exists at %s.'\
450                      % (brain.portal_type,value,brain.getPath())
451            if err:
452                datastructure.setError(widget_id, err)
453            else:
454                datamodel = datastructure.getDataModel()
455                datamodel[self.fields[0]] = value
456
457            return not err
458
459InitializeClass(WAeUPIdWidget)
460
461widgetRegistry.register(WAeUPIdWidget)
462
463
464###)
465
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()
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()
479        id_pat_str = r"\S"
480        inv_id_pat = compile(r"^%s$" % id_pat_str)
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)
488        else:
489            datamodel = datastructure.getDataModel()
490            datamodel[self.fields[0]] = value
491        return not err
492
493InitializeClass(StudyCourseWidget)
494
495widgetRegistry.register(StudyCourseWidget)
496###)
497
498class JambRegNoWidget(CPSStringWidget): ###(
499    """ JambRegNo Widget"""
500    meta_type = "JambRegNo Widget"
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 = ""
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)
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)
522            err = 'Invalid number'
523        elif self.reference == '':
524            #s = getStudentByRegNo(self,value)
525            pume = jamb_nr_catalog(jamb_reg_no = value)
526            if len(pume) < 1:
527                err = 'No student with Registration Number %s' % (value)
528            else:
529                datastructure['pume'] = pume[0]
530        else:
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:
536                err = 'Registration number does not match.'
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
543
544InitializeClass(JambRegNoWidget)
545
546widgetRegistry.register(JambRegNoWidget)
547###)
548
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"
559    matric_no_catalog = 'returning_import'
560    check_fields = ("Firstname", "Middlename","Lastname")
561    def validate(self, datastructure, **kw):
562        """Validate datastructure and update datamodel."""
563        logger = logging.getLogger('Widgets.SecretWidget.validate')
564        valid = CPSStringWidget.validate(self, datastructure, **kw)
565        widget_id = self.getWidgetId()
566        value = datastructure[widget_id].upper()
567        err = 0
568        record = datastructure.get(self.reference,None)
569        #import pdb;pdb.set_trace()
570        if not valid or len(value) < 2:
571            err = 'Invalid string'
572        elif not record or datastructure.errors:
573            err = 0
574        else:
575            found = False
576            cvs = []
577            for field in self.check_fields:
578                cv = getattr(record,field).upper()
579                if len(cv.split()) > 1:
580                    for splited in cv.split():
581                        cvs.append(splited.strip())
582                else:
583                    cvs.append(cv)
584            for cv in cvs:
585                if cv  == value.upper():
586                    found = True
587                    break
588            matric_no = record.matric_no
589            name = " ".join(cvs)
590            if not found:
591                logger.info('%(matric_no)s did not find %(value)s in %(name)s' % vars())
592                err = 'No name does match.'
593            else:
594                logger.info('%(matric_no)s found %(value)s in %(name)s' % vars())
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
607class WAeUPSexWidget(CPSBooleanWidget): ###(
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
636###)
637
638class MatricNoWidget(CPSStringWidget): ###(
639    """ MatricNo Widget"""
640    meta_type = "MatricNo Widget"
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
649    results_catalog = "results_import" #results catalog
650
651    def validate(self, datastructure, **kw):
652        """Validate datastructure and update datamodel."""
653        #import pdb;pdb.set_trace()
654        valid = CPSStringWidget.validate(self, datastructure, **kw)
655        logger = logging.getLogger('Widgets.MatricNoWidget.validate')
656        returning = getattr(self,self.matric_no_catalog)
657        results = getattr(self,self.results_catalog,None)
658        err = 0
659        widget_id = self.getWidgetId()
660        value = datastructure[widget_id]
661        if not valid or not value:
662            err = 'Invalid string %s' % value
663            logger.info('Invalid matric_no string %s' % value)
664        else:
665            value = value.upper()
666            datastructure['student'] = None
667            while not err:
668                res = returning(matric_no = value)
669                if len(res) < 1:
670                    logger.info('matric_no %s not found' % value)
671                    err = 'No student with Matriculation Number %s' % (value)
672                    break
673                datastructure['student'] = res[0]
674                if results is not None:
675                    res = results(matric_no = value)
676                    if len(res) < 1:
677                        err = 'No results for Matriculation Number %s' % (value)
678                        continue
679                    datastructure['results'] = res
680                break
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
687
688InitializeClass(MatricNoWidget)
689
690widgetRegistry.register(MatricNoWidget)
691###)
692
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)
699        logger = logging.getLogger('Widgets.StudentIdWidget.validate')
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:
706            err = 'Invalid Id string %s' % value
707            logger.info('Invalid id string %s' % value)
708            datastructure['student'] = None
709        else:
710            value = value.upper()
711            res = s_cat(id = value)
712            if not res:
713                logger.info('Student id %s not found' % value)
714                err = 'No student with Id %s' % (value)
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
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()))
778
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
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()
836        datastructure[widget_id] = v
837        datastructure[widget_id+'_s'] = ''
838        datastructure[widget_id+'_g'] = ''
839    ###)
840
841    def validate(self, datastructure, **kw): ###(
842        """Validate datastructure and update datamodel."""
843        #import pdb;pdb.set_trace()
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()
849        while 1:
850            if not s and g:
851                err = "No subject grade for subject %s " % s
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
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
901class ScratchCardPin: ###(
902    """the ScratchCardPin"""
903    def __init__(self,prefix,batch_no,number):
904        if not batch_no and not number:
905            s = prefix
906            if len(s) > 3:
907                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
908            else:
909                prefix,batch_no,number = s,'',''
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)
916
917    def __repr__(self):
918        return "%s%s%s" % (self.p,self.b,self.n)
919###)
920
921class ScratchcardPinWidget(CPSStringWidget): ###(
922    """ ScratchcardPin Widget"""
923    meta_type = "Scratchcard Pin Widget"
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 = ''
932    def prepare(self, datastructure, **kw): ###(
933        """Prepare datastructure from datamodel."""
934        datamodel = datastructure.getDataModel()
935        v = datamodel[self.fields[0]]
936        widget_id = self.getWidgetId()
937        #import pdb;pdb.set_trace()
938        if v and type(v) is StringType:
939            try:
940                p,b,n = v.split('-')
941                v = ScratchCardPin(p,b,n)
942            except ValueError:
943                v = ScratchCardPin(v,'','')
944        if v:
945            p = '%s' % v.p
946            b = '%s' % v.b
947            n = '%s' % v.n
948        else:
949            p = self.prefix
950            if p.startswith('@'):
951                p = getattr(self,self.prefix[1:])()
952            b = n = ''
953            v = ScratchCardPin(p,b,n)
954        datastructure[widget_id] = v
955        datastructure[widget_id+'_p'] = p
956        datastructure[widget_id+'_b'] = b
957        datastructure[widget_id+'_n'] = n
958    ###)
959
960    def validate(self, datastructure, **kw): ###(
961        """Validate datastructure and update datamodel."""
962        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
963        widget_id = self.getWidgetId()
964        v = datastructure[widget_id]
965        #import pdb;pdb.set_trace()
966        err = 0
967        prefix= self.prefix
968        if prefix.startswith('@'):
969            prefix= getattr(self,self.prefix[1:])()
970        b = datastructure[widget_id+'_b'].strip()
971        n = datastructure[widget_id+'_n'].strip()
972        pins = self.portal_pins
973        pin = "%(prefix)s%(b)s%(n)s" % vars()
974        pin_str = "%(prefix)s-%(b)-s%(n)s" % vars()
975        do = 1
976        s_id = str(self.portal_membership.getAuthenticatedMember())
977        #import pdb;pdb.set_trace()
978        if self.isStaff():
979            do = 0
980            err ='You are not a Student. PIN neither checked nor used.'
981            s_logger.info('%s tried to use scratch card %s' % (s_id,pin_str))
982        elif len(b) > 1 and b.find('-') > -1:
983            do = 0
984            err = 'PIN must not contain "-"'
985            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
986        elif n.find('-') > -1:
987            do = 0
988            err = 'PIN must not contain "-"'
989            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
990        elif len(n) != 10:
991            do = 0
992            err = 'Invalid PIN length %d' % len(n)
993            s_logger.info('%s entered invalid PIN with length %d' % (s_id,len(n)))
994        elif self.reference == "":
995            ref = s_id
996        else:
997            ref = datastructure[self.reference]
998            if datastructure.errors:
999                do = 0
1000                datastructure.setError(widget_id, 'errors in other data, PIN neither checked nor used')
1001                s_logger.info('%s/%s entered wrong data together with PIN %s' % (s_id,ref,pin_str))
1002        while do:
1003            ok = pins.searchAndSetRecord(pin,ref,prefix)
1004            if ok < -2 or ok > 2:
1005                err = 'Unknown error, please report!'
1006                s_logger.info('%s/%s caused unknown error with PIN %s' % (s_id,ref,pin_str))
1007                break
1008            elif ok == -2:
1009                err = 'Service already is activated but with a different PIN.'
1010                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (s_id,ref,pin_str))
1011                break
1012            elif ok == -1:
1013                err = 'Invalid PIN'
1014                s_logger.info('%s/%s entered invalid PIN %s' % (s_id,ref,pin_str))
1015                break
1016            if ok == 0:
1017                err = 'PIN already used'
1018                s_logger.info('%s/%s entered used PIN %s' % (s_id,ref,pin_str))
1019                break
1020            if ok >= 1:
1021                #import pdb;pdb.set_trace()
1022                if self.isStudent():
1023                    if self.reference == "jamb_reg_no":
1024                        err = "You are already logged in."
1025                        s_logger.info('%s/%s checked admission with PIN %s though logged in' % (s_id,ref,pin_str))
1026                        break
1027                    if ok == 1:
1028                        s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
1029                    else:
1030                        s_logger.info('%s/%s repeatedly used PIN %s' % (s_id,ref,pin_str))
1031                    break
1032                else:
1033                    student = getStudentByRegNo(self,ref)
1034                    s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
1035                if student is None:
1036                    err = "Student not found"
1037                    s_logger.info('%s not found in admission list' % (ref))
1038                    break
1039                s_id = student.getId()
1040                if ok == 2:
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
1044                            s_logger.info('%s/%s repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
1045                            break
1046                        else:
1047                            s_logger.info('%s/%s (non-member) repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
1048                    else:
1049                        err = "Unknown error" % s_id
1050                        s_logger.info('%s/%s repeatedly activated service with PIN %s' % (s_id,ref,pin_str))
1051                        break
1052                try:
1053                    student.getContent().makeStudentMember(s_id,password=pin[4:])
1054                    s_logger.info('%s/%s has been created using PIN %s' % (s_id,ref,pin_str))
1055                except:
1056                    err = "Please login with your Student Id %s and 10-digit PIN." % s_id
1057                    s_logger.info('%s/%s could not be made a member with PIN %s' % (s_id,ref,pin_str))
1058                    break
1059            break
1060        if err:
1061            datastructure.setError(widget_id, err)
1062        else:
1063            datamodel = datastructure.getDataModel()
1064            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
1065            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
1066            datastructure[widget_id+'_p'] = prefix
1067            datastructure[widget_id+'_b'] = b
1068            datastructure[widget_id+'_n'] = n
1069            datastructure['s_id'] = s_id
1070        return not err
1071
1072###)
1073
1074    def render(self, mode, datastructure, **kw): ###(
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]]
1087        if v and type(v) is StringType:
1088            try:
1089                p,b,n = v.split('-')
1090                v = ScratchCardPin(p,b,n)
1091            except ValueError:
1092                v = ScratchCardPin(self.prefix,'1',v)
1093                pass
1094        if v:
1095            prefix= '%s' % v.p
1096            b = '%s' % v.b
1097            n = '%s' % v.n
1098        else:
1099            prefix= self.prefix
1100            if prefix.startswith('@'):
1101                prefix= getattr(self,self.prefix[1:])()
1102            b = n = ''
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
1109        return meth(mode=mode,
1110                    datastructure=datastructure,
1111                    )
1112    ###)
1113
1114
1115InitializeClass(ScratchcardPinWidget)
1116widgetRegistry.register(ScratchcardPinWidget)
1117
1118
1119###)
1120
1121class WAeUPImageWidget(CPSImageWidget): ###(
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)
1137###)
1138
1139
1140###########
1141
Note: See TracBrowser for help on using the repository browser.