source: WAeUP_SRP/trunk/Widgets.py @ 1405

Last change on this file since 1405 was 1393, checked in by joachim, 18 years ago

new method book_reserved_bed to book a reserved bed for a student

  • Property svn:keywords set to Id
File size: 32.8 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Widgets.py 1393 2007-02-05 21:42:08Z 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
280##class StudentIdWidget(CPSStringWidget): ###(
281##    """ StudentId Widget"""
282##    meta_type = "StudentId Widget"
283##    digits = 8
284##    digits_str = "N"*digits
285##    letters = 2
286##    letters_str = "L"*letters
287##
288##    def validate(self, datastructure, **kw):
289##        """Validate datastructure and update datamodel."""
290##
291##        valid = CPSStringWidget.validate(self, datastructure, **kw)
292##        if not valid:
293##            return 0
294##        else:
295##            widget_id = self.getWidgetId()
296##            value = datastructure[widget_id]
297##            err = 0
298##            if not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
299##                err = 'Invalid Registration Number in the format: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
300##            if err:
301##                datastructure.setError(widget_id, err)
302##            else:
303##                datamodel = datastructure.getDataModel()
304##                datamodel[self.fields[0]] = value
305##
306##            return not err
307##
308##InitializeClass(StudentIdWidget)
309##widgetRegistry.register(StudentIdWidget)
310##
311#####)
312
313class JambRegNoWidget(CPSStringWidget): ###(
314    """ JambRegNo Widget"""
315    meta_type = "JambRegNo Widget"
316    _properties = CPSStringWidget._properties + (
317        {'id': 'catalog', 'type': 'string', 'mode': 'w',
318         'label': 'Catalog to search'},
319         {'id': 'reference', 'type': 'string', 'mode': 'w',
320         'label': 'Reference Field'},
321         )
322    catalog = "portal_pumeresults" #the catalog to search for jamb_reg_no
323    reference = ""
324    digits = 8
325    digits_str = "N"*digits
326    letters = 2
327    letters_str = "L"*letters
328    def validate(self, datastructure, **kw):
329        """Validate datastructure and update datamodel."""
330        valid = CPSStringWidget.validate(self, datastructure, **kw)
331        #import pdb;pdb.set_trace()
332        jamb_nr_catalog = getattr(self,self.catalog)
333        widget_id = self.getWidgetId()
334        value = datastructure[widget_id].upper()
335        err = 0
336        if not valid: #or not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
337            #err = 'Invalid number, the expected format is: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
338            err = 'Invalid number'
339        elif self.reference == '':
340            #s = getStudentByRegNo(self,value)
341            pume = jamb_nr_catalog(jamb_reg_no = value)
342            if len(pume) < 1:
343                err = 'No Student with JAMB RegNo %s.' % (value)
344            else:
345                datastructure['pume'] = pume[0]
346        else:
347            #import pdb;pdb.set_trace()
348            record = datastructure[self.reference]
349            #jamb_reg_no = getattr(record,widget_id)
350            jamb_reg_no = record.Entryregno
351            if jamb_reg_no != value:
352                err = 'Entry Registration Nr does not match.'
353        if err:
354            datastructure.setError(widget_id, err)
355        else:
356            datamodel = datastructure.getDataModel()
357            datamodel[self.fields[0]] = value
358        return not err
359
360InitializeClass(JambRegNoWidget)
361
362widgetRegistry.register(JambRegNoWidget)
363###)
364
365class SecretWidget(CPSStringWidget): ###(
366    """ Secret Widget"""
367    meta_type = "Secret Widget"
368    _properties = CPSStringWidget._properties + (
369        {'id': 'reference', 'type': 'string', 'mode': 'w',
370         'label': 'Reference Record'},
371         {'id': 'check_fields', 'type': 'tokens', 'mode': 'w',
372         'label': 'Fields to check'},
373         )
374    reference = "student"
375    check_fields = ("Firstname", "Middlename","Lastname")
376    def validate(self, datastructure, **kw):
377        """Validate datastructure and update datamodel."""
378        logger = logging.getLogger('Secret.Validate')
379        valid = CPSStringWidget.validate(self, datastructure, **kw)
380        #import pdb;pdb.set_trace()
381        widget_id = self.getWidgetId()
382        value = datastructure[widget_id].upper()
383        err = 0
384        record = datastructure.get(self.reference,None)
385        if not valid or len(value) < 2:
386            err = 'Invalid String'
387        elif not record or datastructure.errors:
388            err = 0
389        else:
390            found = False
391            cvs = []
392            for field in self.check_fields:
393                cv = getattr(record,field).upper()
394                if len(cv.split()) > 1:
395                    for splited in cv.split():
396                        cvs.append(splited)
397                else:
398                    cvs.append(cv)
399                if cv  == value.upper():
400                    found = True
401                    break
402            matric_no = record.matric_no
403            name = " ".join(cvs)
404            if not found:
405                logger.info('"%(matric_no)s","mismatch", "%(value)s", "not in","%(name)s"' % vars())
406                err = 'No Name does match.'
407            else:
408                logger.info('"%(matric_no)s","found", "%(value)s", "in","%(name)s"' % vars())
409        if err:
410            datastructure.setError(widget_id, err)
411        else:
412            datamodel = datastructure.getDataModel()
413            datamodel[self.fields[0]] = value
414        return not err
415
416InitializeClass(SecretWidget)
417
418widgetRegistry.register(SecretWidget)
419###)
420
421class MatricNoWidget(CPSStringWidget): ###(
422    """ MatricNo Widget"""
423    meta_type = "MatricNo Widget"
424    def validate(self, datastructure, **kw):
425        """Validate datastructure and update datamodel."""
426        valid = CPSStringWidget.validate(self, datastructure, **kw)
427        logger = logging.getLogger('MatricNo.Validate')
428        #import pdb;pdb.set_trace()
429        returning = self.returning_import
430        results = self.results_import
431        err = 0
432        widget_id = self.getWidgetId()
433        value = datastructure[widget_id]
434        if not valid or not value:
435            err = 'Invalid MatricNo String %s.' % value
436            logger.info('"%s","invalid MatricNo String"' % value)
437        else:
438            value = value.upper()
439            datastructure['student'] = None
440            while not err:
441                res = returning(matric_no = value)
442                if len(res) < 1:
443                    logger.info('"%s","MatricNo not found."' % value)
444                    err = 'No Student with MatricNo %s.' % (value)
445                    continue
446                datastructure['student'] = res[0]
447                res = results(matric_no = value)
448                if len(res) < 1:
449                    err = 'No Results with MatricNo %s.' % (value)
450                    continue
451                datastructure['results'] = res
452                break
453        if err:
454            datastructure.setError(widget_id, err)
455        else:
456            datamodel = datastructure.getDataModel()
457            datamodel[self.fields[0]] = value
458        return not err
459
460InitializeClass(MatricNoWidget)
461
462widgetRegistry.register(MatricNoWidget)
463###)
464
465class StudentIdWidget(CPSStringWidget): ###(
466    """ StudentId Widget"""
467    meta_type = "StudentId Widget"
468    def validate(self, datastructure, **kw):
469        """Validate datastructure and update datamodel."""
470        valid = CPSStringWidget.validate(self, datastructure, **kw)
471        logger = logging.getLogger('StudentId.Validate')
472        #import pdb;pdb.set_trace()
473        s_cat = self.students_catalog
474        err = 0
475        widget_id = self.getWidgetId()
476        value = datastructure[widget_id]
477        if not valid or not value:
478            err = 'Invalid StudentId String %s.' % value
479            logger.info('"%s","invalid StudentId String"' % value)
480            datastructure['student'] = res
481        else:
482            value = value.upper()
483            res = s_cat(id = value)
484            if not res:
485                logger.info('"%s","StudentId not found."' % value)
486                err = 'No Student with StudentId %s.' % (value)
487                datastructure['student'] = None
488            else:
489                datastructure['student'] = res[0]
490        if err:
491            datastructure.setError(widget_id, err)
492        else:
493            datamodel = datastructure.getDataModel()
494            datamodel[self.fields[0]] = value
495        return not err
496
497InitializeClass(StudentIdWidget)
498
499widgetRegistry.register(StudentIdWidget)
500###)
501
502class WAeUPMultilineResultsWidget(CPSStringWidget): ###(
503    """ WAeUPMultilineResults Widget"""
504    meta_type = "WAeUp Multiline Results Widget"
505    _properties = CPSWidget._properties + (
506        {'id': 'nr_of_lines', 'type': 'int', 'mode': 'w',
507         'label': 'Nr of Lines'},
508         )
509    nr_of_lines = 5
510    def prepare(self, datastructure, **kw): ###(
511        """Prepare datastructure from datamodel."""
512        datamodel = datastructure.getDataModel()
513        #import pdb;pdb.set_trace()
514        widget_id = self.getWidgetId()
515        v = datamodel[self.fields[0]]
516        if type(v) is ListType and v:
517            nr_results = len(v)
518        else:
519            v = []
520            nr_results = 0
521        count = 1
522        for s,g in v:
523            wid = "%s%02d"% (widget_id,count)
524            datastructure[wid+'_s'] = s
525            datastructure[wid+'_g'] = g
526            count += 1
527        if nr_results < self.nr_of_lines:
528            for line in range(nr_results,self.nr_of_lines):
529                v.append(('',''))
530                wid = "%s%02d"% (widget_id,line)
531                datastructure[wid+'_s'] = ''
532                datastructure[wid+'_g'] = ''
533        datastructure[widget_id] = v
534        datastructure[widget_id+'_s'] = ''
535        datastructure[widget_id+'_g'] = ''
536    ###)
537
538    def validate(self, datastructure, **kw): ###(
539        """Validate datastructure and update datamodel."""
540        #import pdb;pdb.set_trace()
541        widget_id = self.getWidgetId()
542        err = 0
543        lines = []
544        for line in range(1,30):
545            wid = "%s%02d"% (widget_id,line)
546            if not datastructure.has_key(wid+'_s'):
547                break
548            lines.append((datastructure[wid+'_s'].strip(),
549                         datastructure[wid+'_g'].strip()))
550
551        s = datastructure[widget_id+'_s'].strip()
552        g = datastructure[widget_id+'_g'].strip()
553        if s and g:
554            lines.append((s,g))
555        active = []
556        for s,g in lines:
557            if g != "":
558                active.append((s,g))
559        if err:
560            datastructure.setError(widget_id, err)
561        else:
562            datamodel = datastructure.getDataModel()
563            datamodel[self.fields[0]] = active
564        return not err
565    ###)
566
567    def render(self, mode, datastructure, **kw): ###(
568        """Render in mode from datastructure."""
569        render_method = 'widget_waeup_multiline_result_render'
570        meth = getattr(self, render_method, None)
571        if meth is None:
572            raise RuntimeError("Unknown Render Method %s for widget type %s"
573                               % (render_method, self.getId()))
574        #import pdb;pdb.set_trace()
575        datamodel = datastructure.getDataModel()
576        widget_id = self.getWidgetId()
577        lines = datamodel[self.fields[0]]
578        if len(lines) < self.nr_of_lines:
579            for line in range(len(lines),self.nr_of_lines + 1):
580                lines.append(('',''))
581        datastructure[widget_id] = lines
582        datastructure[widget_id+'_s'] = ''
583        datastructure[widget_id+'_g'] = ''
584##        count = 1
585##        for s,g in v:
586##            wid = "%s%02d"% (widget_id,count)
587##            count += 1
588        return meth(mode=mode,
589                    datastructure=datastructure,
590                    )
591    ###)
592
593
594InitializeClass(WAeUPMultilineResultsWidget)
595widgetRegistry.register(WAeUPMultilineResultsWidget)
596###)
597
598class WAeUPResultsWidget(CPSStringWidget): ###(
599    """ WAeUPResults Widget"""
600    meta_type = "WAeUp Results Widget"
601
602    def prepare(self, datastructure, **kw): ###(
603        """Prepare datastructure from datamodel."""
604        datamodel = datastructure.getDataModel()
605        v = datamodel[self.fields[0]]
606        #import pdb;pdb.set_trace()
607        widget_id = self.getWidgetId()
608        datastructure[widget_id] = v
609        datastructure[widget_id+'_s'] = ''
610        datastructure[widget_id+'_g'] = ''
611    ###)
612
613    def validate(self, datastructure, **kw): ###(
614        """Validate datastructure and update datamodel."""
615        #import pdb;pdb.set_trace()
616        widget_id = self.getWidgetId()
617        v = datastructure[widget_id]
618        err = 0
619        s = datastructure[widget_id+'_s'].strip()
620        g = datastructure[widget_id+'_g'].strip()
621        while 1:
622            if not s and g:
623                err = "no subject grad for subject %s " % s
624                break
625            i = 0
626            done = False
627            for sv,gv in v:
628                if sv == s:
629                    done = True
630                    if not g:
631                        v.pop(i)
632                        break
633                    v[i] = (s,g)
634                    break
635                i += 1
636            if done:
637                break
638            if s and g:
639                v.append((s,g))
640            break
641        if err:
642            datastructure.setError(widget_id, err)
643        else:
644            datamodel = datastructure.getDataModel()
645            datamodel[self.fields[0]] = v
646            datastructure[widget_id+'_s'] = s
647            datastructure[widget_id+'_g'] = g
648        return not err
649    ###)
650
651    def render(self, mode, datastructure, **kw): ###(
652        """Render in mode from datastructure."""
653        render_method = 'widget_waeup_result_render'
654        meth = getattr(self, render_method, None)
655        if meth is None:
656            raise RuntimeError("Unknown Render Method %s for widget type %s"
657                               % (render_method, self.getId()))
658        #import pdb;pdb.set_trace()
659        datamodel = datastructure.getDataModel()
660        widget_id = self.getWidgetId()
661        datastructure[widget_id+'_s'] = ''
662        datastructure[widget_id+'_g'] = ''
663        return meth(mode=mode,
664                    datastructure=datastructure,
665                    )
666    ###)
667
668
669InitializeClass(WAeUPResultsWidget)
670widgetRegistry.register(WAeUPResultsWidget)
671###)
672
673class ScratchCardPin: ###(
674    """the ScratchCardPin"""
675    def __init__(self,prefix,batch_no,number):
676        if not batch_no and not number:
677            s = prefix
678            if len(s) > 3:
679                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
680            else:
681                prefix,batch_no,number = s,'',''
682        self.p = prefix
683        self.b = batch_no
684        self.n = number
685
686    def __str__(self):
687        return "%s-%s-%s" % (self.p,self.b,self.n)
688
689    def __repr__(self):
690        return "%s%s%s" % (self.p,self.b,self.n)
691###)
692
693class ScratchcardPinWidget(CPSStringWidget): ###(
694    """ ScratchcardPin Widget"""
695    meta_type = "Scratchcard Pin Widget"
696    _properties = CPSWidget._properties + (
697        {'id': 'prefix', 'type': 'string', 'mode': 'w',
698         'label': 'Prefix'},
699         {'id': 'reference', 'type': 'string', 'mode': 'w',
700         'label': 'Reference Field'},
701        )
702    prefix = ''
703    reference = ''
704    def prepare(self, datastructure, **kw): ###(
705        """Prepare datastructure from datamodel."""
706        datamodel = datastructure.getDataModel()
707        v = datamodel[self.fields[0]]
708        widget_id = self.getWidgetId()
709        #import pdb;pdb.set_trace()
710        if v and type(v) is StringType:
711            try:
712                p,b,n = v.split('-')
713                v = ScratchCardPin(p,b,n)
714            except ValueError:
715                v = ScratchCardPin(v,'','')
716        if v:
717            p = '%s' % v.p
718            b = '%s' % v.b
719            n = '%s' % v.n
720        else:
721            p = self.prefix
722            if p.startswith('@'):
723                p = getattr(self,self.prefix[1:])()
724            b = n = ''
725            v = ScratchCardPin(p,b,n)
726        datastructure[widget_id] = v
727        datastructure[widget_id+'_p'] = p
728        datastructure[widget_id+'_b'] = b
729        datastructure[widget_id+'_n'] = n
730    ###)
731
732    def validate(self, datastructure, **kw): ###(
733        """Validate datastructure and update datamodel."""
734        s_logger = logging.getLogger('Pin.Validate')
735        widget_id = self.getWidgetId()
736        v = datastructure[widget_id]
737        #import pdb;pdb.set_trace()
738        err = 0
739        prefix= self.prefix
740        if prefix.startswith('@'):
741            prefix= getattr(self,self.prefix[1:])()
742        b = datastructure[widget_id+'_b'].strip()
743        n = datastructure[widget_id+'_n'].strip()
744        pins = self.portal_pins
745        pin = "%(prefix)s%(b)s%(n)s" % vars()
746        pin_str = "%(prefix)s-%(b)-s%(n)s" % vars()
747        do = 1
748        s_id = str(self.portal_membership.getAuthenticatedMember())
749        #import pdb;pdb.set_trace()
750        if self.isStaff():
751            do = 0
752            err ='You are not a Student. PIN neither checked nor used.'
753            s_logger.info('"%s","tried to use Scratchcard", "%s"' % (s_id,pin_str))
754        elif len(n) != 10:
755            do = 0
756            err = 'Invalid PIN-Number length %d' % len(n)
757            s_logger.info('"%s","Invalid PIN-Number length", "%d"' % (s_id,len(n)))
758        elif self.reference == "":
759            ref = s_id
760        else:
761            ref = datastructure[self.reference]
762            if datastructure.errors:
763                do = 0
764                datastructure.setError(widget_id, 'Errors in other data, PIN neither checked nor used.')
765                s_logger.info('"%s", "%s","entered wrong data together with pin", "%s"' % (s_id,ref,pin_str))
766        while do:
767            ok = pins.searchAndSetRecord(pin,ref,prefix)
768            if ok < -2 or ok > 2:
769                err = 'Unknown error, please report!'
770                s_logger.info('"%s","%s", "caused unknown error with pin", "%s"' % (s_id,ref,pin_str))
771                break
772            elif ok == -2:
773                err = 'Service already activated but with a different PIN.'
774                s_logger.info('"%s","%s", "repeatedly activated service but with different pin", "%s"' % (s_id,ref,pin_str))
775                break
776            elif ok == -1:
777                err = 'Invalid PIN'
778                s_logger.info('"%s","%s", "entered invalid pin", "%s"' % (s_id,ref,pin_str))
779                break
780            if ok == 0:
781                err = 'PIN already used.'
782                s_logger.info('"%s","%s", "entered used pin", "%s"' % (s_id,ref,pin_str))
783                break
784            if ok >= 1:
785                #import pdb;pdb.set_trace()
786                if self.isStudent():
787                    if self.reference == "jamb_reg_no":
788                        err = "You are already logged in."
789                        s_logger.info('"%s","%s", "checked admission though logged in", "%s"' % (s_id,ref,pin_str))
790                        break
791                    if ok == 1:
792                        s_logger.info('"%s","%s", "successfully used pin", "%s"' % (s_id,ref,pin_str))
793                    else:
794                        s_logger.info('"%s","%s", "repeatedly used pin", "%s"' % (s_id,ref,pin_str))
795                    break
796                else:
797                    student = getStudentByRegNo(self,ref)
798                    s_logger.info('"%s","%s","successfully used pin","%s"' % (s_id,ref,pin_str))
799                if student is None:
800                    err = "Student not found."
801                    s_logger.info('"%s","not found in admission list"' % (ref))
802                    break
803                s_id = student.getId()
804                if ok == 2:
805                    if self.reference == "jamb_reg_no":
806                        if hasattr(self.portal_directories.students,s_id):
807                            err = "Please login with your Student Id %s and 10-digit PIN." % s_id
808                            s_logger.info('"%s","%s", "repeatedly checked admission with pin", "%s"' % (s_id,ref,pin_str))
809                            break
810                        else:
811                            s_logger.info('"%s","%s","(non-member) repeatedly checked admission with pin", "%s"' % (s_id,ref,pin_str))
812                    else:
813                        err = "Unknown error" % s_id
814                        s_logger.info('"%s","%s", "repeatedly activated service with pin", "%s"' % (s_id,ref,pin_str))
815                        break
816                try:
817                    student.getContent().makeStudentMember(s_id,password=pin[4:])
818                    s_logger.info('"%s","%s", "has been created using pin", "%s"' % (s_id,ref,pin_str))
819                except:
820                    err = "Please login with your Student Id %s and 10-digit PIN." % s_id
821                    s_logger.info('"%s","%s", "could not be made a member with pin", "%s"' % (s_id,ref,pin_str))
822                    break
823            break
824        if err:
825            datastructure.setError(widget_id, err)
826        else:
827            datamodel = datastructure.getDataModel()
828            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
829            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
830            datastructure[widget_id+'_p'] = prefix
831            datastructure[widget_id+'_b'] = b
832            datastructure[widget_id+'_n'] = n
833            datastructure['s_id'] = s_id
834        return not err
835
836###)
837
838    def render(self, mode, datastructure, **kw): ###(
839        """Render in mode from datastructure."""
840        render_method = 'widget_scratch_card_pin_render'
841        meth = getattr(self, render_method, None)
842        if meth is None:
843            raise RuntimeError("Unknown Render Method %s for widget type %s"
844                               % (render_method, self.getId()))
845
846        # XXX AT: datastructure has to be set again here, in case we're in edit
847        # or create mode, because a default value has to be provided.
848        #import pdb;pdb.set_trace()
849        datamodel = datastructure.getDataModel()
850        v = datamodel[self.fields[0]]
851        if v and type(v) is StringType:
852            try:
853                p,b,n = v.split('-')
854                v = ScratchCardPin(p,b,n)
855            except ValueError:
856                v = ScratchCardPin(self.prefix,'1',v)
857                pass
858        if v:
859            prefix= '%s' % v.p
860            b = '%s' % v.b
861            n = '%s' % v.n
862        else:
863            prefix= self.prefix
864            if prefix.startswith('@'):
865                prefix= getattr(self,self.prefix[1:])()
866            b = n = ''
867            v = ScratchCardPin(prefix,b,n)
868        widget_id = self.getWidgetId()
869        datastructure[widget_id] = v
870        datastructure[widget_id+'_p'] = prefix
871        datastructure[widget_id+'_b'] = b
872        datastructure[widget_id+'_n'] = n
873        return meth(mode=mode,
874                    datastructure=datastructure,
875                    )
876    ###)
877
878
879InitializeClass(ScratchcardPinWidget)
880widgetRegistry.register(ScratchcardPinWidget)
881
882
883###)
884
885class WAeUPImageWidget(CPSImageWidget): ###(
886    """Photo widget."""
887    meta_type = 'WAeUP Image Widget'
888
889    def render(self, mode, datastructure, **kw):
890        render_method = 'widget_waeup_image_render'
891        meth = getattr(self, render_method, None)
892        if meth is None:
893            raise RuntimeError("Unknown Render Method %s for widget type %s"
894                               % (render_method, self.getId()))
895        img_info = self.getImageInfo(datastructure)
896        return meth(mode=mode, datastructure=datastructure, **img_info)
897
898###)
899
900
901
902InitializeClass(WAeUPImageWidget)
903
904widgetRegistry.register(WAeUPImageWidget)
905
906
907###########
908
Note: See TracBrowser for help on using the repository browser.