source: WAeUP_SRP/trunk/Widgets.py @ 2096

Last change on this file since 2096 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
RevLine 
[47]1#-*- mode: python; mode: fold -*-
[990]2# $Id: Widgets.py 2095 2007-08-13 15:33:15Z henrik $
[295]3from cgi import escape
[502]4from types import *
[22]5from Globals import InitializeClass
[199]6##from Products.CPSSchemas.Widget import CPSWidgetType
[295]7from Products.CMFCore.utils import getToolByName
[1772]8from Products.CPSSchemas.BasicWidgets import CPSBooleanWidget, CPSWidget, CPSStringWidget, CPSEmailWidget,CPSImageWidget
[295]9from Products.CPSSchemas.BasicWidgets import renderHtmlTag,CPSSelectWidget, CPSStringWidget
[22]10from Products.CPSSchemas.ExtendedWidgets import CPSDateTimeWidget
[199]11from Products.CPSSchemas.Widget import widgetRegistry
12##from Products.CPSSchemas.WidgetTypesTool import WidgetTypeRegistry
[22]13from DateTime.DateTime import DateTime
14from AccessControl import getSecurityManager
[502]15from Products.WAeUP_SRP.Students import getStudentByRegNo
[1747]16from Products.WAeUP_SRP.Academics import makeCertificateCode
[22]17from re import compile
[952]18import logging
[1915]19import operator
[22]20
[952]21#from zLOG import LOG, DEBUG
[22]22
[295]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()
[444]48            res = renderHtmlTag('select',
49                                name='%s.%s:records' % (self.record_id,html_widget_id),
[295]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
[373]77class CPSStringWidgetForRecord(CPSStringWidget): ###(
[295]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,
[444]99                  'name': '%s.%s:records' % (self.record_id,html_widget_id),
[295]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
[373]112###)
113
114class CertificateCourseIdWidget(CPSStringWidget): ###(
115    """ CertificateCourseId Widget"""
116    meta_type = "CertificateCourseId Widget"
[444]117
[373]118    def validate(self, datastructure, **kw):
119        """Validate datastructure and update datamodel."""
[444]120
[373]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"})]
[381]129            if hasattr(self.aq_parent,value):
[1891]130                err = 'Course already exists'
[381]131            elif value not in c_ids:
[1891]132                err = 'Course does not exist'
[373]133            if err:
134                datastructure.setError(widget_id, err)
135            else:
136                datamodel = datastructure.getDataModel()
137                datamodel[self.fields[0]] = value
[444]138
[373]139            return not err
140
141InitializeClass(CertificateCourseIdWidget)
142
143widgetRegistry.register(CertificateCourseIdWidget)
[551]144###)
[373]145
[551]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:
[1891]162                err = 'Course already exists'
[551]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
[373]176###)
177
[1820]178class WAeUPStudyModeWidget(CPSSelectWidget): ###(
[1986]179    """WAeUP StudyMode Widget."""
[1820]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:
[1836]201            v = value = 'ume_ft'
[1820]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
[1804]247class WAeUPSessionWidget(CPSSelectWidget): ###(
[1986]248    """WAeUP Session Widget."""
[1804]249    meta_type = 'WAeUP Session Widget'
[2095]250
[1804]251    def _getSessions(self):
252        current_year = DateTime().year()
[1986]253        d = {'-1': 'N/A'}
[1804]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
[1805]267
[1804]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:
[1986]297                vocabulary_items.sort(key=operator.itemgetter(0))
[1804]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):
[1986]323        d = {'000':'N/A'}
[1804]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
[1805]337
338        if not value:
[1804]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:
[1986]365                vocabulary_items.sort(key=operator.itemgetter(0))
[1804]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): ###(
[1986]387    """WAeUP Verdict Widget."""
[1804]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
[2094]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
[2095]524
[2094]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())
[2095]535            datamodel[self.fields[0]] =   state + "_" + lga
[2094]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
[714]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:
[926]587                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
[714]588                                     if r]
[1038]589            except (ValueError,IndexError),msg:
[714]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
[388]603class WAeUPIdWidget(CPSStringWidget): ###(
604    """ WAeUPId Widget"""
605    meta_type = "WAeUPId Widget"
[444]606
[388]607    def validate(self, datastructure, **kw):
608        """Validate datastructure and update datamodel."""
[444]609
[388]610        valid = CPSStringWidget.validate(self, datastructure, **kw)
[422]611        id_pat_str = r"\S"
612        inv_id_pat = compile(r"^%s$" % id_pat_str)
[388]613        if not valid:
614            return 0
615        else:
[586]616            portal_type_query = {'query':['Faculty',
617                                          'Department',
618                                          'Course',
619                                          'Certificate',
620                                          'CertificateCourse',]}
[388]621            widget_id = self.getWidgetId()
[2013]622            value = datastructure[widget_id]  #.upper()  is not necessary here because it's also done in waeup_document_create_do
[388]623            err = 0
[1907]624            mapping = {}
[440]625            if len(value.split()) > 1:
[783]626                err = 'Invalid Id, Id contains space(s).'
[586]627            elif self.portal_catalog(portal_type=portal_type_query,id=value):
[1718]628                brain = self.portal_catalog(portal_type=portal_type_query,id=value)[0]
[1907]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                           }
[388]634            if err:
[1907]635                datastructure.setError(widget_id, err, mapping)
[388]636            else:
637                datamodel = datastructure.getDataModel()
638                datamodel[self.fields[0]] = value
[444]639
[388]640            return not err
641
642InitializeClass(WAeUPIdWidget)
643
644widgetRegistry.register(WAeUPIdWidget)
645
646
647###)
648
[1025]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()
[1747]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()
[1025]662        id_pat_str = r"\S"
663        inv_id_pat = compile(r"^%s$" % id_pat_str)
[1747]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)
[1025]671        else:
[1747]672            datamodel = datastructure.getDataModel()
673            datamodel[self.fields[0]] = value
674        return not err
[1025]675
676InitializeClass(StudyCourseWidget)
677
678widgetRegistry.register(StudyCourseWidget)
679###)
680
[463]681class JambRegNoWidget(CPSStringWidget): ###(
682    """ JambRegNo Widget"""
683    meta_type = "JambRegNo Widget"
[1169]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 = ""
[463]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)
[1169]699        jamb_nr_catalog = getattr(self,self.catalog)
700        widget_id = self.getWidgetId()
701        value = datastructure[widget_id].upper()
702        err = 0
[2094]703        #import pdb;pdb.set_trace()
704        if kw.has_key('mode'):
705            mode = kw['mode']
706        else:
707            mode = "xxxx"
[2095]708        if not valid:
[1793]709            err = 'Invalid number'
[1169]710        elif self.reference == '':
711            #s = getStudentByRegNo(self,value)
712            pume = jamb_nr_catalog(jamb_reg_no = value)
713            if len(pume) < 1:
[1891]714                err = 'No student record with this registration number.'
[1169]715            else:
716                datastructure['pume'] = pume[0]
[2094]717        elif mode == 'add':
718            pass
[2095]719        elif self.reference != '' and self.catalog == "applicants_catalog":
[2094]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]
[463]725        else:
[1169]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:
[1783]730                err = 'Registration number does not match.'
[1169]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
[463]737
738InitializeClass(JambRegNoWidget)
739
740widgetRegistry.register(JambRegNoWidget)
[47]741###)
742
[1175]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"
[1747]753    matric_no_catalog = 'returning_import'
[1175]754    check_fields = ("Firstname", "Middlename","Lastname")
755    def validate(self, datastructure, **kw):
756        """Validate datastructure and update datamodel."""
[1571]757        logger = logging.getLogger('Widgets.SecretWidget.validate')
[1175]758        valid = CPSStringWidget.validate(self, datastructure, **kw)
759        widget_id = self.getWidgetId()
760        value = datastructure[widget_id].upper()
761        err = 0
[1189]762        record = datastructure.get(self.reference,None)
[1747]763        #import pdb;pdb.set_trace()
[1379]764        if not valid or len(value) < 2:
[1793]765            err = 'Invalid string'
[1189]766        elif not record or datastructure.errors:
[1177]767            err = 0
[1175]768        else:
769            found = False
770            cvs = []
771            for field in self.check_fields:
772                cv = getattr(record,field).upper()
[1243]773                if len(cv.split()) > 1:
774                    for splited in cv.split():
[1747]775                        cvs.append(splited.strip())
[1243]776                else:
777                    cvs.append(cv)
[1747]778            for cv in cvs:
[1175]779                if cv  == value.upper():
780                    found = True
781                    break
782            matric_no = record.matric_no
783            name = " ".join(cvs)
784            if not found:
[1573]785                logger.info('%(matric_no)s did not find %(value)s in %(name)s' % vars())
786                err = 'No name does match.'
[1175]787            else:
[1571]788                logger.info('%(matric_no)s found %(value)s in %(name)s' % vars())
[1175]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
[1804]801class WAeUPSexWidget(CPSBooleanWidget): ###(
[1772]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
[1804]830###)
831
[1146]832class MatricNoWidget(CPSStringWidget): ###(
833    """ MatricNo Widget"""
834    meta_type = "MatricNo Widget"
[1747]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
[1748]843    results_catalog = "results_import" #results catalog
[1747]844
[1146]845    def validate(self, datastructure, **kw):
846        """Validate datastructure and update datamodel."""
[1747]847        #import pdb;pdb.set_trace()
[1146]848        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1571]849        logger = logging.getLogger('Widgets.MatricNoWidget.validate')
[1747]850        returning = getattr(self,self.matric_no_catalog)
851        results = getattr(self,self.results_catalog,None)
[1146]852        err = 0
[1189]853        widget_id = self.getWidgetId()
854        value = datastructure[widget_id]
855        if not valid or not value:
[1891]856            err = 'Invalid string'
[1573]857            logger.info('Invalid matric_no string %s' % value)
[1146]858        else:
[1189]859            value = value.upper()
[1177]860            datastructure['student'] = None
[1146]861            while not err:
[1151]862                res = returning(matric_no = value)
[1146]863                if len(res) < 1:
[1573]864                    logger.info('matric_no %s not found' % value)
[1915]865                    err = 'No student with this matriculation number.'
[1747]866                    break
[1146]867                datastructure['student'] = res[0]
[1747]868                if results is not None:
869                    res = results(matric_no = value)
870                    if len(res) < 1:
[1891]871                        err = 'No results for this matriculation number'
[1747]872                        continue
873                    datastructure['results'] = res
[1146]874                break
[1189]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
[1146]881
882InitializeClass(MatricNoWidget)
883
884widgetRegistry.register(MatricNoWidget)
885###)
886
[1393]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)
[1571]893        logger = logging.getLogger('Widgets.StudentIdWidget.validate')
[1393]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:
[1891]900            err = 'Invalid Id string'
[1573]901            logger.info('Invalid id string %s' % value)
[1449]902            datastructure['student'] = None
[1393]903        else:
904            value = value.upper()
905            res = s_cat(id = value)
906            if not res:
[1573]907                logger.info('Student id %s not found' % value)
[1891]908                err = 'No student with this Id'
[1393]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
[1146]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()))
[1155]972
[1146]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
[794]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()
[807]1030        datastructure[widget_id] = v
[794]1031        datastructure[widget_id+'_s'] = ''
1032        datastructure[widget_id+'_g'] = ''
1033    ###)
1034
1035    def validate(self, datastructure, **kw): ###(
1036        """Validate datastructure and update datamodel."""
[807]1037        #import pdb;pdb.set_trace()
[794]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()
[807]1043        while 1:
1044            if not s and g:
[1891]1045                err = "No subject grade for subject"
[807]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
[794]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
[488]1095class ScratchCardPin: ###(
1096    """the ScratchCardPin"""
1097    def __init__(self,prefix,batch_no,number):
[990]1098        if not batch_no and not number:
1099            s = prefix
[996]1100            if len(s) > 3:
[990]1101                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
1102            else:
[996]1103                prefix,batch_no,number = s,'',''
[488]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)
[1146]1110
1111    def __repr__(self):
1112        return "%s%s%s" % (self.p,self.b,self.n)
[488]1113###)
1114
[47]1115class ScratchcardPinWidget(CPSStringWidget): ###(
[22]1116    """ ScratchcardPin Widget"""
[199]1117    meta_type = "Scratchcard Pin Widget"
[488]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 = ''
[502]1126    def prepare(self, datastructure, **kw): ###(
[488]1127        """Prepare datastructure from datamodel."""
1128        datamodel = datastructure.getDataModel()
1129        v = datamodel[self.fields[0]]
1130        widget_id = self.getWidgetId()
[742]1131        #import pdb;pdb.set_trace()
[747]1132        if v and type(v) is StringType:
[990]1133            try:
1134                p,b,n = v.split('-')
1135                v = ScratchCardPin(p,b,n)
1136            except ValueError:
1137                v = ScratchCardPin(v,'','')
[488]1138        if v:
[742]1139            p = '%s' % v.p
[488]1140            b = '%s' % v.b
1141            n = '%s' % v.n
1142        else:
[742]1143            p = self.prefix
1144            if p.startswith('@'):
1145                p = getattr(self,self.prefix[1:])()
[488]1146            b = n = ''
[742]1147            v = ScratchCardPin(p,b,n)
[488]1148        datastructure[widget_id] = v
[742]1149        datastructure[widget_id+'_p'] = p
[488]1150        datastructure[widget_id+'_b'] = b
1151        datastructure[widget_id+'_n'] = n
[1376]1152    ###)
[758]1153
[1169]1154    def validate(self, datastructure, **kw): ###(
[22]1155        """Validate datastructure and update datamodel."""
[1571]1156        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
[488]1157        widget_id = self.getWidgetId()
1158        v = datastructure[widget_id]
[996]1159        #import pdb;pdb.set_trace()
[488]1160        err = 0
[1907]1161        mapping = {}
[742]1162        prefix= self.prefix
1163        if prefix.startswith('@'):
1164            prefix= getattr(self,self.prefix[1:])()
[488]1165        b = datastructure[widget_id+'_b'].strip()
1166        n = datastructure[widget_id+'_n'].strip()
[502]1167        pins = self.portal_pins
[742]1168        pin = "%(prefix)s%(b)s%(n)s" % vars()
[2001]1169        pin_str = "%(prefix)s-%(b)s-%(n)s" % vars()
[816]1170        do = 1
[1025]1171        s_id = str(self.portal_membership.getAuthenticatedMember())
[1343]1172        if self.isStaff():
[1326]1173            do = 0
1174            err ='You are not a Student. PIN neither checked nor used.'
[1571]1175            s_logger.info('%s tried to use scratch card %s' % (s_id,pin_str))
[1557]1176        elif len(b) > 1 and b.find('-') > -1:
1177            do = 0
[1573]1178            err = 'PIN must not contain "-"'
1179            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1557]1180        elif n.find('-') > -1:
1181            do = 0
[1573]1182            err = 'PIN must not contain "-"'
1183            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1376]1184        elif len(n) != 10:
1185            do = 0
[1891]1186            err = 'Invalid PIN length'
[1573]1187            s_logger.info('%s entered invalid PIN with length %d' % (s_id,len(n)))
[1326]1188        elif self.reference == "":
[1030]1189            ref = s_id
[635]1190        else:
1191            ref = datastructure[self.reference]
[843]1192            if datastructure.errors:
[816]1193                do = 0
[1805]1194                datastructure.setError(widget_id, 'PIN neither checked nor used.')
[1571]1195                s_logger.info('%s/%s entered wrong data together with PIN %s' % (s_id,ref,pin_str))
[816]1196        while do:
1197            ok = pins.searchAndSetRecord(pin,ref,prefix)
[1030]1198            if ok < -2 or ok > 2:
1199                err = 'Unknown error, please report!'
[1571]1200                s_logger.info('%s/%s caused unknown error with PIN %s' % (s_id,ref,pin_str))
[1030]1201                break
1202            elif ok == -2:
[1783]1203                err = 'Service already is activated but with a different PIN.'
[1571]1204                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (s_id,ref,pin_str))
[710]1205                break
1206            elif ok == -1:
[1793]1207                err = 'Invalid PIN'
[1571]1208                s_logger.info('%s/%s entered invalid PIN %s' % (s_id,ref,pin_str))
[502]1209                break
1210            if ok == 0:
[1571]1211                err = 'PIN already used'
1212                s_logger.info('%s/%s entered used PIN %s' % (s_id,ref,pin_str))
[502]1213                break
1214            if ok >= 1:
[710]1215                #import pdb;pdb.set_trace()
[635]1216                if self.isStudent():
[992]1217                    if self.reference == "jamb_reg_no":
[997]1218                        err = "You are already logged in."
[1573]1219                        s_logger.info('%s/%s checked admission with PIN %s though logged in' % (s_id,ref,pin_str))
[992]1220                        break
[1082]1221                    if ok == 1:
[1571]1222                        s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[1032]1223                    else:
[1571]1224                        s_logger.info('%s/%s repeatedly used PIN %s' % (s_id,ref,pin_str))
[637]1225                    break
[635]1226                else:
1227                    student = getStudentByRegNo(self,ref)
[1571]1228                    s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[502]1229                if student is None:
[1793]1230                    err = "Student not found"
[1571]1231                    s_logger.info('%s not found in admission list' % (ref))
[502]1232                    break
[648]1233                s_id = student.getId()
[502]1234                if ok == 2:
[990]1235                    if self.reference == "jamb_reg_no":
1236                        if hasattr(self.portal_directories.students,s_id):
[1907]1237                            err = "Please login with your Student Id ${id} and 10-digit PIN."
1238                            mapping = {'id': s_id}
[1571]1239                            s_logger.info('%s/%s repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]1240                            break
1241                        else:
[1571]1242                            s_logger.info('%s/%s (non-member) repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]1243                    else:
[1891]1244                        err = "Unknown error"
[1571]1245                        s_logger.info('%s/%s repeatedly activated service with PIN %s' % (s_id,ref,pin_str))
[986]1246                        break
1247                try:
1248                    student.getContent().makeStudentMember(s_id,password=pin[4:])
[1571]1249                    s_logger.info('%s/%s has been created using PIN %s' % (s_id,ref,pin_str))
[986]1250                except:
[1907]1251                    err = "Please login with your Student Id ${id} and 10-digit PIN."
1252                    mapping = {'id': s_id}
[1571]1253                    s_logger.info('%s/%s could not be made a member with PIN %s' % (s_id,ref,pin_str))
[986]1254                    break
[502]1255            break
[488]1256        if err:
[1907]1257            datastructure.setError(widget_id, err,mapping)
[488]1258        else:
1259            datamodel = datastructure.getDataModel()
[742]1260            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
1261            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
1262            datastructure[widget_id+'_p'] = prefix
[488]1263            datastructure[widget_id+'_b'] = b
1264            datastructure[widget_id+'_n'] = n
[502]1265            datastructure['s_id'] = s_id
[488]1266        return not err
[444]1267
[1169]1268###)
1269
[502]1270    def render(self, mode, datastructure, **kw): ###(
[488]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]]
[502]1283        if v and type(v) is StringType:
[990]1284            try:
1285                p,b,n = v.split('-')
1286                v = ScratchCardPin(p,b,n)
1287            except ValueError:
[2002]1288                v = ScratchCardPin(self.prefix,'XXX',v)
[996]1289                pass
[488]1290        if v:
[742]1291            prefix= '%s' % v.p
[488]1292            b = '%s' % v.b
1293            n = '%s' % v.n
[22]1294        else:
[742]1295            prefix= self.prefix
1296            if prefix.startswith('@'):
1297                prefix= getattr(self,self.prefix[1:])()
[488]1298            b = n = ''
[742]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
[758]1305        return meth(mode=mode,
1306                    datastructure=datastructure,
[488]1307                    )
[523]1308    ###)
[488]1309
[22]1310InitializeClass(ScratchcardPinWidget)
[199]1311widgetRegistry.register(ScratchcardPinWidget)
[2094]1312###)
[22]1313
[2094]1314class PumePinWidget(ScratchcardPinWidget): ###(
1315    """ Pume Pin Widget"""
1316    meta_type = "Pume Pin Widget"
[47]1317
[2094]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']
[2095]1386                    if not applicant.pin:
[2094]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)
[47]1412###)
1413
[1169]1414class WAeUPImageWidget(CPSImageWidget): ###(
[537]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)
[1804]1430###)
[537]1431
1432
[22]1433###########
1434
Note: See TracBrowser for help on using the repository browser.