[Mpuls-commits] r233 - in waska/trunk: . waskaweb/controllers waskaweb/lib waskaweb/templates waskaweb/templates/casemanagement/evaluation

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Wed Feb 4 16:58:37 CET 2009


Author: torsten
Date: 2009-02-04 16:58:35 +0100 (Wed, 04 Feb 2009)
New Revision: 233

Added:
   waska/trunk/waskaweb/lib/adelexml.py
   waska/trunk/waskaweb/lib/evaluation_new.py
   waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_adele.mako
Modified:
   waska/trunk/ChangeLog.txt
   waska/trunk/waskaweb/controllers/evaluate.py
   waska/trunk/waskaweb/controllers/waska.py
   waska/trunk/waskaweb/lib/helpers.py
   waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_navigation.mako
   waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_result_2.mako
   waska/trunk/waskaweb/templates/main.mako
Log:
Added new evaluation for adele stammblatt


Modified: waska/trunk/ChangeLog.txt
===================================================================
--- waska/trunk/ChangeLog.txt	2009-01-09 11:54:32 UTC (rev 232)
+++ waska/trunk/ChangeLog.txt	2009-02-04 15:58:35 UTC (rev 233)
@@ -1,3 +1,19 @@
+2009-02-04	Torsten Irlaender  <torsten.irlaender at intevation.de>
+
+	Added new evalution adele stammblatt. 
+
+	* waskaweb/controllers/evaluate.py,
+	  waskaweb/lib/adelexml.py,
+	  waskaweb/lib/helpers.py,
+	  waskaweb/lib/evaluation_new.py,
+	  waskaweb/templates/casemanagement/evaluation/evaluation_adele.mako,
+	  waskaweb/templates/casemanagement/evaluation/evaluation_navigation.mako,
+	  waskaweb/templates/casemanagement/evaluation/evaluation_result_2.mako,
+	  waskaweb/templates/main.mako: The evaluations is hardcoded and is
+	  based on the new mpuls implementation. So do not extect a well
+	  integrated evulation.
+
+
 2009-01-05	Torsten Irlaender  <torsten.irlaender at intevation.de>
 
 	1.4.2 Release

Modified: waska/trunk/waskaweb/controllers/evaluate.py
===================================================================
--- waska/trunk/waskaweb/controllers/evaluate.py	2009-01-09 11:54:32 UTC (rev 232)
+++ waska/trunk/waskaweb/controllers/evaluate.py	2009-02-04 15:58:35 UTC (rev 233)
@@ -35,6 +35,9 @@
 from waskaweb.lib.sql_helper import range_compress 
 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 
@@ -131,6 +134,15 @@
         rc = range_compress(ids)
         return rc
 
+    def evaluateAdele(self):
+        params = {}
+        params['start_date'] = '2008-09-01'
+        params['end_date']   = '2008-12-01'
+        params['agencyid']   = 'inte0002'
+        evaluation = AdeleXML(params)
+        c.eval = evaluation.perform()
+        return render('casemanagement/evaluation/evaluation_adele.mako')
+
     @checkRole(('admin_ka', 'cm_ka', 'pt_dlr', 'pb_ka'))
     def evaluate(self, id, reset=0):
         reset = self._checkBool(reset)
@@ -198,8 +210,8 @@
                 e20 = Evaluation_20(self._getCompressedIds(reset))
                 c.eval_20 = e20.perform()
                 # ESF-Stammblatt 
-                # e21 = Evaluation_21(self._getCompressedIds(reset))
-                # c.eval_21 = e21.perform()
+                e21 = Evaluation_21(self._getCompressedIds(reset))
+                c.eval_21 = e21.perform()
                 page = render('casemanagement/evaluation/evaluation_result_2.mako')
             elif id == '3':
                 # Verweildauer CM

Modified: waska/trunk/waskaweb/controllers/waska.py
===================================================================
--- waska/trunk/waskaweb/controllers/waska.py	2009-01-09 11:54:32 UTC (rev 232)
+++ waska/trunk/waskaweb/controllers/waska.py	2009-02-04 15:58:35 UTC (rev 233)
@@ -104,6 +104,7 @@
 
         # LOAD NEWS
         c.news = NewsList(user)
+        #c.news = [] 
         return render('/start/start.mako')
 
     def markNewsAsRead(self, id, confirmed=0):

