source: WAeUP_SRP/branches/regebro-noskins/Widgets.py @ 5035

Last change on this file since 5035 was 1449, checked in by joachim, 18 years ago

modified importReservedBeds
fixReservedBeds
added release_bed
many documentation addons for xml-files

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