source: WAeUP_SRP/trunk/Widgets.py @ 2097

Last change on this file since 2097 was 2095, checked in by Henrik Bettermann, 17 years ago

applicants_catalog and application instead of new_students

  • Property svn:keywords set to Id
File size: 52.1 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Widgets.py 2095 2007-08-13 15:33:15Z henrik $
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
19import operator
20
21#from zLOG import LOG, DEBUG
22
23class CPSSelectWidgetForRecord(CPSSelectWidget): ###(
24    """Select widget. with record names"""
25    meta_type = 'Select Widget for Records'
26
27    field_types = ('CPS String Field',)
28    field_inits = ({'is_searchabletext': 1,},)
29
30    _properties = CPSSelectWidget._properties + (
31        {'id': 'record_id', 'type': 'string', 'mode': 'w',
32         'label': 'Record Id', 'is_required' : 1},
33        )
34
35    def render(self, mode, datastructure, **kw):
36        """Render in mode from datastructure."""
37        value = datastructure[self.getWidgetId()]
38        vocabulary = self._getVocabulary(datastructure)
39        portal = getToolByName(self, 'portal_url').getPortalObject()
40        cpsmcat = portal.translation_service
41        if mode == 'view':
42            if self.translated:
43                return escape(cpsmcat(vocabulary.getMsgid(value, value)).encode('ISO-8859-15', 'ignore'))
44            else:
45                return escape(vocabulary.get(value, value))
46        elif mode == 'edit':
47            html_widget_id = self.getHtmlWidgetId()
48            res = renderHtmlTag('select',
49                                name='%s.%s:records' % (self.record_id,html_widget_id),
50                                id=html_widget_id)
51            in_selection = 0
52            for k, v in vocabulary.items():
53                if self.translated:
54                    kw = {'value': k,
55                          'contents': cpsmcat(vocabulary.getMsgid(k, k)).encode('ISO-8859-15', 'ignore')
56                          }
57                else:
58                    kw = {'value': k, 'contents': v}
59                if value == k:
60                    kw['selected'] = 'selected'
61                    in_selection = 1
62                res += renderHtmlTag('option', **kw)
63            if value and not in_selection:
64                kw = {'value': value, 'contents': 'invalid: '+ str(value),
65                      'selected': 'selected'}
66                res += renderHtmlTag('option', **kw)
67            res += '</select>'
68            return res
69        raise RuntimeError('unknown mode %s' % mode)
70
71InitializeClass(CPSSelectWidgetForRecord)
72
73widgetRegistry.register(CPSSelectWidgetForRecord)
74
75###)
76
77class CPSStringWidgetForRecord(CPSStringWidget): ###(
78    """String widget."""
79    meta_type = 'String Widget For Record'
80
81    field_types = ('CPS String Field',)
82    field_inits = ({'is_searchabletext': 1,},)
83    _properties = CPSStringWidget._properties + (
84        {'id': 'record_id', 'type': 'string', 'mode': 'w',
85         'label': 'Record Id', 'is_required' : 1},
86        )
87
88    def render(self, mode, datastructure, **kw):
89        """Render in mode from datastructure."""
90        value = datastructure[self.getWidgetId()]
91        if mode == 'view':
92            return escape(value)
93        elif mode == 'edit':
94            # XXX TODO should use an other name than kw !
95            # XXX change this everywhere
96            html_widget_id = self.getHtmlWidgetId()
97            kw = {'type': 'text',
98                  'id'  : html_widget_id,
99                  'name': '%s.%s:records' % (self.record_id,html_widget_id),
100                  'value': escape(value),
101                  'size': self.display_width,
102                  }
103            if self.size_max:
104                kw['maxlength'] = self.size_max
105            return renderHtmlTag('input', **kw)
106        raise RuntimeError('unknown mode %s' % mode)
107
108InitializeClass(CPSStringWidgetForRecord)
109
110widgetRegistry.register(CPSStringWidgetForRecord)
111
112###)
113
114class CertificateCourseIdWidget(CPSStringWidget): ###(
115    """ CertificateCourseId Widget"""
116    meta_type = "CertificateCourseId Widget"
117
118    def validate(self, datastructure, **kw):
119        """Validate datastructure and update datamodel."""
120
121        valid = CPSStringWidget.validate(self, datastructure, **kw)
122        if not valid:
123            return 0
124        else:
125            widget_id = self.getWidgetId()
126            value = datastructure[widget_id].upper()
127            err = 0
128            c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
129            if hasattr(self.aq_parent,value):
130                err = 'Course already exists'
131            elif value not in c_ids:
132                err = 'Course does not exist'
133            if err:
134                datastructure.setError(widget_id, err)
135            else:
136                datamodel = datastructure.getDataModel()
137                datamodel[self.fields[0]] = value
138
139            return not err
140
141InitializeClass(CertificateCourseIdWidget)
142
143widgetRegistry.register(CertificateCourseIdWidget)
144###)
145
146class CourseIdWidget(CPSStringWidget): ###(
147    """ CourseId Widget"""
148    meta_type = "CourseId Widget"
149
150    def validate(self, datastructure, **kw):
151        """Validate datastructure and update datamodel."""
152
153        valid = CPSStringWidget.validate(self, datastructure, **kw)
154        if not valid:
155            return 0
156        else:
157            widget_id = self.getWidgetId()
158            value = datastructure[widget_id].upper()
159            err = 0
160            res = self.portal_catalog(meta_type= "Course",id = value)
161            if len(res) > 0:
162                err = 'Course already exists'
163            if err:
164                datastructure.setError(widget_id, err)
165            else:
166                datamodel = datastructure.getDataModel()
167                datamodel[self.fields[0]] = value
168
169            return not err
170
171InitializeClass(CourseIdWidget)
172
173widgetRegistry.register(CourseIdWidget)
174
175
176###)
177
178class WAeUPStudyModeWidget(CPSSelectWidget): ###(
179    """WAeUP StudyMode Widget."""
180    meta_type = 'WAeUP StudyMode Widget'
181    vocabulary = 'entry_modes'
182
183    def _getStudyModes(self):
184        voc = getattr(self.portal_vocabularies,self.vocabulary)
185        d = {}
186        for k,v in voc.items():
187            d[k] = v
188        return d
189
190    def validate(self, datastructure, **kw):
191        """Validate datastructure and update datamodel."""
192        widget_id = self.getWidgetId()
193        value = datastructure[widget_id]
194        try:
195            v = str(value)
196        except ValueError:
197            datastructure.setError(widget_id, "'%s' not a valid session key" % value)
198            return 0
199        studymodes = self._getStudyModes()
200        if not value:
201            v = value = 'ume_ft'
202        #import pdb;pdb.set_trace()
203        if not studymodes.has_key(value):
204            datastructure.setError(widget_id, "'%s' not a valid session key" % v)
205            return 0
206        if self.is_required and not len(v):
207            datastructure.setError(widget_id, "session key required")
208            return 0
209
210        datamodel = datastructure.getDataModel()
211        datamodel[self.fields[0]] = v
212        return 1
213
214    def render(self, mode, datastructure, **kw):
215        """Render in mode from datastructure."""
216        value = datastructure[self.getWidgetId()]
217        studymodes = self._getStudyModes()
218        if mode == 'view':
219            return escape(studymodes.get(value, value))
220        elif mode == 'edit':
221            html_widget_id = self.getHtmlWidgetId()
222            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
223            in_selection = 0
224            vocabulary_items = studymodes.items()
225            if self.sorted:
226                vocabulary_items.sort(key=operator.itemgetter(1))
227            for k, v in vocabulary_items:
228                kw = {'value': k, 'contents': v}
229                if value == k:
230                    kw['selected'] = 'selected'
231                    in_selection = 1
232                res += renderHtmlTag('option', **kw)
233            if value and not in_selection:
234                kw = {'value': value, 'contents': 'invalid: '+ str(value),
235                      'selected': 'selected'}
236                res += renderHtmlTag('option', **kw)
237            res += '</select>'
238            return res
239        raise RuntimeError('unknown mode %s' % mode)
240
241InitializeClass(WAeUPStudyModeWidget)
242
243widgetRegistry.register(WAeUPStudyModeWidget)
244
245###)
246
247class WAeUPSessionWidget(CPSSelectWidget): ###(
248    """WAeUP Session Widget."""
249    meta_type = 'WAeUP Session Widget'
250
251    def _getSessions(self):
252        current_year = DateTime().year()
253        d = {'-1': 'N/A'}
254        for y in range(current_year - 9,current_year + 1):
255            d['%s' % str(y)[-2:]] = '%4d/%4d' % (y,y+1)
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 session key" % value)
266            return 0
267
268        if len(v) == 1:
269            v = value = '0%c' % v
270        elif not value:
271            v = value = self.getSessionId()[-2:]
272        #import pdb;pdb.set_trace()
273        sessions = self._getSessions()
274        if not sessions.has_key(value):
275            datastructure.setError(widget_id, "'%s' not a valid session key" % v)
276            return 0
277        if self.is_required and not len(v):
278            datastructure.setError(widget_id, "session key required")
279            return 0
280
281        datamodel = datastructure.getDataModel()
282        datamodel[self.fields[0]] = v
283        return 1
284
285    def render(self, mode, datastructure, **kw):
286        """Render in mode from datastructure."""
287        value = datastructure[self.getWidgetId()]
288        sessions = self._getSessions()
289        if mode == 'view':
290            return escape(sessions.get(value, value))
291        elif mode == 'edit':
292            html_widget_id = self.getHtmlWidgetId()
293            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
294            in_selection = 0
295            vocabulary_items = sessions.items()
296            if self.sorted:
297                vocabulary_items.sort(key=operator.itemgetter(0))
298            for k, v in vocabulary_items:
299                kw = {'value': k, 'contents': v}
300                if value == k:
301                    kw['selected'] = 'selected'
302                    in_selection = 1
303                res += renderHtmlTag('option', **kw)
304            if value and not in_selection:
305                kw = {'value': value, 'contents': 'invalid: '+ str(value),
306                      'selected': 'selected'}
307                res += renderHtmlTag('option', **kw)
308            res += '</select>'
309            return res
310        raise RuntimeError('unknown mode %s' % mode)
311
312InitializeClass(WAeUPSessionWidget)
313
314widgetRegistry.register(WAeUPSessionWidget)
315
316###)
317
318class WAeUPLevelWidget(CPSSelectWidget): ###(
319    """WAeUP Level Widget."""
320    meta_type = 'WAeUP Level Widget'
321
322    def _getLevels(self):
323        d = {'000':'N/A'}
324        for y in range(100,800,100):
325            d['%s' % str(y)] = 'Year %1d (%3d Level)' % (y/100,y)
326        return d
327
328    def validate(self, datastructure, **kw):
329        """Validate datastructure and update datamodel."""
330        widget_id = self.getWidgetId()
331        value = datastructure[widget_id]
332        try:
333            v = str(value)
334        except ValueError:
335            datastructure.setError(widget_id, "'%s' not a valid level key" % value)
336            return 0
337
338        if not value:
339            v = value = '100'
340        #import pdb;pdb.set_trace()
341        levels = self._getLevels()
342        if not levels.has_key(value):
343            datastructure.setError(widget_id, "'%s' not a valid level" % v)
344            return 0
345        if self.is_required and not len(v):
346            datastructure.setError(widget_id, "level key required")
347            return 0
348
349        datamodel = datastructure.getDataModel()
350        datamodel[self.fields[0]] = v
351        return 1
352
353    def render(self, mode, datastructure, **kw):
354        """Render in mode from datastructure."""
355        value = datastructure[self.getWidgetId()]
356        levels = self._getLevels()
357        if mode == 'view':
358            return escape(levels.get(value, value))
359        elif mode == 'edit':
360            html_widget_id = self.getHtmlWidgetId()
361            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
362            in_selection = 0
363            vocabulary_items = levels.items()
364            if self.sorted:
365                vocabulary_items.sort(key=operator.itemgetter(0))
366            for k, v in vocabulary_items:
367                kw = {'value': k, 'contents': v}
368                if value == k:
369                    kw['selected'] = 'selected'
370                    in_selection = 1
371                res += renderHtmlTag('option', **kw)
372            if value and not in_selection:
373                kw = {'value': value, 'contents': 'invalid: '+ str(value),
374                      'selected': 'selected'}
375                res += renderHtmlTag('option', **kw)
376            res += '</select>'
377            return res
378        raise RuntimeError('unknown mode %s' % mode)
379
380InitializeClass(WAeUPLevelWidget)
381
382widgetRegistry.register(WAeUPLevelWidget)
383
384###)
385
386class WAeUPVerdictWidget(CPSSelectWidget): ###(
387    """WAeUP Verdict Widget."""
388    meta_type = 'WAeUP Verdict Widget'
389
390    # XXX make a menu for the vocabulary.
391    vocabulary = 'verdicts'
392
393    # Associating the widget label with an input area to improve the widget
394    # accessibility.
395    has_input_area = True
396
397    def _getVerdicts(self,datastructure):
398        voc = getattr(self.portal_vocabularies,self.vocabulary)
399        d = {}
400        for k,v in voc.items():
401            d[k] = v
402        return d
403
404    def validate(self, datastructure, **kw):
405        """Validate datastructure and update datamodel."""
406        widget_id = self.getWidgetId()
407        value = datastructure[widget_id]
408        try:
409            v = str(value)
410        except ValueError:
411            datastructure.setError(widget_id, "'%s' not a valid verdict key" % value)
412            return 0
413        #import pdb;pdb.set_trace()
414        verdicts = self._getVerdicts(datastructure)
415        if not value:
416            v = value = verdicts['N/A']
417        if not verdicts.has_key(value):
418            datastructure.setError(widget_id, "'%s' not a valid verdict key" % v)
419            return 0
420        if self.is_required and not len(v):
421            datastructure.setError(widget_id, "verdict required")
422            return 0
423
424        datamodel = datastructure.getDataModel()
425        datamodel[self.fields[0]] = v
426        return 1
427
428    def render(self, mode, datastructure, **kw):
429        """Render in mode from datastructure."""
430        value = datastructure[self.getWidgetId()]
431        verdicts = self._getVerdicts(datastructure)
432        if mode == 'view':
433            return escape(verdicts.get(value, value))
434        elif mode == 'edit':
435            html_widget_id = self.getHtmlWidgetId()
436            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
437            in_selection = 0
438            vocabulary_items = verdicts.items()
439            if self.sorted:
440                vocabulary_items.sort(key=operator.itemgetter(1))
441            for k, v in vocabulary_items:
442                kw = {'value': k, 'contents': v}
443                if value == k:
444                    kw['selected'] = 'selected'
445                    in_selection = 1
446                res += renderHtmlTag('option', **kw)
447            if value and not in_selection:
448                kw = {'value': value, 'contents': 'invalid: '+ str(value),
449                      'selected': 'selected'}
450                res += renderHtmlTag('option', **kw)
451            res += '</select>'
452            return res
453        raise RuntimeError('unknown mode %s' % mode)
454
455InitializeClass(WAeUPVerdictWidget)
456
457widgetRegistry.register(WAeUPVerdictWidget)
458
459###)
460
461class WAeUPLGAWidget(CPSSelectWidget): ###(
462    """WAeUP LGA Widget."""
463    meta_type = 'WAeUP LGA Widget'
464    _properties = CPSSelectWidget._properties + (
465        {'id': 'state_field', 'type': 'string', 'mode': 'w',
466         'label': 'Name of the state field'},
467         {'id': 'lga_field', 'type': 'string', 'mode': 'w',
468         'label': 'Name of the LGA Field (without state)'},
469         )
470    state_field = "state"
471    lga_field = "lga"
472
473    # XXX make a menu for the vocabulary.
474    vocabulary = 'local_gov_areas'
475
476    # Associating the widget label with an input area to improve the widget
477    # accessibility.
478    has_input_area = True
479
480    def _getLGAs(self):
481        voc = getattr(self.portal_vocabularies,self.vocabulary)
482        states = []
483        lgas  = []
484        d = {}
485        for k,v in voc.items():
486            parts = k.split('_')
487            state = parts[0]
488            lga = ' '.join(parts[1:])
489            if state not in states:
490                states.append(state)
491            lgas.append(lga)
492            d[k] = v
493        return (d,states,lgas)
494
495    def validate(self, datastructure, **kw):
496        """Validate datastructure and update datamodel."""
497        widget_id = self.getWidgetId()
498        value = datastructure[widget_id]
499        #import pdb;pdb.set_trace()
500        try:
501            v = str(value)
502        except ValueError:
503            datastructure.setError(widget_id, "'%s' not a valid lga key" % value)
504            return 0
505        v = v.lower()
506        combined,states,lgas = self._getLGAs()
507        one_field = False
508        if not self.state_field and not self.lga_field:
509            one_field = True
510            if v not in combined.keys():
511                datastructure.setError(widget_id, "'%s' not a valid lga key" % v)
512                return 0
513        else:
514            if widget_id == self.state_field:
515                if v not in states:
516                    datastructure.setError(widget_id, "'%s' not a valid state" % v)
517                    return 0
518            elif widget_id == self.lga_field:
519                if v not in lgas:
520                    datastructure.setError(widget_id, "'%s' not a valid lga" % v)
521                    return 0
522                if datastructure[self.state_field]:
523                    v = datastructure[self.state_field] + '_' + v
524
525        if self.is_required and not len(v):
526            datastructure.setError(widget_id, "lga required")
527            return 0
528
529        datamodel = datastructure.getDataModel()
530        if one_field:
531            datamodel[self.fields[0]] = v
532        else:
533            state = datastructure[self.state_field].lower()
534            lga = "_".join(datastructure[self.lga_field].lower().split())
535            datamodel[self.fields[0]] =   state + "_" + lga
536        return 1
537
538    def render(self, mode, datastructure, **kw):
539        """Render in mode from datastructure."""
540        w_id = self
541        value = datastructure[self.getWidgetId()]
542        lgas,x,y = self._getLGAs(datastructure)
543        if mode == 'view':
544            return escape(lgas.get(value, value))
545        elif mode == 'edit':
546            html_widget_id = self.getHtmlWidgetId()
547            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
548            in_selection = 0
549            vocabulary_items = lgas.items()
550            # if self.sorted:
551            #     vocabulary_items.sort(key=operator.itemgetter(1))
552            for k, v in vocabulary_items:
553                kw = {'value': k, 'contents': v}
554                if value == k:
555                    kw['selected'] = 'selected'
556                    in_selection = 1
557                res += renderHtmlTag('option', **kw)
558            if value and not in_selection:
559                kw = {'value': value, 'contents': 'invalid: '+ str(value),
560                      'selected': 'selected'}
561                res += renderHtmlTag('option', **kw)
562            res += '</select>'
563            return res
564        raise RuntimeError('unknown mode %s' % mode)
565
566InitializeClass(WAeUPLGAWidget)
567
568widgetRegistry.register(WAeUPLGAWidget)
569
570###)
571
572class WAeUPReservedRoomsWidget(CPSStringWidget): ###(
573    """ WAeUPReservedRooms Widget"""
574    meta_type = "WAeUPReservedRooms Widget"
575
576    def validate(self, datastructure, **kw):
577        """Validate datastructure and update datamodel."""
578        import re
579        valid = CPSStringWidget.validate(self, datastructure, **kw)
580        if not valid:
581            return 0
582        else:
583            widget_id = self.getWidgetId()
584            value = datastructure[widget_id]
585            err = 0
586            try:
587                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
588                                     if r]
589            except (ValueError,IndexError),msg:
590                err = str(msg)
591            if err:
592                datastructure.setError(widget_id, err)
593            else:
594                datamodel = datastructure.getDataModel()
595                datamodel[self.fields[0]] = value
596            return not err
597
598InitializeClass(WAeUPReservedRoomsWidget)
599
600widgetRegistry.register(WAeUPReservedRoomsWidget)
601###)
602
603class WAeUPIdWidget(CPSStringWidget): ###(
604    """ WAeUPId Widget"""
605    meta_type = "WAeUPId Widget"
606
607    def validate(self, datastructure, **kw):
608        """Validate datastructure and update datamodel."""
609
610        valid = CPSStringWidget.validate(self, datastructure, **kw)
611        id_pat_str = r"\S"
612        inv_id_pat = compile(r"^%s$" % id_pat_str)
613        if not valid:
614            return 0
615        else:
616            portal_type_query = {'query':['Faculty',
617                                          'Department',
618                                          'Course',
619                                          'Certificate',
620                                          'CertificateCourse',]}
621            widget_id = self.getWidgetId()
622            value = datastructure[widget_id]  #.upper()  is not necessary here because it's also done in waeup_document_create_do
623            err = 0
624            mapping = {}
625            if len(value.split()) > 1:
626                err = 'Invalid Id, Id contains space(s).'
627            elif self.portal_catalog(portal_type=portal_type_query,id=value):
628                brain = self.portal_catalog(portal_type=portal_type_query,id=value)[0]
629                err = 'An ${portal_type} object with the Id ${id} already exists at ${path}.'
630                mapping = {'portal_type': brain.portal_type,
631                           'id': value,
632                           'path': brain.getPath(),
633                           }
634            if err:
635                datastructure.setError(widget_id, err, mapping)
636            else:
637                datamodel = datastructure.getDataModel()
638                datamodel[self.fields[0]] = value
639
640            return not err
641
642InitializeClass(WAeUPIdWidget)
643
644widgetRegistry.register(WAeUPIdWidget)
645
646
647###)
648
649class StudyCourseWidget(CPSStringWidget): ###(
650    """ StudyCourse Widget"""
651    meta_type = "StudyCourse Widget"
652
653    def validate(self, datastructure, **kw):
654        """Validate datastructure and update datamodel."""
655        #from Products.zdb import set_trace
656        #set_trace()
657##        valid = CPSStringWidget.validate(self, datastructure, **kw)
658##        if not valid:
659##            return 0
660        widget_id = self.getWidgetId()
661        value = makeCertificateCode(datastructure[widget_id]).upper()
662        id_pat_str = r"\S"
663        inv_id_pat = compile(r"^%s$" % id_pat_str)
664        err = 0
665        if len(value.split()) > 1:
666            err = 'Invalid Id, Id contains space(s).'
667        elif not self.portal_catalog(portal_type='Certificate',id=value):
668            err = 'No such certificate'
669        if err:
670            datastructure.setError(widget_id, err)
671        else:
672            datamodel = datastructure.getDataModel()
673            datamodel[self.fields[0]] = value
674        return not err
675
676InitializeClass(StudyCourseWidget)
677
678widgetRegistry.register(StudyCourseWidget)
679###)
680
681class JambRegNoWidget(CPSStringWidget): ###(
682    """ JambRegNo Widget"""
683    meta_type = "JambRegNo Widget"
684    _properties = CPSStringWidget._properties + (
685        {'id': 'catalog', 'type': 'string', 'mode': 'w',
686         'label': 'Catalog to search'},
687         {'id': 'reference', 'type': 'string', 'mode': 'w',
688         'label': 'Reference Field'},
689         )
690    catalog = "portal_pumeresults" #the catalog to search for jamb_reg_no
691    reference = ""
692    digits = 8
693    digits_str = "N"*digits
694    letters = 2
695    letters_str = "L"*letters
696    def validate(self, datastructure, **kw):
697        """Validate datastructure and update datamodel."""
698        valid = CPSStringWidget.validate(self, datastructure, **kw)
699        jamb_nr_catalog = getattr(self,self.catalog)
700        widget_id = self.getWidgetId()
701        value = datastructure[widget_id].upper()
702        err = 0
703        #import pdb;pdb.set_trace()
704        if kw.has_key('mode'):
705            mode = kw['mode']
706        else:
707            mode = "xxxx"
708        if not valid:
709            err = 'Invalid number'
710        elif self.reference == '':
711            #s = getStudentByRegNo(self,value)
712            pume = jamb_nr_catalog(jamb_reg_no = value)
713            if len(pume) < 1:
714                err = 'No student record with this registration number.'
715            else:
716                datastructure['pume'] = pume[0]
717        elif mode == 'add':
718            pass
719        elif self.reference != '' and self.catalog == "applicants_catalog":
720            res = jamb_nr_catalog.searchResults({"%s" % self.reference: value})
721            if len(res) != 1:
722                err = 'No record with this registration number.'
723            else:
724                datastructure['record'] = res[0]
725        else:
726            record = datastructure[self.reference]
727            #jamb_reg_no = getattr(record,widget_id)
728            jamb_reg_no = record.Entryregno
729            if jamb_reg_no != value:
730                err = 'Registration number does not match.'
731        if err:
732            datastructure.setError(widget_id, err)
733        else:
734            datamodel = datastructure.getDataModel()
735            datamodel[self.fields[0]] = value
736        return not err
737
738InitializeClass(JambRegNoWidget)
739
740widgetRegistry.register(JambRegNoWidget)
741###)
742
743class SecretWidget(CPSStringWidget): ###(
744    """ Secret Widget"""
745    meta_type = "Secret Widget"
746    _properties = CPSStringWidget._properties + (
747        {'id': 'reference', 'type': 'string', 'mode': 'w',
748         'label': 'Reference Record'},
749         {'id': 'check_fields', 'type': 'tokens', 'mode': 'w',
750         'label': 'Fields to check'},
751         )
752    reference = "student"
753    matric_no_catalog = 'returning_import'
754    check_fields = ("Firstname", "Middlename","Lastname")
755    def validate(self, datastructure, **kw):
756        """Validate datastructure and update datamodel."""
757        logger = logging.getLogger('Widgets.SecretWidget.validate')
758        valid = CPSStringWidget.validate(self, datastructure, **kw)
759        widget_id = self.getWidgetId()
760        value = datastructure[widget_id].upper()
761        err = 0
762        record = datastructure.get(self.reference,None)
763        #import pdb;pdb.set_trace()
764        if not valid or len(value) < 2:
765            err = 'Invalid string'
766        elif not record or datastructure.errors:
767            err = 0
768        else:
769            found = False
770            cvs = []
771            for field in self.check_fields:
772                cv = getattr(record,field).upper()
773                if len(cv.split()) > 1:
774                    for splited in cv.split():
775                        cvs.append(splited.strip())
776                else:
777                    cvs.append(cv)
778            for cv in cvs:
779                if cv  == value.upper():
780                    found = True
781                    break
782            matric_no = record.matric_no
783            name = " ".join(cvs)
784            if not found:
785                logger.info('%(matric_no)s did not find %(value)s in %(name)s' % vars())
786                err = 'No name does match.'
787            else:
788                logger.info('%(matric_no)s found %(value)s in %(name)s' % vars())
789        if err:
790            datastructure.setError(widget_id, err)
791        else:
792            datamodel = datastructure.getDataModel()
793            datamodel[self.fields[0]] = value
794        return not err
795
796InitializeClass(SecretWidget)
797
798widgetRegistry.register(SecretWidget)
799###)
800
801class WAeUPSexWidget(CPSBooleanWidget): ###(
802    """WAeUP sex widget."""
803    meta_type = 'WAeUP Sex Widget'
804
805    def validate(self, datastructure, **kw):
806        """Validate datastructure and update datamodel."""
807        value = datastructure[self.getWidgetId()]
808
809        if self.render_format not in self.render_formats:
810            self.render_format = 'select'
811
812        female = value in ('F','f','Female','female',"True",True)
813        male = value in ('M','m','Male','male','False',False)
814        if not female and not male:
815            datastructure.setError(self.getWidgetId(),
816                                   "invalid sex %s" % value)
817            return 0
818        elif female:
819            v = True
820        else:
821            v = False
822        datamodel = datastructure.getDataModel()
823        datamodel[self.fields[0]] = v
824        return 1
825
826InitializeClass(WAeUPSexWidget)
827
828widgetRegistry.register(WAeUPSexWidget)
829
830###)
831
832class MatricNoWidget(CPSStringWidget): ###(
833    """ MatricNo Widget"""
834    meta_type = "MatricNo Widget"
835
836    _properties = CPSStringWidget._properties + (
837        {'id': 'matric_no_catalog', 'type': 'string', 'mode': 'w',
838         'label': 'Catalog to search for MatricNo'},
839        { 'id': 'results_catalog', 'type': 'string', 'mode': 'w',
840         'label': 'Results Catalog'},
841         )
842    matric_no_catalog = "" #the catalog to search for matric_no
843    results_catalog = "results_import" #results catalog
844
845    def validate(self, datastructure, **kw):
846        """Validate datastructure and update datamodel."""
847        #import pdb;pdb.set_trace()
848        valid = CPSStringWidget.validate(self, datastructure, **kw)
849        logger = logging.getLogger('Widgets.MatricNoWidget.validate')
850        returning = getattr(self,self.matric_no_catalog)
851        results = getattr(self,self.results_catalog,None)
852        err = 0
853        widget_id = self.getWidgetId()
854        value = datastructure[widget_id]
855        if not valid or not value:
856            err = 'Invalid string'
857            logger.info('Invalid matric_no string %s' % value)
858        else:
859            value = value.upper()
860            datastructure['student'] = None
861            while not err:
862                res = returning(matric_no = value)
863                if len(res) < 1:
864                    logger.info('matric_no %s not found' % value)
865                    err = 'No student with this matriculation number.'
866                    break
867                datastructure['student'] = res[0]
868                if results is not None:
869                    res = results(matric_no = value)
870                    if len(res) < 1:
871                        err = 'No results for this matriculation number'
872                        continue
873                    datastructure['results'] = res
874                break
875        if err:
876            datastructure.setError(widget_id, err)
877        else:
878            datamodel = datastructure.getDataModel()
879            datamodel[self.fields[0]] = value
880        return not err
881
882InitializeClass(MatricNoWidget)
883
884widgetRegistry.register(MatricNoWidget)
885###)
886
887class StudentIdWidget(CPSStringWidget): ###(
888    """ StudentId Widget"""
889    meta_type = "StudentId Widget"
890    def validate(self, datastructure, **kw):
891        """Validate datastructure and update datamodel."""
892        valid = CPSStringWidget.validate(self, datastructure, **kw)
893        logger = logging.getLogger('Widgets.StudentIdWidget.validate')
894        #import pdb;pdb.set_trace()
895        s_cat = self.students_catalog
896        err = 0
897        widget_id = self.getWidgetId()
898        value = datastructure[widget_id]
899        if not valid or not value:
900            err = 'Invalid Id string'
901            logger.info('Invalid id string %s' % value)
902            datastructure['student'] = None
903        else:
904            value = value.upper()
905            res = s_cat(id = value)
906            if not res:
907                logger.info('Student id %s not found' % value)
908                err = 'No student with this Id'
909                datastructure['student'] = None
910            else:
911                datastructure['student'] = res[0]
912        if err:
913            datastructure.setError(widget_id, err)
914        else:
915            datamodel = datastructure.getDataModel()
916            datamodel[self.fields[0]] = value
917        return not err
918
919InitializeClass(StudentIdWidget)
920
921widgetRegistry.register(StudentIdWidget)
922###)
923
924class WAeUPMultilineResultsWidget(CPSStringWidget): ###(
925    """ WAeUPMultilineResults Widget"""
926    meta_type = "WAeUp Multiline Results Widget"
927    _properties = CPSWidget._properties + (
928        {'id': 'nr_of_lines', 'type': 'int', 'mode': 'w',
929         'label': 'Nr of Lines'},
930         )
931    nr_of_lines = 5
932    def prepare(self, datastructure, **kw): ###(
933        """Prepare datastructure from datamodel."""
934        datamodel = datastructure.getDataModel()
935        #import pdb;pdb.set_trace()
936        widget_id = self.getWidgetId()
937        v = datamodel[self.fields[0]]
938        if type(v) is ListType and v:
939            nr_results = len(v)
940        else:
941            v = []
942            nr_results = 0
943        count = 1
944        for s,g in v:
945            wid = "%s%02d"% (widget_id,count)
946            datastructure[wid+'_s'] = s
947            datastructure[wid+'_g'] = g
948            count += 1
949        if nr_results < self.nr_of_lines:
950            for line in range(nr_results,self.nr_of_lines):
951                v.append(('',''))
952                wid = "%s%02d"% (widget_id,line)
953                datastructure[wid+'_s'] = ''
954                datastructure[wid+'_g'] = ''
955        datastructure[widget_id] = v
956        datastructure[widget_id+'_s'] = ''
957        datastructure[widget_id+'_g'] = ''
958    ###)
959
960    def validate(self, datastructure, **kw): ###(
961        """Validate datastructure and update datamodel."""
962        #import pdb;pdb.set_trace()
963        widget_id = self.getWidgetId()
964        err = 0
965        lines = []
966        for line in range(1,30):
967            wid = "%s%02d"% (widget_id,line)
968            if not datastructure.has_key(wid+'_s'):
969                break
970            lines.append((datastructure[wid+'_s'].strip(),
971                         datastructure[wid+'_g'].strip()))
972
973        s = datastructure[widget_id+'_s'].strip()
974        g = datastructure[widget_id+'_g'].strip()
975        if s and g:
976            lines.append((s,g))
977        active = []
978        for s,g in lines:
979            if g != "":
980                active.append((s,g))
981        if err:
982            datastructure.setError(widget_id, err)
983        else:
984            datamodel = datastructure.getDataModel()
985            datamodel[self.fields[0]] = active
986        return not err
987    ###)
988
989    def render(self, mode, datastructure, **kw): ###(
990        """Render in mode from datastructure."""
991        render_method = 'widget_waeup_multiline_result_render'
992        meth = getattr(self, render_method, None)
993        if meth is None:
994            raise RuntimeError("Unknown Render Method %s for widget type %s"
995                               % (render_method, self.getId()))
996        #import pdb;pdb.set_trace()
997        datamodel = datastructure.getDataModel()
998        widget_id = self.getWidgetId()
999        lines = datamodel[self.fields[0]]
1000        if len(lines) < self.nr_of_lines:
1001            for line in range(len(lines),self.nr_of_lines + 1):
1002                lines.append(('',''))
1003        datastructure[widget_id] = lines
1004        datastructure[widget_id+'_s'] = ''
1005        datastructure[widget_id+'_g'] = ''
1006##        count = 1
1007##        for s,g in v:
1008##            wid = "%s%02d"% (widget_id,count)
1009##            count += 1
1010        return meth(mode=mode,
1011                    datastructure=datastructure,
1012                    )
1013    ###)
1014
1015
1016InitializeClass(WAeUPMultilineResultsWidget)
1017widgetRegistry.register(WAeUPMultilineResultsWidget)
1018###)
1019
1020class WAeUPResultsWidget(CPSStringWidget): ###(
1021    """ WAeUPResults Widget"""
1022    meta_type = "WAeUp Results Widget"
1023
1024    def prepare(self, datastructure, **kw): ###(
1025        """Prepare datastructure from datamodel."""
1026        datamodel = datastructure.getDataModel()
1027        v = datamodel[self.fields[0]]
1028        #import pdb;pdb.set_trace()
1029        widget_id = self.getWidgetId()
1030        datastructure[widget_id] = v
1031        datastructure[widget_id+'_s'] = ''
1032        datastructure[widget_id+'_g'] = ''
1033    ###)
1034
1035    def validate(self, datastructure, **kw): ###(
1036        """Validate datastructure and update datamodel."""
1037        #import pdb;pdb.set_trace()
1038        widget_id = self.getWidgetId()
1039        v = datastructure[widget_id]
1040        err = 0
1041        s = datastructure[widget_id+'_s'].strip()
1042        g = datastructure[widget_id+'_g'].strip()
1043        while 1:
1044            if not s and g:
1045                err = "No subject grade for subject"
1046                break
1047            i = 0
1048            done = False
1049            for sv,gv in v:
1050                if sv == s:
1051                    done = True
1052                    if not g:
1053                        v.pop(i)
1054                        break
1055                    v[i] = (s,g)
1056                    break
1057                i += 1
1058            if done:
1059                break
1060            if s and g:
1061                v.append((s,g))
1062            break
1063        if err:
1064            datastructure.setError(widget_id, err)
1065        else:
1066            datamodel = datastructure.getDataModel()
1067            datamodel[self.fields[0]] = v
1068            datastructure[widget_id+'_s'] = s
1069            datastructure[widget_id+'_g'] = g
1070        return not err
1071    ###)
1072
1073    def render(self, mode, datastructure, **kw): ###(
1074        """Render in mode from datastructure."""
1075        render_method = 'widget_waeup_result_render'
1076        meth = getattr(self, render_method, None)
1077        if meth is None:
1078            raise RuntimeError("Unknown Render Method %s for widget type %s"
1079                               % (render_method, self.getId()))
1080        #import pdb;pdb.set_trace()
1081        datamodel = datastructure.getDataModel()
1082        widget_id = self.getWidgetId()
1083        datastructure[widget_id+'_s'] = ''
1084        datastructure[widget_id+'_g'] = ''
1085        return meth(mode=mode,
1086                    datastructure=datastructure,
1087                    )
1088    ###)
1089
1090
1091InitializeClass(WAeUPResultsWidget)
1092widgetRegistry.register(WAeUPResultsWidget)
1093###)
1094
1095class ScratchCardPin: ###(
1096    """the ScratchCardPin"""
1097    def __init__(self,prefix,batch_no,number):
1098        if not batch_no and not number:
1099            s = prefix
1100            if len(s) > 3:
1101                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
1102            else:
1103                prefix,batch_no,number = s,'',''
1104        self.p = prefix
1105        self.b = batch_no
1106        self.n = number
1107
1108    def __str__(self):
1109        return "%s-%s-%s" % (self.p,self.b,self.n)
1110
1111    def __repr__(self):
1112        return "%s%s%s" % (self.p,self.b,self.n)
1113###)
1114
1115class ScratchcardPinWidget(CPSStringWidget): ###(
1116    """ ScratchcardPin Widget"""
1117    meta_type = "Scratchcard Pin Widget"
1118    _properties = CPSWidget._properties + (
1119        {'id': 'prefix', 'type': 'string', 'mode': 'w',
1120         'label': 'Prefix'},
1121         {'id': 'reference', 'type': 'string', 'mode': 'w',
1122         'label': 'Reference Field'},
1123        )
1124    prefix = ''
1125    reference = ''
1126    def prepare(self, datastructure, **kw): ###(
1127        """Prepare datastructure from datamodel."""
1128        datamodel = datastructure.getDataModel()
1129        v = datamodel[self.fields[0]]
1130        widget_id = self.getWidgetId()
1131        #import pdb;pdb.set_trace()
1132        if v and type(v) is StringType:
1133            try:
1134                p,b,n = v.split('-')
1135                v = ScratchCardPin(p,b,n)
1136            except ValueError:
1137                v = ScratchCardPin(v,'','')
1138        if v:
1139            p = '%s' % v.p
1140            b = '%s' % v.b
1141            n = '%s' % v.n
1142        else:
1143            p = self.prefix
1144            if p.startswith('@'):
1145                p = getattr(self,self.prefix[1:])()
1146            b = n = ''
1147            v = ScratchCardPin(p,b,n)
1148        datastructure[widget_id] = v
1149        datastructure[widget_id+'_p'] = p
1150        datastructure[widget_id+'_b'] = b
1151        datastructure[widget_id+'_n'] = n
1152    ###)
1153
1154    def validate(self, datastructure, **kw): ###(
1155        """Validate datastructure and update datamodel."""
1156        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
1157        widget_id = self.getWidgetId()
1158        v = datastructure[widget_id]
1159        #import pdb;pdb.set_trace()
1160        err = 0
1161        mapping = {}
1162        prefix= self.prefix
1163        if prefix.startswith('@'):
1164            prefix= getattr(self,self.prefix[1:])()
1165        b = datastructure[widget_id+'_b'].strip()
1166        n = datastructure[widget_id+'_n'].strip()
1167        pins = self.portal_pins
1168        pin = "%(prefix)s%(b)s%(n)s" % vars()
1169        pin_str = "%(prefix)s-%(b)s-%(n)s" % vars()
1170        do = 1
1171        s_id = str(self.portal_membership.getAuthenticatedMember())
1172        if self.isStaff():
1173            do = 0
1174            err ='You are not a Student. PIN neither checked nor used.'
1175            s_logger.info('%s tried to use scratch card %s' % (s_id,pin_str))
1176        elif len(b) > 1 and b.find('-') > -1:
1177            do = 0
1178            err = 'PIN must not contain "-"'
1179            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
1180        elif n.find('-') > -1:
1181            do = 0
1182            err = 'PIN must not contain "-"'
1183            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
1184        elif len(n) != 10:
1185            do = 0
1186            err = 'Invalid PIN length'
1187            s_logger.info('%s entered invalid PIN with length %d' % (s_id,len(n)))
1188        elif self.reference == "":
1189            ref = s_id
1190        else:
1191            ref = datastructure[self.reference]
1192            if datastructure.errors:
1193                do = 0
1194                datastructure.setError(widget_id, 'PIN neither checked nor used.')
1195                s_logger.info('%s/%s entered wrong data together with PIN %s' % (s_id,ref,pin_str))
1196        while do:
1197            ok = pins.searchAndSetRecord(pin,ref,prefix)
1198            if ok < -2 or ok > 2:
1199                err = 'Unknown error, please report!'
1200                s_logger.info('%s/%s caused unknown error with PIN %s' % (s_id,ref,pin_str))
1201                break
1202            elif ok == -2:
1203                err = 'Service already is activated but with a different PIN.'
1204                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (s_id,ref,pin_str))
1205                break
1206            elif ok == -1:
1207                err = 'Invalid PIN'
1208                s_logger.info('%s/%s entered invalid PIN %s' % (s_id,ref,pin_str))
1209                break
1210            if ok == 0:
1211                err = 'PIN already used'
1212                s_logger.info('%s/%s entered used PIN %s' % (s_id,ref,pin_str))
1213                break
1214            if ok >= 1:
1215                #import pdb;pdb.set_trace()
1216                if self.isStudent():
1217                    if self.reference == "jamb_reg_no":
1218                        err = "You are already logged in."
1219                        s_logger.info('%s/%s checked admission with PIN %s though logged in' % (s_id,ref,pin_str))
1220                        break
1221                    if ok == 1:
1222                        s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
1223                    else:
1224                        s_logger.info('%s/%s repeatedly used PIN %s' % (s_id,ref,pin_str))
1225                    break
1226                else:
1227                    student = getStudentByRegNo(self,ref)
1228                    s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
1229                if student is None:
1230                    err = "Student not found"
1231                    s_logger.info('%s not found in admission list' % (ref))
1232                    break
1233                s_id = student.getId()
1234                if ok == 2:
1235                    if self.reference == "jamb_reg_no":
1236                        if hasattr(self.portal_directories.students,s_id):
1237                            err = "Please login with your Student Id ${id} and 10-digit PIN."
1238                            mapping = {'id': s_id}
1239                            s_logger.info('%s/%s repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
1240                            break
1241                        else:
1242                            s_logger.info('%s/%s (non-member) repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
1243                    else:
1244                        err = "Unknown error"
1245                        s_logger.info('%s/%s repeatedly activated service with PIN %s' % (s_id,ref,pin_str))
1246                        break
1247                try:
1248                    student.getContent().makeStudentMember(s_id,password=pin[4:])
1249                    s_logger.info('%s/%s has been created using PIN %s' % (s_id,ref,pin_str))
1250                except:
1251                    err = "Please login with your Student Id ${id} and 10-digit PIN."
1252                    mapping = {'id': s_id}
1253                    s_logger.info('%s/%s could not be made a member with PIN %s' % (s_id,ref,pin_str))
1254                    break
1255            break
1256        if err:
1257            datastructure.setError(widget_id, err,mapping)
1258        else:
1259            datamodel = datastructure.getDataModel()
1260            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
1261            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
1262            datastructure[widget_id+'_p'] = prefix
1263            datastructure[widget_id+'_b'] = b
1264            datastructure[widget_id+'_n'] = n
1265            datastructure['s_id'] = s_id
1266        return not err
1267
1268###)
1269
1270    def render(self, mode, datastructure, **kw): ###(
1271        """Render in mode from datastructure."""
1272        render_method = 'widget_scratch_card_pin_render'
1273        meth = getattr(self, render_method, None)
1274        if meth is None:
1275            raise RuntimeError("Unknown Render Method %s for widget type %s"
1276                               % (render_method, self.getId()))
1277
1278        # XXX AT: datastructure has to be set again here, in case we're in edit
1279        # or create mode, because a default value has to be provided.
1280        #import pdb;pdb.set_trace()
1281        datamodel = datastructure.getDataModel()
1282        v = datamodel[self.fields[0]]
1283        if v and type(v) is StringType:
1284            try:
1285                p,b,n = v.split('-')
1286                v = ScratchCardPin(p,b,n)
1287            except ValueError:
1288                v = ScratchCardPin(self.prefix,'XXX',v)
1289                pass
1290        if v:
1291            prefix= '%s' % v.p
1292            b = '%s' % v.b
1293            n = '%s' % v.n
1294        else:
1295            prefix= self.prefix
1296            if prefix.startswith('@'):
1297                prefix= getattr(self,self.prefix[1:])()
1298            b = n = ''
1299            v = ScratchCardPin(prefix,b,n)
1300        widget_id = self.getWidgetId()
1301        datastructure[widget_id] = v
1302        datastructure[widget_id+'_p'] = prefix
1303        datastructure[widget_id+'_b'] = b
1304        datastructure[widget_id+'_n'] = n
1305        return meth(mode=mode,
1306                    datastructure=datastructure,
1307                    )
1308    ###)
1309
1310InitializeClass(ScratchcardPinWidget)
1311widgetRegistry.register(ScratchcardPinWidget)
1312###)
1313
1314class PumePinWidget(ScratchcardPinWidget): ###(
1315    """ Pume Pin Widget"""
1316    meta_type = "Pume Pin Widget"
1317
1318    def validate(self, datastructure, **kw): ###(
1319        """Validate datastructure and update datamodel."""
1320        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
1321        widget_id = self.getWidgetId()
1322        v = datastructure[widget_id]
1323        err = 0
1324        mapping = {}
1325        prefix= self.prefix
1326        if prefix.startswith('@'):
1327            prefix= getattr(self,self.prefix[1:])()
1328        b = datastructure[widget_id+'_b'].strip()
1329        n = datastructure[widget_id+'_n'].strip()
1330        pins = self.portal_pins
1331        pin = "%(prefix)s%(b)s%(n)s" % vars()
1332        pin_str = "%(prefix)s-%(b)s-%(n)s" % vars()
1333        do = 1
1334        s_id = str(self.portal_membership.getAuthenticatedMember())
1335        import pdb;pdb.set_trace()
1336        if self.isStaff():
1337            do = 0
1338            err ='You are not a Student. PIN neither checked nor used.'
1339            s_logger.info('%s tried to use scratch card %s' % (s_id,pin_str))
1340        elif len(b) > 1 and b.find('-') > -1:
1341            do = 0
1342            err = 'PIN must not contain "-"'
1343            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
1344        elif n.find('-') > -1:
1345            do = 0
1346            err = 'PIN must not contain "-"'
1347            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
1348        elif len(n) != 10:
1349            do = 0
1350            err = 'Invalid PIN length'
1351            s_logger.info('%s entered invalid PIN with length %d' % (s_id,len(n)))
1352        elif self.reference == "":
1353            ref = s_id
1354        else:
1355            ref = datastructure[self.reference]
1356            if datastructure.errors:
1357                do = 0
1358                datastructure.setError(widget_id, 'PIN neither checked nor used.')
1359                s_logger.info('%s/%s entered wrong data together with PIN %s' % (s_id,ref,pin_str))
1360        while do:
1361            ok = pins.searchAndSetRecord(pin,ref,prefix)
1362            if ok < -2 or ok > 2:
1363                err = 'Unknown error, please report!'
1364                s_logger.info('%s/%s caused unknown error with PIN %s' % (s_id,ref,pin_str))
1365                break
1366            elif ok == -2:
1367                err = 'Service already is activated but with a different PIN.'
1368                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (s_id,ref,pin_str))
1369                break
1370            elif ok == -1:
1371                err = 'Invalid PIN'
1372                s_logger.info('%s/%s entered invalid PIN %s' % (s_id,ref,pin_str))
1373                break
1374            if ok == 0:
1375                err = 'PIN already used'
1376                s_logger.info('%s/%s entered used PIN %s' % (s_id,ref,pin_str))
1377                break
1378            if ok >= 1:
1379                #import pdb;pdb.set_trace()
1380                if self.isStudent():
1381                    err = "This is only for Pume application."
1382                    s_logger.info('%s/%s applied for PUME with PIN %s' % (s_id,ref,pin_str))
1383                    break
1384                else:
1385                    applicant = datastructure['record']
1386                    if not applicant.pin:
1387                        s_logger.info('%s successfully used PIN %s' % (ref,pin_str))
1388                        d = {}
1389                        d['reg_no'] = applicant.reg_no
1390                        d['pin'] = n
1391                        self.new_students.modifyRecord(**d)
1392                    elif applicant.pin != pin_str:
1393                        s_logger.info('%s/%s repeatedly applied for PUME with different PIN %s' % (s_id,ref,pin_str))
1394                    elif applicant.pin == pin_str:
1395                        s_logger.info('%s/%s repeatedly applied for PUME with PIN %s' % (s_id,ref,pin_str))
1396            break
1397        if err:
1398            datastructure.setError(widget_id, err,mapping)
1399        else:
1400            datamodel = datastructure.getDataModel()
1401            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
1402            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
1403            datastructure[widget_id+'_p'] = prefix
1404            datastructure[widget_id+'_b'] = b
1405            datastructure[widget_id+'_n'] = n
1406            datastructure['s_id'] = s_id
1407        return not err
1408    ###)
1409
1410InitializeClass(PumePinWidget)
1411widgetRegistry.register(PumePinWidget)
1412###)
1413
1414class WAeUPImageWidget(CPSImageWidget): ###(
1415    """Photo widget."""
1416    meta_type = 'WAeUP Image Widget'
1417
1418    def render(self, mode, datastructure, **kw):
1419        render_method = 'widget_waeup_image_render'
1420        meth = getattr(self, render_method, None)
1421        if meth is None:
1422            raise RuntimeError("Unknown Render Method %s for widget type %s"
1423                               % (render_method, self.getId()))
1424        img_info = self.getImageInfo(datastructure)
1425        return meth(mode=mode, datastructure=datastructure, **img_info)
1426
1427InitializeClass(WAeUPImageWidget)
1428
1429widgetRegistry.register(WAeUPImageWidget)
1430###)
1431
1432
1433###########
1434
Note: See TracBrowser for help on using the repository browser.