[Mpuls-commits] r607 - in wasko/branches/1.0: . waskaweb/controllers waskaweb/lib

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Wed Sep 23 14:44:30 CEST 2009


Author: torsten
Date: 2009-09-23 14:44:29 +0200 (Wed, 23 Sep 2009)
New Revision: 607

Modified:
   wasko/branches/1.0/ChangeLog.txt
   wasko/branches/1.0/waskaweb/controllers/evaluate.py
   wasko/branches/1.0/waskaweb/lib/helpers.py
   wasko/branches/1.0/waskaweb/lib/validators.py
Log:
First basic form of evaluations


Modified: wasko/branches/1.0/ChangeLog.txt
===================================================================
--- wasko/branches/1.0/ChangeLog.txt	2009-09-22 12:24:43 UTC (rev 606)
+++ wasko/branches/1.0/ChangeLog.txt	2009-09-23 12:44:29 UTC (rev 607)
@@ -1,3 +1,13 @@
+2009-09-23	Torsten Irlaender	<torsten.irlaender at intevation.de> 
+
+	Perform evaluations in with default options (No integration with
+	search).
+
+	* waskaweb/controllers/evaluate.py,
+	  waskaweb/lib/helpers.py,
+	  waskaweb/lib/validators.py: Replaced old evaluate controller with
+	  new one. 
+
 2009-09-22	Torsten Irlaender	<torsten.irlaender at intevation.de> 
 
 	Read jason-based configuration-files. List evaluations based on

Modified: wasko/branches/1.0/waskaweb/controllers/evaluate.py
===================================================================
--- wasko/branches/1.0/waskaweb/controllers/evaluate.py	2009-09-22 12:24:43 UTC (rev 606)
+++ wasko/branches/1.0/waskaweb/controllers/evaluate.py	2009-09-23 12:44:29 UTC (rev 607)
@@ -1,438 +1,157 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright 2007, 2008 Intevation GmbH, Germany, <info at intevation.de>
-# 
-# This file is part of mpuls WASKA (CoMPUter-based case fiLeS - 
-# Web-Anwendungs-Server fuer Kompetenzagenturen).
-# 
-# mpuls WASKA is free software: you can redistribute it and/or modify it under
-# the terms of the GNU Affero General Public License as published by the
-# Free Software Foundation, either version 3 of the License, or (at your
-# option) any later version.
-# 
-# mpuls WASKA is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
-# License for more details.
-# 
-# You should have received a copy of the GNU Affero General Public
-# License along with mpuls WASKA. If not, see <http://www.gnu.org/licenses/>.
-# 
-# mpuls WASKA has been developed on behalf of the 
-# Projekttraeger im Deutschen Zentrum fuer Luft- und Raumfahrt e.V. (PT-DLR)
-# within the programme Kompetenzagenturen (Durchfuehrungsphase) funded by
-# the Bundesministerium fuer Familie, Senioren, Frauen und Jugend and 
-# European Social Fund resources.
-#
-# Authors:
-# Torsten Irländer <torsten.irlaender at intevation.de>
-# Sascha L. Teichmann <teichmann at intevation.de>
-#
+import os
 import logging
-import paste
 import formencode
-from sets import Set
-from waskaweb.lib.sql_helper import range_compress 
+import traceback
+import pylons
+
+from pylons import session, g, c
+from waskaweb.lib.validators import EvaluationFormValidator
 from waskaweb.lib.base import *
-from waskaweb.lib.evaluation import *
-from waskaweb.lib.evaluation_new import Evaluation as NewEvaluation, EvaluationExportXML
-from waskaweb.lib.adelexml import AdeleXML
-from waskaweb.lib.evaluation_new import *
-from waskaweb.lib.search import CaseSearch
-from waskaweb.lib.validators import SearchCaseForm 
-from waskaweb.controllers.case_overview import parseSearchOptions 
-from waskaweb.model.case import CaseBundle 
-from waskaweb.model.agency import AgencyBundle, AgencyOverview 
+from waskaweb.lib.db import db
+from waskaweb.lib.helpers import format_date 
+from libmpuls.evaluation.config import EvaluationConfig
+from libmpuls.evaluation.evaluation import EvaluationSet
+from libmpuls.evaluation.export import EvaluationExportXML, EvaluationExportCSV, EvaluationExportHTML
 
 log = logging.getLogger(__name__)
 
