source: WAeUP_SRP/trunk/Widgets.py @ 1785

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