Added: waska/trunk/waskaweb/lib/adelexml.py
===================================================================
--- waska/trunk/waskaweb/lib/adelexml.py	2009-01-09 11:54:32 UTC (rev 232)
+++ waska/trunk/waskaweb/lib/adelexml.py	2009-02-04 15:58:35 UTC (rev 233)
@@ -0,0 +1,224 @@
+# -*- coding: utf-8 -*-
+#
+# (c) 2008 by Intevation GmbH
+# This is Free software under the GPLv3. 
+# See LICENSE comming with the source of 'mpuls'
+# for details.
+#
+# author: Torsten Irländer <torsten.irlaender at intevation.de>
+#
+import re, logging
+from datetime import datetime
+from waskaweb.lib.db import db
+from waskaweb.lib.evaluation_new import *
+log = logging.getLogger(__name__)
+
+#JSA.02.12345.08
+EXP_DOKNR  = re.compile('^JSA\.0[0-2]{1}\.([0-9]{5})\.[0-9]{2}$')
+EXP_TYPE   = re.compile('^([0-9]{1,2},?)+$')
+EXP_DATE   = re.compile('^\d{4}-\d{2}-\d{2}$')
+
+SQL_TABLE      = "master_tbl_view"
+SQL_GENDER_FIELD   = 'geschlecht'
+SQL_FKZ = """(fkz = '%s')"""
+SQL_CM = """(kompetenzfeststellung = '1' or (kompetenzfeststellung = '-1' and
+phase in (2,3,4,5)))"""
+
+
+SQL_TIME = """(datum_feststellung <= '%s'::date and coalesce(beendigung_5, now()) >= '%s'::date)"""
+
+SQL_EINTRITTE_GESAMT           = """('%s'::date <= datum_feststellung and '%s'::date >= datum_feststellung)"""
+SQL_AUSTRITTE_GESAMT           = """('%s'::date <= beendigung_5 and '%s'::date >= beendigung_5)"""
+SQL_AUSTRITTE_VORZEITIG        = """(art_beendigung = 2 and '%s'::date <= beendigung_5 and '%s'::date >= beendigung_5)"""
+SQL_AUSTRITTE_ABBRUCH          = """(art_beendigung = 1 and '%s'::date <= beendigung_5 and '%s'::date >= beendigung_5)"""
+SQL_CMKUNDEN                   = """TRUE"""
+SQL_ALTER_15_24                = """(date_part('year', age(geburtsdatum)) >= 14 and date_part('year', age(geburtsdatum)) <= 24)"""
+SQL_ALTER                      = """(date_part('year', age(geburtsdatum)) < 15 or date_part('year', age(geburtsdatum)) >= 25 and date_part('year', age(geburtsdatum)) <= 54 or date_part('year', age(geburtsdatum)) > 64)"""
+SQL_ALTER_55_64                = """(date_part('year', age(geburtsdatum)) >= 55 and date_part('year', age(geburtsdatum)) <= 64)"""
+SQL_ERWERBSTAETIG              = """(erwerbstaetigkeit_job = 1)"""
+SQL_SELBSTSTAENDIG             = """(bei_eintritt_ist_der_jugendliche = 6)"""
+SQL_ARBEITSLOSIGKEIT           = """(arbeitslosigkeit_1 = 1)"""
+SQL_ARBEITSLOSIGKEIT_LANG      = """(arbeitslosigkeit_1 = 1 and dauer_nach_letzter_beschaeftigung > 12)"""
+SQL_ARBEITSLOSIGKEIT_SGBII     = """(arbeitslosigkeit_1 = 1 and bezug_alg2 = 1)"""
+SQL_ARBEITSLOSIGKEIT_SGBIII    = """(arbeitslosigkeit_1 = 1 and bezug_alg1 = 1)"""
+SQL_ARBEITSLOSIGKEIT_SGBIII    = """(arbeitslosigkeit_1 = 1 and bezug_alg1 = 1)"""
+SQL_NICHTERWERBSTAETIG         = """(erwerbstaetigkeit_job = 0 and arbeitslosigkeit_1 = 0)"""
+SQL_NICHTERWERBSTAETIG_SCHULE  = """(erwerbstaetigkeit_job = 0 and arbeitslosigkeit_1 = 0 and bei_eintritt_ist_der_jugendliche = 1)"""
+SQL_MIGRATIONSHINTERGRUND      = """(muttersprache not in (18,-1) or staatsangehoerigkeit not in (29,-1) or vater not in (1, -1) or mutter not in (1,-1))"""
+SQL_BEHINDERUNG                = """(anerkannte_behinderung = 1)"""
+SQL_SONST_BEEINTRAECHTIGUNG    = """(physische_beeintraechtigungen = 1 or psychische_beeintraechtigungen = 1)"""
+SQL_OHNEABSCHLUSS              = """(schulabschluss_1 = 1)"""
+SQL_ISCED1_2                   = """(schulabschluss_1 in (3,4,5,9))"""
+SQL_ISCED3                     = """(schulabschluss_1 in (6))"""
+SQL_ISCED4                     = """(schulabschluss_1 in (8))"""
+SQL_AUSBLIDBUNG                = """(bei_eintritt_ist_der_jugendliche = 1)"""
+
+EVALUATION = {'1': SQL_EINTRITTE_GESAMT,
+              '2': SQL_AUSTRITTE_GESAMT,
+              '3': SQL_AUSTRITTE_VORZEITIG,
+              '4': SQL_AUSTRITTE_ABBRUCH, 
+              '7': SQL_ALTER_15_24, 
+              '8': SQL_ALTER, 
+              '9': SQL_ALTER_55_64, 
+              '10': SQL_ERWERBSTAETIG,
+              '11': SQL_SELBSTSTAENDIG,
+              '12': SQL_ARBEITSLOSIGKEIT,
+              '13': SQL_ARBEITSLOSIGKEIT_LANG,
+              '14': SQL_ARBEITSLOSIGKEIT_SGBII,
+              '15': SQL_ARBEITSLOSIGKEIT_SGBIII,
+              '16': SQL_NICHTERWERBSTAETIG,
+              '17': SQL_NICHTERWERBSTAETIG_SCHULE,
+              '19': SQL_MIGRATIONSHINTERGRUND,
+              '20': SQL_BEHINDERUNG,
+              '21': SQL_SONST_BEEINTRAECHTIGUNG,
+              '22': SQL_OHNEABSCHLUSS,
+              '23': SQL_ISCED1_2,
+              '24': SQL_ISCED3,
+              '25': SQL_ISCED4,
+              '27': SQL_AUSBLIDBUNG,
+              '28': SQL_CMKUNDEN
+              }
+
+DEFAULT_EVALUATIONS = ['1','2','3','4','7','8','9','10','12','13','14','15','16','17','19','20','21','22','23','24','25','27','28']
+
+EVAL_NAMES = {'1': 'Eintritte gesamt',
+              '2': 'Austritte gesamt',
+              '3': 'Vorzeitig ausgetreten',
+              '4': 'Abbrecher/innen', 
+              '7': SQL_ALTER_15_24, 
+              '8': SQL_ALTER, 
+              '9': SQL_ALTER_55_64, 
+              '10': SQL_ERWERBSTAETIG,
+              '11': SQL_SELBSTSTAENDIG,
+              '12': SQL_ARBEITSLOSIGKEIT,
+              '13': SQL_ARBEITSLOSIGKEIT_LANG,
+              '14': SQL_ARBEITSLOSIGKEIT_SGBII,
+              '15': SQL_ARBEITSLOSIGKEIT_SGBIII,
+              '16': SQL_NICHTERWERBSTAETIG,
+              '17': SQL_NICHTERWERBSTAETIG_SCHULE,
+              '19': SQL_MIGRATIONSHINTERGRUND,
+              '20': SQL_BEHINDERUNG,
+              '21': SQL_SONST_BEEINTRAECHTIGUNG,
+              '22': SQL_OHNEABSCHLUSS,
+              '23': SQL_ISCED1_2,
+              '24': SQL_ISCED3,
+              '25': SQL_ISCED4,
+              '27': SQL_AUSBLIDBUNG,
+              '28': SQL_CMKUNDEN
+              }
+
+EVAL_DESCRIPTIONS = {'1': 'Anzahl der Jugendlichen die im Bereichszeitraum neu in das CM aufgenommen wurden.',
+              '2': 'Gesamtanzahl der Jugendlichen, die im Bereichszeitraum das CM beendet haben.',
+              '3': 'Anzahl der Jugendlichen, die im Bereichszeitraum das CM mit der Art "vorzeitige Beendigung" beendet haben',
+              '4': SQL_AUSTRITTE_ABBRUCH, 
+              '7': SQL_ALTER_15_24, 
+              '8': SQL_ALTER, 
+              '9': SQL_ALTER_55_64, 
+              '10': SQL_ERWERBSTAETIG,
+              '11': SQL_SELBSTSTAENDIG,
+              '12': SQL_ARBEITSLOSIGKEIT,
+              '13': SQL_ARBEITSLOSIGKEIT_LANG,
+              '14': SQL_ARBEITSLOSIGKEIT_SGBII,
+              '15': SQL_ARBEITSLOSIGKEIT_SGBIII,
+              '16': SQL_NICHTERWERBSTAETIG,
+              '17': SQL_NICHTERWERBSTAETIG_SCHULE,
+              '19': SQL_MIGRATIONSHINTERGRUND,
+              '20': SQL_BEHINDERUNG,
+              '21': SQL_SONST_BEEINTRAECHTIGUNG,
+              '22': SQL_OHNEABSCHLUSS,
+              '23': SQL_ISCED1_2,
+              '24': SQL_ISCED3,
+              '25': SQL_ISCED4,
+              '27': SQL_AUSBLIDBUNG,
+              '28': SQL_CMKUNDEN
+              }
+
+class AdeleXML(Evaluation):
+    def __init__(self, params):
+        Evaluation.__init__(self, params)
+
+    def _setup(self):
+        self.evaluation_mapping  = EVALUATION
+        self.default_evaluations = DEFAULT_EVALUATIONS
+        self.sql_base_query      = SQL_BASE_QUERY
+        self.sql_table           = SQL_TABLE
+        self.sql_gender          = SQL_GENDER_FIELD
+
+        #custom
+        self.sql_time_frame      = SQL_TIME
+        self.sql_fkz             = SQL_FKZ
+        self.sql_cm              = SQL_CM
+
+    def _build_sql(self, where):
+        out = []
+        try:
+            out.append(self.sql_fkz % self.agency)
+            out.append(self.sql_cm)
+            out.append(self.sql_time_frame % (self.end_date, self.start_date))
+        except StandardError, err:
+            pass
+        try:
+            out.append(where % (self.start_date, self.end_date))
+        except StandardError, err:
+            out.append(where)
+            pass # Maybe the where clause does not have any time restrictions
+        where = " and ".join(out)
+        sql = Evaluation._build_sql(self, where)
+        return sql
+
+#class AdeleXML:
+#
+#    def perform(self, params):
+#        doknr      = params.get('doknr')
+#        start_date = params.get('start_date')
+#        end_date   = params.get('end_date')
+#        typelist   = params.get('typelist')
+#
+#        #TEST Remove for production
+#        doknr = 'JSA.02.12345.08'
+#        start_date = '2008-01-01'
+#        end_date = '2008-12-31'
+#
+#        #Do some checks on the incoming data
+#        if not doknr or not EXP_DOKNR.match(doknr): return "INVALID: 'doknr'"
+#        if not start_date or not EXP_DATE.match(start_date): return "INVALID: 'start_date'"
+#        if not end_date or not EXP_DATE.match(end_date): return "INVALID: 'end_date'"
+#        if not typelist:
+#            TYPELIST = DEFAULT_EVALUATIONS
+#        else:
+#            if not EXP_TYPE.match(typelist): return "INVALID: 'typelist'"
+#            TYPELIST = typelist.split(',')
+#
+#        #Make evaluation on the collected cases
+#        try:
+#            out = []
+#            out.append(XML_HEADER % (doknr, start_date, end_date)) 
+#            for id in TYPELIST:
+#                SQL_WHERE = EVALUATION.get(str(id), 'TRUE')
+#
+#                # If the timeinterval was not or not full provied set timeframe
+#                # to a very large interval 
+#                if not start_date or not end_date:
+#                    start_date = '1970-01-01'
+#                    end_date = '%s' % datetime.today().strftime('%Y-%m-%d') 
+#
+#                TIMEFRAME = SQL_TIME % (end_date, start_date)
+#
+#                # Try to set the dates in the where clause
+#                try:
+#                    SQL_WHERE = SQL_WHERE % (start_date, end_date)
+#                except:
+#                    pass # Ignore. Maybe the sql query does not have any
+#                         # datefields
+#
+#                sql = SQL_BASE_QUERY % (SQL_GROUPBY, SQL_TABLE, TIMEFRAME, SQL_WHERE , SQL_GROUPBY)
+#                eval = EvaluationQuery(id, sql)
+#                eval.perform()
+#                out.append(XML_EVALBLOCK % (eval.id, eval.men, eval.women, eval.men+eval.women))
+#            out.append(XML_FOOTER)
+#        except StandardError, err:
+#            log.error(err)
+#
+#        return "\n".join(out)
+
+# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