-import sys
-import traceback
+def get_configfile(id):
+    for enabled_eval in g.mpuls_config.get('evaluations', 'enabled'):
+        if enabled_eval.get('id') == str(id):
+            filename = enabled_eval.get('config')
+            path = os.path.join(
+                pylons.config.get('pylons.paths').get('static_files'), 
+                'xml',
+                filename)
+            return path
+    return None
 
-from waskaweb.lib.security import checkRole
-from paste.httpexceptions  import HTTPNotFound
+def get_search_options(soptions=None, id=None):
+    options = {}
+    options['id'] = id
+    if soptions:
+        options['start_date'] = soptions.get('start_date') or datetime.date(2009,9,1)
+        options['end_date'] = soptions.get('end_date') or datetime.date.today() 
 
-SEARCH_STR = "state:1;state:2;state:4;state:5;own:%s"
-
-class EvaluateController(BaseController):
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def index(self):
-        raise HTTPNotFound()
-
-    def search(self):
-        user = session['USER_AUTHORIZED']
-        search_str = SEARCH_STR % user.id
-        validator = SearchCaseForm()
-        c.form_result = {}
-        c.form_errors = {}
-        try:
-            form_result = validator.to_python(request.params)
-            # Update the searchoptions with params coming from the search
-            # dialog on the evaluation page 
-            old_session = session.get('CASE_OVERVIEW_SEARCHOPTIONS', {}) 
-            for key, value in form_result.iteritems():
-                if value:
-                   old_session[key] = value 
-            session['CASE_OVERVIEW_SEARCHOPTIONS'] = old_session
-            session.save()
-
-            search_str2 = ";".join(parseSearchOptions(form_result))
-            search_str  = ";".join([search_str2, search_str])
-            search = CaseSearch()
-            result = search.perform(search_str)
-            # fetch ids of the new search 
-            new_case_ids = []
-            for row in result:
-                new_case_ids.append(row['id'])
-
-            # fetch ids from the old casebundle 
-            old_case_bundle = session.get('casebundle_for_eval')
-            if not old_case_bundle:
-                old_case_bundle = self._getNewCaseBundle()
-            old_case_ids = old_case_bundle.listDatasetIds()
-
-            #print "old: %s new: %s" % (old_case_ids, new_case_ids)
-            # now only take those ids which intersects.
-            ids = Set(old_case_ids) & Set(new_case_ids)
-
-            ## build casebundle
-            case_bundle = CaseBundle([id for id in ids])
-            session['casebundle'] = case_bundle
-            session.save()
-        except formencode.Invalid, error:
-            form_result = error.value
-            form_errors = error.error_dict or {}
-
-        return self.evaluate(form_result.get('eval_id'))
-
-    def _getNewCaseBundle(self, search_str=None):
-            user = session['USER_AUTHORIZED']
-            if not search_str:
-                search_str = SEARCH_STR % user.id
-            search = CaseSearch()
-            result = search.perform(search_str)
-            # fetch ids if the cases
-            ids = []
-            for row in result:
-                ids.append(row['id'])
-            # build casebundle
-            case_bundle = CaseBundle(ids)
-            session['casebundle'] = case_bundle
-            session.save()
-            return case_bundle
-
-    def _getCompressedIds(self, reset=False):
-        # Load case bundle and build where to define cases for the evaluation
-        if reset:
-            case_bundle = self._getNewCaseBundle()
+        phase = [int(p) for p in soptions.get('phase')]
+        if len(phase) == 1 and -1 in phase:
+            options['start_date_field'] = g.mpuls_config.get('evaluations', 'default-start-date-field')
+            options['end_date_field'] = g.mpuls_config.get('evaluations', 'default-end-date-field')
         else:
