source: WAeUP_SRP/trunk/Widgets.py @ 556

Last change on this file since 556 was 551, checked in by joachim, 18 years ago

added CourseId? widget
made adding in Academics Section work again

  • Property svn:keywords set to Id
File size: 14.5 KB
Line 
1#-*- mode: python; mode: fold -*-
2
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
17
18from zLOG import LOG, DEBUG
19
20class CPSSelectWidgetForRecord(CPSSelectWidget): ###(
21    """Select widget. with record names"""
22    meta_type = 'Select Widget for Records'
23
24    field_types = ('CPS String Field',)
25    field_inits = ({'is_searchabletext': 1,},)
26
27    _properties = CPSSelectWidget._properties + (
28        {'id': 'record_id', 'type': 'string', 'mode': 'w',
29         'label': 'Record Id', 'is_required' : 1},
30        )
31
32    def render(self, mode, datastructure, **kw):
33        """Render in mode from datastructure."""
34        value = datastructure[self.getWidgetId()]
35        vocabulary = self._getVocabulary(datastructure)
36        portal = getToolByName(self, 'portal_url').getPortalObject()
37        cpsmcat = portal.translation_service
38        if mode == 'view':
39            if self.translated:
40                return escape(cpsmcat(vocabulary.getMsgid(value, value)).encode('ISO-8859-15', 'ignore'))
41            else:
42                return escape(vocabulary.get(value, value))
43        elif mode == 'edit':
44            html_widget_id = self.getHtmlWidgetId()
45            res = renderHtmlTag('select',
46                                name='%s.%s:records' % (self.record_id,html_widget_id),
47                                id=html_widget_id)
48            in_selection = 0
49            for k, v in vocabulary.items():
50                if self.translated:
51                    kw = {'value': k,
52                          'contents': cpsmcat(vocabulary.getMsgid(k, k)).encode('ISO-8859-15', 'ignore')
53                          }
54                else:
55                    kw = {'value': k, 'contents': v}
56                if value == k:
57                    kw['selected'] = 'selected'
58                    in_selection = 1
59                res += renderHtmlTag('option', **kw)
60            if value and not in_selection:
61                kw = {'value': value, 'contents': 'invalid: '+ str(value),
62                      'selected': 'selected'}
63                res += renderHtmlTag('option', **kw)
64            res += '</select>'
65            return res
66        raise RuntimeError('unknown mode %s' % mode)
67
68InitializeClass(CPSSelectWidgetForRecord)
69
70widgetRegistry.register(CPSSelectWidgetForRecord)
71
72###)
73
74class CPSStringWidgetForRecord(CPSStringWidget): ###(
75    """String widget."""
76    meta_type = 'String Widget For Record'
77
78    field_types = ('CPS String Field',)
79    field_inits = ({'is_searchabletext': 1,},)
80    _properties = CPSStringWidget._properties + (
81        {'id': 'record_id', 'type': 'string', 'mode': 'w',
82         'label': 'Record Id', 'is_required' : 1},
83        )
84
85    def render(self, mode, datastructure, **kw):
86        """Render in mode from datastructure."""
87        value = datastructure[self.getWidgetId()]
88        if mode == 'view':
89            return escape(value)
90        elif mode == 'edit':
91            # XXX TODO should use an other name than kw !
92            # XXX change this everywhere
93            html_widget_id = self.getHtmlWidgetId()
94            kw = {'type': 'text',
95                  'id'  : html_widget_id,
96                  'name': '%s.%s:records' % (self.record_id,html_widget_id),
97                  'value': escape(value),
98                  'size': self.display_width,
99                  }
100            if self.size_max:
101                kw['maxlength'] = self.size_max
102            return renderHtmlTag('input', **kw)
103        raise RuntimeError('unknown mode %s' % mode)
104
105InitializeClass(CPSStringWidgetForRecord)
106
107widgetRegistry.register(CPSStringWidgetForRecord)
108
109###)
110
111class CertificateCourseIdWidget(CPSStringWidget): ###(
112    """ CertificateCourseId Widget"""
113    meta_type = "CertificateCourseId Widget"
114
115    def validate(self, datastructure, **kw):
116        """Validate datastructure and update datamodel."""
117
118        valid = CPSStringWidget.validate(self, datastructure, **kw)
119        if not valid:
120            return 0
121        else:
122            widget_id = self.getWidgetId()
123            value = datastructure[widget_id].upper()
124            err = 0
125            c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
126            if hasattr(self.aq_parent,value):
127                err = 'Course %s already exists' % (value)
128            elif value not in c_ids:
129                err = 'Course %s does not exist' % (value)
130            if err:
131                datastructure.setError(widget_id, err)
132            else:
133                datamodel = datastructure.getDataModel()
134                datamodel[self.fields[0]] = value
135
136            return not err
137
138InitializeClass(CertificateCourseIdWidget)
139
140widgetRegistry.register(CertificateCourseIdWidget)
141###)
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 WAeUPIdWidget(CPSStringWidget): ###(
177    """ WAeUPId Widget"""
178    meta_type = "WAeUPId Widget"
179
180    def validate(self, datastructure, **kw):
181        """Validate datastructure and update datamodel."""
182
183        valid = CPSStringWidget.validate(self, datastructure, **kw)
184        id_pat_str = r"\S"
185        inv_id_pat = compile(r"^%s$" % id_pat_str)
186        if not valid:
187            return 0
188        else:
189            widget_id = self.getWidgetId()
190            value = datastructure[widget_id].upper()
191            err = 0
192            if len(value.split()) > 1:
193                err = 'Invalid Id (Id contains space(s)'
194            elif hasattr(self.aq_parent,value):
195                err = 'An object with the Id %s already exists in this context' % (value)
196            if err:
197                datastructure.setError(widget_id, err)
198            else:
199                datamodel = datastructure.getDataModel()
200                datamodel[self.fields[0]] = value
201
202            return not err
203
204InitializeClass(WAeUPIdWidget)
205
206widgetRegistry.register(WAeUPIdWidget)
207
208
209###)
210
211class StudentIdWidget(CPSStringWidget): ###(
212    """ StudentId Widget"""
213    meta_type = "StudentId Widget"
214    digits = 8
215    digits_str = "N"*digits
216    letters = 2
217    letters_str = "L"*letters
218
219    def validate(self, datastructure, **kw):
220        """Validate datastructure and update datamodel."""
221
222        valid = CPSStringWidget.validate(self, datastructure, **kw)
223        if not valid:
224            return 0
225        else:
226            widget_id = self.getWidgetId()
227            value = datastructure[widget_id]
228            err = 0
229            if not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
230                err = 'Invalid Registration Number in the format: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
231            if err:
232                datastructure.setError(widget_id, err)
233            else:
234                datamodel = datastructure.getDataModel()
235                datamodel[self.fields[0]] = value
236
237            return not err
238
239InitializeClass(StudentIdWidget)
240widgetRegistry.register(StudentIdWidget)
241
242###)
243
244##def getStudentByRegNo(self,reg_no):
245##    search = self.portal_catalog({'meta_type': 'StudentApplication',
246##                                  'jamb_reg_no': reg_no,
247##                                  })
248##    if len(search) < 1:
249##        return None
250##    return search[0].getObject().
251                   
252class JambRegNoWidget(CPSStringWidget): ###(
253    """ JambRegNo Widget"""
254    meta_type = "JambRegNo Widget"
255    digits = 8
256    digits_str = "N"*digits
257    letters = 2
258    letters_str = "L"*letters
259
260    def validate(self, datastructure, **kw):
261        """Validate datastructure and update datamodel."""
262
263        valid = CPSStringWidget.validate(self, datastructure, **kw)
264        if not valid:
265            return 0
266        else:
267            widget_id = self.getWidgetId()
268            value = datastructure[widget_id]
269            err = 0
270            if not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
271                err = 'Invalid Registration Number in the format: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
272            else:
273                s = getStudentByRegNo(self,value)
274                if s is None:
275                    err = 'No JAMB data for %s' % (value)
276            if err:
277                datastructure.setError(widget_id, err)
278            else:
279                datamodel = datastructure.getDataModel()
280                datamodel[self.fields[0]] = value
281
282            return not err
283
284InitializeClass(JambRegNoWidget)
285
286widgetRegistry.register(JambRegNoWidget)
287###)
288
289class ScratchCardPin: ###(
290    """the ScratchCardPin"""
291    def __init__(self,prefix,batch_no,number):
292        self.p = prefix
293        self.b = batch_no
294        self.n = number
295
296    def __str__(self):
297        return "%s-%s-%s" % (self.p,self.b,self.n)
298###)
299
300class ScratchcardPinWidget(CPSStringWidget): ###(
301    """ ScratchcardPin Widget"""
302    meta_type = "Scratchcard Pin Widget"
303    _properties = CPSWidget._properties + (
304        {'id': 'prefix', 'type': 'string', 'mode': 'w',
305         'label': 'Prefix'},
306         {'id': 'reference', 'type': 'string', 'mode': 'w',
307         'label': 'Reference Field'},
308
309        )
310    prefix = ''
311    reference = ''
312   
313    def prepare(self, datastructure, **kw): ###(
314        """Prepare datastructure from datamodel."""
315        datamodel = datastructure.getDataModel()
316        v = datamodel[self.fields[0]]
317        widget_id = self.getWidgetId()
318        if v and type(v) is StringType:
319            p,b,n = v.split('-')
320            v = ScratchCardPin(v,b,n)
321        if v:
322            b = '%s' % v.b
323            n = '%s' % v.n
324        else:
325            b = n = ''
326        datastructure[widget_id] = v
327        datastructure[widget_id+'_b'] = b
328        datastructure[widget_id+'_n'] = n
329       
330###)
331
332    def validate(self, datastructure, **kw):
333        """Validate datastructure and update datamodel."""
334        widget_id = self.getWidgetId()
335        v = datastructure[widget_id]
336        err = 0
337        p = self.prefix
338        b = datastructure[widget_id+'_b'].strip()
339        n = datastructure[widget_id+'_n'].strip()
340        pins = self.portal_pins
341        pin = "%(p)s%(b)s%(n)s" % vars()
342        ref = datastructure[self.reference]
343        #import pdb;pdb.set_trace()
344        ok = pins.searchAndSetRecord(pin,ref)
345        while 1:
346            if ok == -1:
347                err = 'invalid Pin'
348                break
349            if ok == 0:
350                err = 'Pin already used'
351                break
352            if ok >= 1:
353                student = getStudentByRegNo(self,ref)
354                if student is None:
355                    err = "Student not Found in validate SC"
356                    break
357                s_id = student.getId()
358                if ok == 2:
359                    break
360                student.getContent().makeStudentMember(s_id,password=pin[4:])
361            break
362        if err:
363            datastructure.setError(widget_id, err)
364        else:
365            datamodel = datastructure.getDataModel()
366            datamodel[self.fields[0]] = ScratchCardPin(self.prefix,b,n)
367            datastructure[widget_id] = ScratchCardPin(self.prefix,b,n)
368            datastructure[widget_id+'_b'] = b
369            datastructure[widget_id+'_n'] = n
370            datastructure['s_id'] = s_id
371        #import pdb;pdb.set_trace()
372        return not err
373
374    def render(self, mode, datastructure, **kw): ###(
375        """Render in mode from datastructure."""
376        render_method = 'widget_scratch_card_pin_render'
377        meth = getattr(self, render_method, None)
378        if meth is None:
379            raise RuntimeError("Unknown Render Method %s for widget type %s"
380                               % (render_method, self.getId()))
381
382        # XXX AT: datastructure has to be set again here, in case we're in edit
383        # or create mode, because a default value has to be provided.
384        #import pdb;pdb.set_trace()
385        datamodel = datastructure.getDataModel()
386        v = datamodel[self.fields[0]]
387        if v and type(v) is StringType:
388            p,b,n = v.split('-')
389            v = ScratchCardPin(p,b,n)
390        if v:
391            b = '%s' % v.b
392            n = '%s' % v.n
393        else:
394            b = n = ''
395        if mode in ['edit', 'create']:
396            widget_id = self.getWidgetId()
397            datastructure[widget_id] = v
398            datastructure[widget_id+'_b'] = b
399            datastructure[widget_id+'_n'] = n
400        return meth(mode=mode,
401                    datastructure=datastructure,
402                    prefix=self.prefix,
403                    )
404    ###)
405
406
407InitializeClass(ScratchcardPinWidget)
408widgetRegistry.register(ScratchcardPinWidget)
409
410
411###)
412
413class WAeUPImageWidget(CPSImageWidget):
414    """Photo widget."""
415    meta_type = 'WAeUP Image Widget'
416
417    def render(self, mode, datastructure, **kw):
418        render_method = 'widget_waeup_image_render'
419        meth = getattr(self, render_method, None)
420        if meth is None:
421            raise RuntimeError("Unknown Render Method %s for widget type %s"
422                               % (render_method, self.getId()))
423        img_info = self.getImageInfo(datastructure)
424        return meth(mode=mode, datastructure=datastructure, **img_info)
425
426
427
428InitializeClass(WAeUPImageWidget)
429
430widgetRegistry.register(WAeUPImageWidget)
431
432
433###########
434
Note: See TracBrowser for help on using the repository browser.