Added: waska/trunk/waskaweb/lib/evaluation_new.py
===================================================================
--- waska/trunk/waskaweb/lib/evaluation_new.py	2009-01-09 11:54:32 UTC (rev 232)
+++ waska/trunk/waskaweb/lib/evaluation_new.py	2009-02-04 15:58:35 UTC (rev 233)
@@ -0,0 +1,314 @@
+# -*- coding: utf-8 -*-
+#
+# (c) 2008 by Intevation GmbH
+# This is Free software under the GPLv3. 
+# See LICENSE comming with the source of 'mpuls'
+# for details.
+#
+# author: Torsten Irländer <torsten.irlaender at intevation.de>
+#
+
+import logging
+import pylons
+import os
+import tempfile
+import time
+import traceback
+
+from StringIO import StringIO
+from lxml import etree
+from waskaweb.lib.db import db
+#from waskaweb.lib.base import render
+#from mpuls.lib.config import MpulsConfig 
+#from mpuls.lib.helpers import build_map 
+from pylons.i18n import _
+from pylons import g,c
+#from pylons.templating import pylons_globals 
+from mako.template import Template
+from mako.lookup import TemplateLookup
+
+
+#log = logging.getLogger(__name__)
+XML_HEADER = """<PROJEKT_TEILNEHMER><PRJ_DOK_NR>%s</PRJ_DOK_NR><AUSW_VON>%s</AUSW_VON><AUSW_BIS>%s</AUSW_BIS>"""
+XML_BODY   = """<TEILNEHMER><PJTN_TTYP_ID>%s</PJTN_TTYP_ID><PJTN_MANN>%s</PJTN_MANN><PJTN_FRAU>%s</PJTN_FRAU><PJTN_GESAMT>%s</PJTN_GESAMT></TEILNEHMER>"""
+XML_FOOTER = """</PROJEKT_TEILNEHMER>"""
+
+SQL_TABLE      = "master_tbl_view"
+SQL_GENDER_FIELD   = 'geschlecht'
+SQL_BASE_QUERY = """SELECT %s, count(id) FROM %s WHERE %s GROUP BY %s"""
+
+SQL_TOTAL      = "TRUE"
+EVALUATION     = {'1': SQL_TOTAL}
+
+DEFAULT_EVALUATIONS = ['1']
+
+EVAL_NAMES = {'1': 'Total'}
+EVAL_DESCRIPTIONS = {'1': 'Evaluates how many cases are totally stored in the database.'}
+
+def render_with_mako(eval, data):
+        mako = ''
+        f = None
+
+        #path = os.path.join(pylons.config.get('pylons.paths').get('templates')[0], 'tmp')
+        #f = tempfile.NamedTemporaryFile(suffix='.mako', prefix='eval_', dir=path)
+        #f.write("\n".join(out))
+        #pylons.c.eval = eval
+        #mako = render(os.path.join('/tmp', os.path.split(f.name)[1]))
+        #f.close(); f = None
+
+        try:
+            path = os.path.join(pylons.config.get('pylons.paths').get('templates')[0], 'tmp', 'eval_xyz.mako')
+            #f = open(path, 'w')
+            mylookup = TemplateLookup(os.path.join(pylons.config.get('pylons.paths').get('templates')))
+            #glob = pylons_globals()
+            glob = {'g': g, 'c': c, 'h': h}
+            template = Template(u"\n".join(data), lookup=mylookup)
+            #f.write("\n".join(data))
+            #f.close(); f = None
+            pylons.c.eval = eval
+            #mako = render(os.path.join('/tmp', os.path.split(path)[1]))
+            return template.render(**glob)
+        except StandardError, err:
+            pass
+            print traceback.format_exc()
+            #log.error('Can not write file: %s' % err)
+        except:
+            print traceback.format_exc()
+            #log.error('Unknown error: ' )
+            pass
+        if f:
+            if f:
+                f.close()
+        return ''
+
+class EvaluationExport:
+
+    def __init__(self, style=None):
+        self.style = style
+
+    def export(self, eval):
+        return self.transform(self._toXML(eval))
+
+    def _toXML(self, eval):
+        data = eval.result_dic
+        out = []
+        out.append('<?xml version="1.0"?>')
+        out.append(XML_HEADER % (data['agency'], data['start_date'], data['end_date']))
+        for key in sorted([int(s) for s in data['evaluations'].keys()]):
+            eval = date['evaluations'][str(key)]
+            men   = eval['result'][0]
+            women = eval['result'][1]
+            sum   = eval['result'][2] 
+            out.append(XML_BODY % (key, men, women, sum))
+        out.append(XML_FOOTER)
+        return "\n".join(out)
+
+    def transform(self, data):
+        #log.debug('Transaforming: %s' % data)
+        if self.style:
+            try:
+                path = os.path.join(pylons.config.get('pylons.paths').get('static_files'), 'xsl', self.style)
+                xslt       = open(path, 'r')
+                xslt_doc   = etree.parse(xslt)
+                transform  = etree.XSLT(xslt_doc)
+                xml        = StringIO(data)
+                xml_doc    = etree.parse(xml)
+                result_doc = transform(xml_doc)
+                xslt.close()
+                # Find out how to get the payload even if the result doc does not have a rootnode.                # e-g CSV-Export
+                return etree.tostring(result_doc.getroot(), pretty_print=True)
+            except StandardError, err:
+                print traceback.format_exc()
+                #log.error('Error while transforming error: %s' % err)
+                result_doc = data
+        else:
+            result_doc = data
+            #log.debug('No style defined returning untransformed xml')
+        return result_doc 
+
+class EvaluationExportXML(EvaluationExport):
+
+    def __init__(self):
+        EvaluationExport.__init__(self, None)
+
+    def transform(self, data):
+        return data
+
+class EvaluationExportCSV(EvaluationExport):
+
+    def __init__(self):
+        EvaluationExport.__init__(self, 'eval_csv.xsl')
+
+    def export(self, eval):
+        xml = self._toXML(eval)
+        out = []
+        out.append(self.transform(xml))
+        #log.debug('generated csv: %s' % "\n".join(out))
+        try:
+            csv = render_with_mako(eval, out)
+            without_whitespace = [l for l in csv.split('\n') if l]
+            return "\n".join(without_whitespace[1:-1])
+        except StandardError, err:
+            #log.error('Error while rendering file: %s' % err)
+            raise
+
+class EvaluationExportHTML(EvaluationExport):
+
+    def __init__(self):
+        EvaluationExport.__init__(self, 'eval_mako.xsl')
+
+    def export(self, eval):
+        xml = self._toXML(eval)
+        return self.transform(xml)
+
+class EvaluationExportMAKO(EvaluationExport):
+
+    def __init__(self):
+        EvaluationExport.__init__(self, 'eval_mako.xsl')
+
+    def export(self, eval):
+        xml = self._toXML(eval)
+        out = []
+        out.append('<%inherit file="/main.mako"/>')
+        out.append('<%!  import waskaweb.lib.filters as F %>')
+        out.append(self.transform(xml))
+        print 'generated mako: %s' % "\n".join(out)
+        try:
+            return render_with_mako(eval, out)
+        except StandardError, err:
+            print traceback.format_exc()
+            #log.error('Error while rendering file: %s' % err)
+            raise
+
+class Evaluation:
+    '''Evaluation holds a "set " of different EvaluationQuerys for a particular
+    agency within a given timeframe. The result of the evaluation is stored in
+    a dictionary. The parameters are given in form of a dictionary.
+
+    INPUT
+    -----
+    The following dictionary defines a teh possible params:
+
+    agencyid   : Id of the agency. (e.g the FKZ)
+    start_date : The start date of the timeframe given in YYYY-MM-DD format
+    end_date   : The end date of the timeframe given in YYYY-MM-DD format
+    typelist   : A comma seperated list of evaluation ids
+
+    OUTPUT
+    ------
+    The following dictionary defines a result_set:
+
+    {
+      'agency': $agencyid,
+      'start_date': $start_date,
+      'end_date': $end_date
+      'evaluations': {
+        '$id': {
+           'name': $name,
+           'description': $description,
+           'result':[ men,women,men+women],
+        }
+        ... more evaluations
+      }
+     }
+    '''
+
+    def __init__(self, params):
+        self.id          = params.get('id', '0')
+        self.agency      = params.get('agencyid')
+        self.start_date  = params.get('start_date', '1970-01-01')
+        self.end_date    = params.get('end_date', )
+        self.mapping     = {} #build_map(MpulsConfig().get('database', 'mappingfile'))
+        evaluations_str  = str(params.get('typelist') or '')
+        self._setup()
+
+        if evaluations_str:
+            self.evaluations = evaluations_str.split(',')
+        else:
+            self.evaluations = self.default_evaluations
+
+        self.result_dic  = {}
+
+    def _setup(self):
+        self.evaluation_mapping  = EVALUATION
+        self.default_evaluations = DEFAULT_EVALUATIONS
+        self.sql_base_query      = SQL_BASE_QUERY
+        self.sql_table           = SQL_TABLE
+        self.sql_gender          = SQL_GENDER_FIELD
+
+    def _build_sql(self, where):
+        return self.sql_base_query % (self.sql_gender, self.sql_table, where, self.sql_gender)
+
+    def _set_header(self):
+        agency = self.mapping.get(self.agency, self.agency)
+        self.result_dic['agency']      = agency
+        self.result_dic['start_date']  = self.start_date
+        self.result_dic['end_date']    = self.end_date
+        self.result_dic['evaluations'] = {}
+
+    def _set_body(self, eval):
+        body_dic                                = {}
+        body_dic['name']                        = self.get_name(eval.id)
+        body_dic['description']                 = self.get_description(eval.id)
+        body_dic['result']                      = [eval.men, eval.women, eval.men+eval.women]
+        self.result_dic['evaluations'][eval.id] = body_dic 
+
+    def _set_footer(self):
+        pass
+
+    def perform(self):
+        self._set_header()
+        for eval_id in self.evaluations:
+            print 'performing evaluation for %s' % eval_id
+            try:
+                sql = self._build_sql(self.evaluation_mapping.get(eval_id))
+                evaluation = EvaluationQuery(eval_id, sql)
+                evaluation.perform()
+                self._set_body(evaluation)
+            except StandardError, err:
+                #log.error('Error on performing evaluation: %s' % err)
+                pass
+        self._set_footer()
+        return self.result_dic
+
+    def export(self, handler=None):
+        return handler.export(self)
+
+    def get_name(self, id=None):
+        return EVAL_NAMES.get(str(id), _('Eval No: %s' % id)) 
+
+    def get_description(self, id):
+        return EVAL_DESCRIPTIONS.get(str(id), _('No description available'))
+
+class EvaluationQuery:
+    def __init__(self, id=None, sql=None):
+        self.id     = id 
+        self.sql    = sql
+        self.result = {}
+        self.men    = 0
+        self.women  = 0
+
+    def perform(self): 
+        conn, cur = None, None
+        try:
+            conn = db.getConnection()
+            cur  = conn.cursor()
+            cur.execute(self.sql)
+            #log.debug(cur.query)
+            for r in cur.fetchall():
+                self.result[r[0]] = r[1]
+                if r[0] == 1: # men
+                    self.men = int(r[1])
+                if r[0] == 0: # women
+                    self.women = int(r[1])
+        except StandardError, err:
+            #log.error(err)
+            #log.error("Error with query %s" % self.sql)
+            pass
+        except:
+            #log.error("Error with query %s" % self.sql)
+            pass
+        if conn:
+            db.recycleConnection(conn, cur)
+
+# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