-            case_bundle = session.get('casebundle')
-            if not case_bundle:
-                case_bundle = self._getNewCaseBundle()
-        ids = sorted(case_bundle.listDatasetIds())
-        rc = range_compress(ids)
-        return rc
+            options['start_date_field'] = g.mpuls_config.get('agency-fields-mapping', 'date_phase%s_start' % min(phase))
+            options['end_date_field'] = g.mpuls_config.get('agency-fields-mapping', 'date_phase%s_end' % max(phase))
 
-    def evaluateAdele(self):
-        params = {}
-        params['start_date'] = '2008-09-01'
-        params['end_date']   = '2008-12-31'
-        params['agencyid']   = 'inte0002'
-        evaluation = AdeleXML(params)
-        c.eval = evaluation.perform()
-        return render('casemanagement/evaluation/evaluation_adele.mako')
+        options['phase'] = max(phase)
+        options['sqlwhere'] = soptions.get('sqlwhere') or None 
+        options['sql'] =  soptions.get('sql') or None
+    else:
+        # set default evaluation options.
+        options['phase'] = 1
+        options['start_date'] = g.mpuls_config.get('search', 'default-start-date')
+        options['end_date'] = g.mpuls_config.get('search', 'default-end-date')
+        options['start_date_field'] = g.mpuls_config.get('evaluations', 'default-start-date-field')
+        options['end_date_field'] = g.mpuls_config.get('evaluations', 'default-end-date-field')
 
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def evaluate(self, id, reset=0):
-        reset = self._checkBool(reset)
-        if reset:
-            if c.isEvaluationServer:
-                form_defaults = {}
-                search_options = parseSearchOptions(form_defaults)
-                # sql query fails if no sort order is given.
-                search_options.append('sort_field:fkz')
-                search_options.append('sort_order:asc')
-                agency_ids = [a.fkz for a in AgencyOverview().search(";".join(search_options))]
-                agency_bundle = AgencyBundle(agency_ids)
-                session['agencybundle'] = agency_bundle
+    options['typelist'] = c.evalconfig.get_evaluations()
 