Modified: waska/trunk/waskaweb/lib/helpers.py
===================================================================
--- waska/trunk/waskaweb/lib/helpers.py	2009-01-09 11:54:32 UTC (rev 232)
+++ waska/trunk/waskaweb/lib/helpers.py	2009-02-04 15:58:35 UTC (rev 233)
@@ -32,12 +32,20 @@
 import re
 from pylons import c, cache, config, g, request, response, session
 from webhelpers import *
+from waskaweb.lib.adelexml import EVAL_NAMES, EVAL_DESCRIPTIONS
+from pylons.i18n import _
 
 import datetime
 
 VALID_DATE = re.compile(r'^([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{4})$')
 VALID_TIME = re.compile(r'^([0-9]{1,2}):([0-9]{2})')
 
+def get_adele_name(id=None):
+    return EVAL_NAMES.get(str(id), 'Auswertung Nr: %s' % id) 
+
+def get_adele_description(id):
+    return EVAL_DESCRIPTIONS.get(str(id), 'Keine Beschreibung vorhanden')
+
 def hasRole(rolelist):
     try:
         user = session['USER_AUTHORIZED']

Added: waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_adele.mako
===================================================================
--- waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_adele.mako	2009-01-09 11:54:32 UTC (rev 232)
+++ waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_adele.mako	2009-02-04 15:58:35 UTC (rev 233)
@@ -0,0 +1,37 @@
+## -*- coding: utf-8 -*-
+<%inherit file="/main.mako"/>
+<%!  import waskaweb.lib.filters as F %>
+<%def name="buildNavipath()">
+  ${parent.buildNavipath()}
+  <li><a href="/case">${_('cm_np_root')}</a></li>
+  <li><a href="/evaluate/evaluateAdele">Quartalsauswertung</a></li>
+</%def>
+<h1>Quartalsauswertung vom 01.09.2008 bis zum 31.12.2008</h1>
+##% for k, r in c.eval['evaluations'].iteritems():
+% for key in sorted([int(s) for s in c.eval['evaluations'].keys()]):
+<% r = c.eval['evaluations'][str(key)] %>
+<h3>${h.get_adele_name(key)}</h3>
+<p>${h.get_adele_description(key)}</p>
+<table class"evaluation">
+  <tr>
+    <th clase="table_header_h">Geschlecht</th>
+    <th clase="table_header_h num">Anzahl</th>
+    <th clase="table_header_h num">Prozent</th>
+  </tr>
+  <tr>
+    <td>männlich</td>
+    <td class="num">${r['result'][0]}</td>
+    <td class="num">${float(r['result'][0]) and float(r['result'][2])/float(r['result'][1])*100}%</td>
+  </tr>
+  <tr>
+    <td>weiblich</td>
+    <td class="num">${r['result'][1]}</td>
+    <td class="num">${float(r['result'][1]) and float(r['result'][2])/float(r['result'][1])*100}%</td>
+  </tr>
+  <tr>
+    <td>gesamt</td>
+    <td class="num">${r['result'][2]}</td>
+    <td class="num">100%</td>
+  <tr>
+</table>
+% endfor

Modified: waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_navigation.mako
===================================================================
--- waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_navigation.mako	2009-01-09 11:54:32 UTC (rev 232)
+++ waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_navigation.mako	2009-02-04 15:58:35 UTC (rev 233)
@@ -45,7 +45,7 @@
   <li><a href="${h.url_for(controller="/evaluate", action="evaluate", id=2)}#eval_6">${_('cm_eval_summary_header_6')}</a></li>
   <li><a href="${h.url_for(controller="/evaluate", action="evaluate", id=2)}#eval_19">${_('cm_eval_summary_header_19')}</a></li>
   <li><a href="${h.url_for(controller="/evaluate", action="evaluate", id=2)}#eval_20">${_('cm_eval_summary_header_20')}</a></li>
-##  <li><a href="${h.url_for(controller="/evaluate", action="evaluate", id=2)}#eval_21">${_('cm_eval_summary_header_21')}</a></li>
+  <li><a href="${h.url_for(controller="/evaluate", action="evaluate", id=2)}#eval_21">${_('cm_eval_summary_header_21')}</a></li>
 </ul>
 <h2>${_('eval_group_header_finished')}</h2>
 <ul>

Modified: waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_result_2.mako
===================================================================
--- waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_result_2.mako	2009-01-09 11:54:32 UTC (rev 232)
+++ waska/trunk/waskaweb/templates/casemanagement/evaluation/evaluation_result_2.mako	2009-02-04 15:58:35 UTC (rev 233)
@@ -198,8 +198,8 @@
 </table>
 <a href="#top">${_('cm_eval_table_to_overview')}</a> | <a href="/evaluate/exportEvaluation_20/auswertung_2_5.csv">${_('cm_eval_table_export_analysis')}</a>
 </div>