-            session['hide_search_option_on_eval'] = False 
-            session['CASE_OVERVIEW_SEARCHOPTIONS'] = {}
-            session.save()
-        page = None
-        try:
-            c.eval_id = id
-            if id == '0':
-                # Zeitaufwände Logbuch
-                e14 = Evaluation_14(self._getCompressedIds(reset))
-                c.eval_effort = e14.perform() 
-                c.eval_avg_effort = c.eval_effort 
-                c.count_total = e14.getTotal()
-                c.count_total_valid = e14.getTotalValid()
-                page = render('casemanagement/evaluation/evaluation_result_0.mako')
-            if id == '1':
-                # Verhältnis Beratungskunden
-                e1 = Evaluation_1(self._getCompressedIds(reset))
-                c.eval_1_total, c.eval_1_ber, c.eval_1_ber_percent, c.eval_1_cm, c.eval_1_cm_percent = e1.perform()
-                c.count_total = e1.getTotal()
-                c.count_total_valid = e1.getTotalValid()
-                # Zugang zur KA
-                e4 = Evaluation_4(self._getCompressedIds(reset))
-                c.eval_4 = e4.perform()
-                # Rechtskreis Zugang
-                e5 = Evaluation_5(self._getCompressedIds(reset))
-                c.eval_5 = e5.perform()
-                # Schulabschluss Zugang
-                e11 = Evaluation_11(self._getCompressedIds(reset))
-                c.eval_11 = e11.perform()
-                # Arbeitssituation
-                e12 = Evaluation_12(self._getCompressedIds(reset))
-                c.eval_12 = e12.perform()
-                page = render('casemanagement/evaluation/evaluation_result_1.mako')
-            elif id == '2':
-                # Altersverteilung 
-                e8 = Evaluation_8(self._getCompressedIds(reset)) 
-                c.eval_8 = e8.perform()
-                # Migration
-                e3 = Evaluation_3(self._getCompressedIds(reset))
-                c.eval_3 = e3.perform()
-                # Verteilung Förderangebote
-                e9 = Evaluation_9(self._getCompressedIds(reset))
-                c.eval_9 = e9.perform()
-                # Geschlecht
-                e2 = Evaluation_2(self._getCompressedIds(reset))
-                c.eval_2_t, c.eval_2_m, c.eval_2_w, c.eval_2_i, c.eval_2_u = e2.perform()
-                # Arbeitslose
-                e19 = Evaluation_19(self._getCompressedIds(reset))
-                c.eval_19 = e19.perform()
-                # Nicht-Erwerbspersonen
-                e20 = Evaluation_20(self._getCompressedIds(reset))
-                c.eval_20 = e20.perform()
-                # ESF-Stammblatt 
-                #e21 = Evaluation_21(self._getCompressedIds(reset))
-                #c.eval_21 = e21.perform()
-                page = render('casemanagement/evaluation/evaluation_result_2.mako')
-            elif id == '3':
-                # Verweildauer CM
-                e10 = Evaluation_10(self._getCompressedIds(reset))
-                c.eval_10 = e10.perform()
-                c.count_total = e10.getTotal()
-                c.count_total_valid = e10.getTotalValid()
-                e13 = Evaluation_13(self._getCompressedIds(reset))
-                c.eval_13 = e13.perform()
-                # Vermittlung
-                e6 = Evaluation_6(self._getCompressedIds(reset))
-                c.eval_6 = e6.perform()
-                c.count_total = e6.getTotal()
-                c.count_total_valid = e6.getTotalValid()
-                # Rechtskreis nach Vermittlung
-                e7 = Evaluation_7(self._getCompressedIds(reset))
-                c.eval_7 = e7.perform()
-                # Zeitaufwände Logbuch
-                e15 = Evaluation_15(self._getCompressedIds(reset))
-                c.eval_effort = e15.perform()
-                c.eval_avg_effort = c.eval_effort 
-                page = render('casemanagement/evaluation/evaluation_result_3.mako')
+    # convert dates to locale
+    options['start_date'] = format_date(options['start_date']) 
+    options['end_date']   = format_date(options['end_date']) 
 
-            if page:
-                form_result = session.get('CASE_OVERVIEW_SEARCHOPTIONS', {})
-                if form_result.has_key('eval_id'):
-                    del form_result['eval_id'] # do not fillout eval_id with htmlfill
-                return formencode.htmlfill.render(unicode(page, 'utf-8'),defaults=form_result)
-        except:
-            return render('/tests/trace.mako')
+    return options
 
-        raise HTTPNotFound()
+class EvaluateController(BaseController):
 
-    def _export(self, evaluation):
-        content = evaluation.export()
-        data = paste.fileapp.DataApp(
-            content,
-            content_type='text/comma-separated-values',
-            content_encoding='UTF-8',
-            cache_control='must-revalidate',
-            pragma='public')
-        return data(request.environ, self.start_response)
+    def index(self):
+        return self.evaluate()
 
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_1(self):
+    def evaluate(self, id=None):
+        conn, cur = None, None
         try:
-            e = Evaluation_1(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
+            try:
+                config_file = get_configfile(id)
+                conn = db.getConnection()
+                c.evalconfig   = EvaluationConfig(
+                                config_file,
+                                conn,
+                                None,
+                                None,
+                                None,
+                                None,
+                                None,
+                                None,
+                                None)
+            except:
+                print 'Error: Evaluation failed %s' % traceback.print_exc()
+                log.error(_('Error: Evaluation failed'))
+        finally:
+            db.recycleConnection(conn, cur)
 
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_2(self):
-        try:
-            e = Evaluation_2(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
+        c.evaloptions = get_search_options(session.get('evaluation.options'), id)
+        form = render('/evaluation/evaluate.mako')
+        return formencode.htmlfill.render(unicode(form, 'utf-8'), \
+                defaults=c.evaloptions, \
+                errors={}, \
+                auto_insert_errors=False)
 
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_3(self):
-        try:
-            e = Evaluation_3(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
+    def evaluateAction(self):
+            '''Return an HTML file containing the result of one or more evaluations.'''
+            params = formencode.variabledecode.variable_decode(request.params)
+            validator    = EvaluationFormValidator() 
+            form_result  = {}
+            form_errors  = {}
 
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_4(self):
-        try:
-            e = Evaluation_4(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
+            # Check values
+            conn, cur = None, None
+            conn = db.getConnection()
+            id = int(params['id'])
+            c.evalconfig   = EvaluationConfig(
+                            get_configfile(id),
+                            conn,
+                            None,
+                            None,
+                            None,
+                            None,
+                            None,
+                            None,
+                            None)
+            try:
+                form_result  = validator.to_python(params)
+            except formencode.Invalid, error:
+                form_result = error.value
+                form_errors = error.error_dict or {}
+                c.evaloptions = get_search_options(session.get('evaluation.options'), id)
+                form = render('/evaluation/evaluate.mako')
+                return formencode.htmlfill.render(unicode(form, 'utf-8'), \
+                        defaults=form_result, \
+                        errors=form_errors, \
+                        auto_insert_errors=False)
 
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_5(self):
-        try:
-            e = Evaluation_5(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_6(self):
-        try:
-            e = Evaluation_6(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_7(self):
-        try:
-            e = Evaluation_7(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_8(self):
-        try:
-            e = Evaluation_8(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_9(self):
-        try:
-            e = Evaluation_9(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_10(self):
-        try:
-            e = Evaluation_10(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_11(self):
-        try:
-            e = Evaluation_11(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_12(self):
-        try:
-            e = Evaluation_12(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_13(self):
-        try:
-            e = Evaluation_13(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_14(self):
-        try:
-            e = Evaluation_14(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_15(self):
-        try:
-            e = Evaluation_15(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_16(self):
-        try:
-            e = Evaluation_16(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_17(self):
-        try:
-            e = Evaluation_17(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_19(self):
-        try:
-            e = Evaluation_19(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_20(self):
-        try:
-            e = Evaluation_20(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-    @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
-    def exportEvaluation_21(self):
-        try:
-            e = Evaluation_21(self._getCompressedIds())
-            return self._export(e)
-        except:
-            traceback.print_exc(file=sys.stderr)
-            raise HTTPNotFound()
-
-# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
+            # Build evaluation
+            try:
+                try:
+                    evalconfig   = EvaluationConfig(
+                                    get_configfile(form_result['id']),
+                                    conn,
+                                    form_result['start_date'], 
+                                    form_result['end_date'],
+                                    form_result['start_date_field'], 
+                                    form_result['end_date_field'], 
+                                    None,
+                                    form_result['sql'], 
+                                    form_result['typelist'])
+                    evalset      = EvaluationSet(evalconfig, True)
+                    evalset.evaluate()
+                    c.result = evalset.export(EvaluationExportHTML(show_percent=form_result['show_percent']))
+                    session['evaluation.params'] = form_result
+                    session.save()
+                    form = render('/evaluation/result.mako')
+                    return formencode.htmlfill.render(unicode(form, 'utf-8'), \
+                        defaults=form_result, \
+                        errors=form_errors, \
+                        auto_insert_errors=False)
+                except:
+                    log.error(_('Error: Evaluation failed'))
+                    log.error(traceback.print_exc())
+            finally:
+                db.recycleConnection(conn, cur)

Modified: wasko/branches/1.0/waskaweb/lib/helpers.py
===================================================================
--- wasko/branches/1.0/waskaweb/lib/helpers.py	2009-09-22 12:24:43 UTC (rev 606)
+++ wasko/branches/1.0/waskaweb/lib/helpers.py	2009-09-23 12:44:29 UTC (rev 607)
@@ -126,6 +126,52 @@
         return ''
     return value
 
+def str2date():
+    pass
+
+def date2str(dt):
+    if dt is None: return ''
+    try:
+        #print "dt: %s fmt: %s" % (dt, locale.nl_langinfo(locale.D_FMT))
+        return dt.strftime(locale.nl_langinfo(locale.D_FMT))
+    except Exception, err:
+        log.error(err)
+        return dd_mm_YYYY(dt)
+
+def str2time():
+    pass
+
+def time2str(dt):
+    if dt is None: return ''
+    try:
+        return dt.strftime(locale.nl_langinfo(locale.T_FMT))
+    except:
+        return ''
+
+def str2datetime():
+    pass
+
+def datetime2str(dt):
+    if dt is None: return ''
+    try:
+        return dt.strftime(locale.nl_langinfo(locale.D_T_FMT))
+    except:
+        return dd_mm_yyyy_HH_MM(dt)
+
+# Format functions 
+def format_number(number):
+    retval = locale.format("%.2f",(number),1)
+    return retval
+
+def format_date(dt):
+    return date2str(dt)
+
+def format_time(dt):
+    return time2str(dt)
+
+def format_datetime(dt):
+    return datetime2str(dt)
+
 def dd_mm_YYYY(d, empty = ''):
     ''' datetime.strftime() dislikes years before 1900. '''
     if d is None: return empty
@@ -327,4 +373,6 @@
 def safe_unicode(s):
     return u''.join([c for c in s if ord(c) > 127 or c in PRINTABLE])
 
+# Unicode <-> Str converters. The whole code is fu*&%d  up with mixed str and unicode. So we need some helpers to convert.
+
 # vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

Modified: wasko/branches/1.0/waskaweb/lib/validators.py
===================================================================
--- wasko/branches/1.0/waskaweb/lib/validators.py	2009-09-22 12:24:43 UTC (rev 606)
+++ wasko/branches/1.0/waskaweb/lib/validators.py	2009-09-23 12:44:29 UTC (rev 607)
@@ -22,11 +22,14 @@
 # within the programme Kompetenzagenturen (Durchfuehrungsphase) funded by
 # the Bundesministerium fuer Familie, Senioren, Frauen und Jugend and 
 # European Social Fund resources.
-from pylons import session
+import locale
+from pylons import session, g
+from pylons.i18n import _
 from waskaweb.lib.db import db
 import re
 import formencode
 import datetime
+import time
 
 class ValidatorStateObject:
 
@@ -43,6 +46,19 @@
     allow_extra_fields = True
     filter_extra_fields = False 
 
+class MyDateConverter(formencode.validators.FancyValidator):
+
+    messages = {
+        'wrong_format': _('Date is invalid')}
+
+    def _to_python(self, value, state):
+        value.strip()
+        try:
+            d = time.strptime(value, locale.nl_langinfo(locale.D_FMT))
+            return datetime.date(d[0], d[1], d[2])
+        except:
+            raise formencode.Invalid(self.message("wrong_format", state), value, state)
+
 class MaxMinInt(formencode.validators.FancyValidator):
 
     """
@@ -406,6 +422,16 @@
 class SetPhaseForm(BaseFormValidator):
     pass
 
+class EvaluationFormValidator(BaseFormValidator):
+    id                  = formencode.validators.String(if_missing='0')
+    agencyid            = formencode.validators.String(if_missing=g.mpuls_config.get('common', 'agencyname'))
+    start_date          = MyDateConverter(if_missing='')
+    end_date            = MyDateConverter(if_missing='')
+    start_date_field    = formencode.validators.String(not_empty=True)
+    end_date_field      = formencode.validators.String(not_empty=True)
+    typelist            = formencode.ForEach(formencode.validators.String(), convert_to_list=True)
+    show_percent        = formencode.validators.Bool(if_missing=False)
+
 class ExtraTimeFormValidator1(BaseFormValidator):
     allow_extra_fields         = True
     filter_extra_fields        = True 



More information about the Mpuls-commits mailing list