-##<div class="evaluation odd-row">
-##<h3><a name="eval_21">${_('cm_eval_summary_header_21')}</a></h3>
-##  <%include file="/casemanagement/evaluation/evaluation_esfstammblatt.mako"/>
-##<a href="#top">${_('cm_eval_table_to_overview')}</a> | <a href="/evaluate/exportEvaluation_21/auswertung_2_6.csv">${_('cm_eval_table_export_analysis')}</a>
-##</div>
+<div class="evaluation odd-row">
+<h3><a name="eval_21">${_('cm_eval_summary_header_21')}</a></h3>
+  <%include file="/casemanagement/evaluation/evaluation_esfstammblatt.mako"/>
+<a href="#top">${_('cm_eval_table_to_overview')}</a> | <a href="/evaluate/exportEvaluation_21/auswertung_2_6.csv">${_('cm_eval_table_export_analysis')}</a>
+</div>

Modified: waska/trunk/waskaweb/templates/main.mako
===================================================================
--- waska/trunk/waskaweb/templates/main.mako	2009-01-09 11:54:32 UTC (rev 232)
+++ waska/trunk/waskaweb/templates/main.mako	2009-02-04 15:58:35 UTC (rev 233)
@@ -1,78 +1,4 @@
 ## -*- coding: utf-8 -*-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<html>
-  <head>
-    <title>WASKA</title>
-    <meta name="generator" content="vim">
-    <meta name="author" content="Torsten Irlaender">
-    <meta name="date" content="2007-08-07">
-    <meta name="copyright" content="">
-    <meta name="keywords" content="">
-    <meta name="description" content="">
-    <meta name="ROBOTS" content="NOINDEX, NOFOLLOW">
-    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-    <meta http-equiv="content-style-type" content="text/css">
-    <meta http-equiv="expires" content="0">
-    <link rel="shortcut icon" type="image/x-icon" href="/images/kompetenz3.ico">
-    % if c.print_version:
-    <link href="${h.url_for('/styles/all.css')}" media="all" rel="stylesheet" type="text/css">
-    <link href="${h.url_for('/styles/print.css')}" media="screen" rel="stylesheet" type="text/css">
-    <link href="${h.url_for('/styles/print.css')}" media="print" rel="stylesheet" type="text/css">
-    % else:
-    <link href="${h.url_for('/styles/all.css')}" media="all" rel="stylesheet" type="text/css">
-    <link href="${h.url_for('/styles/screen.css')}" media="screen" rel="stylesheet" type="text/css">
-    <link href="${h.url_for('/styles/print.css')}" media="print" rel="stylesheet" type="text/css">
-    <!--[if gt IE 5]><link href="${h.url_for('/styles/ie6.css')}" media="screen" rel="stylesheet" type="text/css"><![endif]-->
-    % endif
-    <script src="/js/check.js" type="text/javascript"></script>
-  </head>
-  <body onload="clearModification();">
-  <span class="skiplink"><a href="#startmenu" title="Direkt zum Hauptmen&#252; springen" tabindex="1">
-  Zum Hauptmen&#252; springen</a></span>
-  <span class="skiplink"><a href="#navigation" title="Direkt zum Bereichsmen&#252; springen" tabindex="1">Zum Bereichsmen&#252; springen</a></span>
-  <span class="skiplink"><a href="#content" title="Direkt zum Inhalt springen" tabindex="2">Zum Inhalt springen</a></span>
-    <div id="header">
-      <div class="left" id="logo">
-        <a href="${h.url_for(controller='/waska', action='start')}" onclick="return checkModification();">
-          <img src="${h.url_for('/images/logo_ka_75.png')}" alt="Logo Kompetenzagentur" border="0">
-        </a>
-      </div>
-      <div id="rightheader">
-        ${self.buildStartMenu()}
-        ${self.buildStatusBar()}
-        <div id="navipath">
-          <ul>
-            ${self.buildNavipath()}
-          </ul>
-        </div>
-      </div>
-    </div>
-    <div id="main">
-      <div class="left">
-        <div class="navigation" id="navigation">
-          % if h.hasRole(['cm_ka']):
-            ${self.buildPrivacyfield()}
-          % endif
-          ${next.buildNavigation()}
-        </div>
-      </div>
-      <div id="content" class="right">
-        <div id="status_str_nofloat">
-          % if c.status_msg:
-            <span class="redcolor">${c.status_msg}<span>
-          % else:
-            <strong>Hinweis:</strong> Nach 30 Minuten ohne Aktivität/ohne Speichern wird die Sitzung
-      automatisch beendet, ggf. gehen Daten verloren!
-          % endif
-        </div>
-        ${self.buildContentHeader()}
-        ${self.body()}
-      </div>
-    </div>
-    ${self.buildFooter()}
-  </body>
-</html>
-
 <%def name="buildStatusBar()">
   <div id="statusbar">
     ${_('statusbar_logininfo')}:
@@ -144,6 +70,7 @@
           <li><a href="${h.url_for(controller='/case', action='new')}"> ${_('menu_cm_link_new')}</a> </li>
           <li><a href="${h.url_for(controller='/case', action='importCase')}"> ${_('menu_cm_link_import')}</a> </li>
         % endif
+        <li><a href="${h.url_for(controller='/evaluate', action='evaluateAdele')}">Quartalsauswertung</a></li>
         <li><a href="${h.url_for(controller='/evaluate', action='evaluate', id=1, reset=1)}"> ${_('cm_actions_link_evaluate')}</a></li>
         %if session.get('hascaseerrors'):
         <li><a href="${h.url_for(controller='/case_overview', action='listBadCases')}">Inkonsistente Fallakten</a></li>
@@ -209,3 +136,78 @@
 
 <%def name="buildModusfield()">
 </%def>
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+  <head>
+    <title>WASKA</title>
+    <meta name="generator" content="vim">
+    <meta name="author" content="Torsten Irlaender">
+    <meta name="date" content="2007-08-07">
+    <meta name="copyright" content="">
+    <meta name="keywords" content="">
+    <meta name="description" content="">
+    <meta name="ROBOTS" content="NOINDEX, NOFOLLOW">
+    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+    <meta http-equiv="content-style-type" content="text/css">
+    <meta http-equiv="expires" content="0">
+    <link rel="shortcut icon" type="image/x-icon" href="/images/kompetenz3.ico">
+    % if c.print_version:
+    <link href="${h.url_for('/styles/all.css')}" media="all" rel="stylesheet" type="text/css">
+    <link href="${h.url_for('/styles/print.css')}" media="screen" rel="stylesheet" type="text/css">
+    <link href="${h.url_for('/styles/print.css')}" media="print" rel="stylesheet" type="text/css">
+    % else:
+    <link href="${h.url_for('/styles/all.css')}" media="all" rel="stylesheet" type="text/css">
+    <link href="${h.url_for('/styles/screen.css')}" media="screen" rel="stylesheet" type="text/css">
+    <link href="${h.url_for('/styles/print.css')}" media="print" rel="stylesheet" type="text/css">
+    <!--[if gt IE 5]><link href="${h.url_for('/styles/ie6.css')}" media="screen" rel="stylesheet" type="text/css"><![endif]-->
+    % endif
+    <script src="/js/check.js" type="text/javascript"></script>
+  </head>
+  <body onload="clearModification();">
+  <span class="skiplink"><a href="#startmenu" title="Direkt zum Hauptmen&#252; springen" tabindex="1">
+  Zum Hauptmen&#252; springen</a></span>
+  <span class="skiplink"><a href="#navigation" title="Direkt zum Bereichsmen&#252; springen" tabindex="1">Zum Bereichsmen&#252; springen</a></span>
+  <span class="skiplink"><a href="#content" title="Direkt zum Inhalt springen" tabindex="2">Zum Inhalt springen</a></span>
+    <div id="header">
+      <div class="left" id="logo">
+        <a href="${h.url_for(controller='/waska', action='start')}" onclick="return checkModification();">
+          <img src="${h.url_for('/images/logo_ka_75.png')}" alt="Logo Kompetenzagentur" border="0">
+        </a>
+      </div>
+      <div id="rightheader">
+        ${self.buildStartMenu()}
+        ${self.buildStatusBar()}
+        <div id="navipath">
+          <ul>
+            ${self.buildNavipath()}
+          </ul>
+        </div>
+      </div>
+    </div>
+    <div id="main">
+      <div class="left">
+        <div class="navigation" id="navigation">
+          % if h.hasRole(['cm_ka']):
+            ${self.buildPrivacyfield()}
+          % endif
+          ${next.buildNavigation()}
+        </div>
+      </div>
+      <div id="content" class="right">
+        <div id="status_str_nofloat">
+          % if c.status_msg:
+            <span class="redcolor">${c.status_msg}<span>
+          % else:
+            <strong>Hinweis:</strong> Nach 30 Minuten ohne Aktivität/ohne Speichern wird die Sitzung
+      automatisch beendet, ggf. gehen Daten verloren!
+          % endif
+        </div>
+        ${self.buildContentHeader()}
+        ${self.body()}
+      </div>
+    </div>
+    ${self.buildFooter()}
+  </body>
+</html>
+



More information about the Mpuls-commits mailing list