[Mpuls-commits] r415 - in wasko/trunk: . waskaweb/controllers waskaweb/lib waskaweb/model waskaweb/templates/casemanagement

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Thu Mar 19 12:37:37 CET 2009


Author: teichmann
Date: 2009-03-19 12:37:32 +0100 (Thu, 19 Mar 2009)
New Revision: 415

Modified:
   wasko/trunk/ChangeLog.txt
   wasko/trunk/waskaweb/controllers/case.py
   wasko/trunk/waskaweb/controllers/caselifetime.py
   wasko/trunk/waskaweb/lib/helpers.py
   wasko/trunk/waskaweb/model/casedocument.py
   wasko/trunk/waskaweb/model/datapage.py
   wasko/trunk/waskaweb/templates/casemanagement/wiederaufnahme.mako
Log:
Checked data validity before creation of 'wiederaufnahme' and 'neuaufnahme' cases.


Modified: wasko/trunk/ChangeLog.txt
===================================================================
--- wasko/trunk/ChangeLog.txt	2009-03-19 10:02:10 UTC (rev 414)
+++ wasko/trunk/ChangeLog.txt	2009-03-19 11:37:32 UTC (rev 415)
@@ -1,5 +1,24 @@
 2009-03-19	Sascha L. Teichmann <teichmann at intevation.de>
 
+	* waskaweb/model/datapage.py: moved '-' -> '_' replacement to constructor.
+
+	* waskaweb/model/casedocument.py: New methods to do a dry check against
+	  the defaults and store already converted and checked data without
+	  one more check.
+	  toErrorDicts() is now a method of DataSaveException
+
+	* waskaweb/lib/helpers.py: removed toErrorDicts().
+
+	* waskaweb/controllers/caselifetime.py: replaced usage of toErrorDicts.
+
+	* waskaweb/controllers/case.py: Added check of data validity _before_
+	  creation of case.
+
+	* waskaweb/templates/casemanagement/wiederaufnahme.mako: Fixed 'if'
+	  in error handling code.
+
+2009-03-19	Sascha L. Teichmann <teichmann at intevation.de>
+
 	* waskaweb/templates/logbook/edit_body.mako,
 	  waskaweb/templates/casemanagement/neuaufnahme.mako,
 	  waskaweb/templates/casemanagement/wiederaufnahme.mako:

Modified: wasko/trunk/waskaweb/controllers/case.py
===================================================================
--- wasko/trunk/waskaweb/controllers/case.py	2009-03-19 10:02:10 UTC (rev 414)
+++ wasko/trunk/waskaweb/controllers/case.py	2009-03-19 11:37:32 UTC (rev 415)
@@ -174,18 +174,18 @@
 LOGBOOK_ENTRY_SAVE_FAILED_TEXT = u"Die Änderung des Eintrages im Tagebuch ist fehlgeschlagen."
 
 def load_case(id):
-        '''Return a case object'''
-        factory   = CaseFactory()
-        case = factory.loadById(id)
+    '''Return a case object'''
+    factory   = CaseFactory()
+    case = factory.loadById(id)
 
-        # New session code
-        session_case = case.getSessionCase()
-        session['case'] = session_case
+    # New session code
+    session_case = case.getSessionCase()
+    session['case'] = session_case
 
-        navigation = NavigationTree(g.formedTree, case)
-        session['navigation.tree'] = navigation
-        session.save()
-        return case
+    navigation = NavigationTree(g.formedTree, case)
+    session['navigation.tree'] = navigation
+    session.save()
+    return case
 
 def checkPrivacyStatement(context='select'):
     '''Decorator for the methods in the case controller'''
@@ -390,43 +390,55 @@
         try:
             form_result = validator.to_python(request.params)
 
-            del session['signed']
-            session.save()
+            form_result['cm_neuauf_genehm'] = '1'
+            form_result['cm2c']             = '1'
+            form_result['cm_dok_end_art']   = '2'
 
-            # 1. Create a new case
-            factory = CaseFactory()
-            case = factory.createNew(data=session_case.toFormData())
-            statement = case.getPrivacyStatement()
+            try:
+                simulation = g.formedTree.dryConvertAgainstDefaults(form_result)
 
-            # 2. Do we want to sign the statement?
-            if signed: statement.sign()
+                # 1. Create a new case
+                factory = CaseFactory()
+                case = factory.createNew(data=session_case.toFormData())
+                statement = case.getPrivacyStatement()
 
-            self.__init_case(case.id)
-            load_case(case.id)
+                # 2. Do we want to sign the statement?
+                if signed: statement.sign()
 
-            form_result['cm_neuauf_genehm'] = '1'
-            form_result['cm2c'] = '1'
-            form_result['cm_dok_end_art'] = '2'
-            try:
-                g.formedTree.setData(form_result)
-            except DataSaveException, err:
-                c.status_msg = h.status_message(
+                self.__init_case(case.id)
+                load_case(case.id)
+
+                g.formedTree.setDataNoChecks(simulation, case.id)
+
+                del session['signed']
+                session.save()
+
+            except DataSaveException, inst:
+                c.form_result, c.form_errors = form_result, inst.toErrorDicts()[1]
+                form = render('/casemanagement/neuaufnahme.mako')
+                return formencode.htmlfill.render(unicode(form, 'utf-8'), 
+                    defaults           = c.form_result,
+                    auto_insert_errors = False,
+                    errors             = c.form_errors)
+            except:
+                traceback.print_exc(file = sys.stderr)
+                c.status_msg  = h.status_message(
                     u"Eingabedaten fehlerhaft! Daten wurden nicht vollständig übernommen.")
-                c.failed_for = u'Fallakte nicht vollständig angelegt!' 
+                c.failed_for  = u'Fallakte nicht vollständig angelegt!' 
                 c.failed_text = u'Die Fallakte wurde angelegt, aber es konnten nicht alle Daten übernommen werden. Bitte überprüfen Sie die Angaben in der Eingangsdokumentation bezüglich der Neuaufnahme und tragen Sie ggf. fehlende Daten nach. Klicken Sie auf "OK", um den neuen Fall zu öffnen.' 
-                c.url_ok = '/case/select/%s' % case.id 
+                c.url_ok      = '/case/select/%s' % case.id 
                 return render('/casemanagement/dialogs/failed_create_case.mako')
 
             return self.select(str(case.id))
+
         except formencode.Invalid, error:
             c.form_result = error.value
             c.form_errors = error.error_dict or {}
             form = render('/casemanagement/neuaufnahme.mako')
-            print c.form_errors
-            return formencode.htmlfill.render(unicode(form, 'utf-8'), \
-                        defaults=c.form_result, \
-                        auto_insert_errors=False, \
-                        errors=c.form_errors)
+            return formencode.htmlfill.render(unicode(form, 'utf-8'),
+                defaults           = c.form_result, 
+                auto_insert_errors = False, 
+                errors             = c.form_errors)
 
     @checkRole('cm_ka')
     def wiederaufnahmeAction(self):
@@ -441,45 +453,56 @@
         try:
             form_result = validator.to_python(request.params)
 
-            del session['signed']
-            session.save()
+            form_result['cm_wiederauf_genehm_1'] = '1'
+            form_result['cm2c']                  = '1'
+            form_result['cm_dok_end_art']        = '1'
+            try:
+                simulation = g.formedTree.dryConvertAgainstDefaults(form_result)
 
-            # 1. Create a new case
-            factory = CaseFactory()
-            case = factory.createNew(data=session_case.toFormData())
-            statement = case.getPrivacyStatement()
+                # 1. Create a new case
+                factory   = CaseFactory()
+                case      = factory.createNew(data=session_case.toFormData())
+                statement = case.getPrivacyStatement()
 
-            # 2. Do we want to sign the statement?
-            if signed: statement.sign()
+                # 2. Do we want to sign the statement?
+                if signed: statement.sign()
 
-            self.__init_case(case.id)
-            load_case(case.id)
+                self.__init_case(case.id)
+                load_case(case.id)
 
-            form_result['cm_wiederauf_genehm_1'] = '1'
-            form_result['cm2c'] = '1'
-            form_result['cm_dok_end_art'] = '1'
-            try:
-                g.formedTree.setData(form_result)
-            except DataSaveException, err:
-                c.status_msg = h.status_message(
+                g.formedTree.setDataNoChecks(simulation, case.id)
+
+                del session['signed']
+                session.save()
+
+            except DataSaveException, inst:
+                c.form_result, c.form_errors = form_result, inst.toErrorDicts()[1]
+                form = render('/casemanagement/wiederaufnahme.mako')
+                return formencode.htmlfill.render(unicode(form, 'utf-8'), 
+                    defaults           = c.form_result,
+                    auto_insert_errors = False,
+                    errors             = c.form_errors)
+            except:
+                traceback.print_exc(file = sys.stderr)
+                c.status_msg  = h.status_message(
                     "Eingabedaten fehlerhaft! Daten wurden nicht vollständig gespeichert.")
-                c.status_msg = h.status_message(
+                c.status_msg  = h.status_message(
                     u"Eingabedaten fehlerhaft! Daten wurden nicht vollständig übernommen.")
-                c.failed_for = u'Fallakte nicht vollständig angelegt!' 
+                c.failed_for  = u'Fallakte nicht vollständig angelegt!' 
                 c.failed_text = u'Die Fallakte wurde angelegt, aber es konnten nicht alle Daten übernommen werden. Bitte überprüfen Sie die Angaben in der Eingangsdokumentation bezüglich der Wiederaufnahme und tragen Sie ggf. fehlende Daten nach. Klicken Sie auf "OK", um den neuen Fall zu öffnen.' 
-                c.url_ok = '/case/select/%s' % case.id 
+                c.url_ok      = '/case/select/%s' % case.id 
                 return render('/casemanagement/dialogs/failed_create_case.mako')
 
             return self.select(str(case.id))
+
         except formencode.Invalid, error:
             c.form_result = error.value
             c.form_errors = error.error_dict or {}
             form = render('/casemanagement/wiederaufnahme.mako')
-            print c.form_errors
-            return formencode.htmlfill.render(unicode(form, 'utf-8'), \
-                        defaults=c.form_result, \
-                        auto_insert_errors=False, \
-                        errors=c.form_errors)
+            return formencode.htmlfill.render(unicode(form, 'utf-8'), 
+                defaults           = c.form_result,
+                auto_insert_errors = False, 
+                errors             = c.form_errors)
 
     @checkRole(('admin_ka', 'cm_ka', 'pb_ka'))
     def showHelp(self, help_id):

Modified: wasko/trunk/waskaweb/controllers/caselifetime.py
===================================================================
--- wasko/trunk/waskaweb/controllers/caselifetime.py	2009-03-19 10:02:10 UTC (rev 414)
+++ wasko/trunk/waskaweb/controllers/caselifetime.py	2009-03-19 11:37:32 UTC (rev 415)
@@ -220,7 +220,7 @@
                 create_logbook(header='Verlängerung des Integrationsprozess', text='Für den Fall wurde eine Verlängerung des Integrationsprozess dokumentiert.')
                 return self.index()
             except DataSaveException, err:
-                form_result_1, form_errors = h.toErrorDicts(err.errors)
+                form_result_1, form_errors = err.toErrorDicts()
         except formencode.Invalid, error:
             form_result = error.value
             form_errors = error.error_dict or {}
@@ -366,7 +366,7 @@
                     else:
                         return self.reopen_notok(0)
             except DataSaveException, err:
-                form_result_1, form_errors = h.toErrorDicts(err.errors)
+                form_result_1, form_errors = err.toErrorDicts()
         except formencode.Invalid, error:
             print error
             form_result = error.value
@@ -402,11 +402,11 @@
                         c.casedata.setData(form_result, do_write = False)
                         return self.renew(0)
                     except DataSaveException, err:
-                        form_result_1, form_errors = h.toErrorDicts(err.errors)
+                        form_result_1, form_errors = err.toErrorDicts()
                 else:
                     create_logbook(header='Neuaufnahme', text='Für den Fall wurde eine nicht genehmigte Neuaufnahme des Integrationsprozess dokumentiert.')
             except DataSaveException, err:
-                form_result_1, form_errors = h.toErrorDicts(err.errors)
+                form_result_1, form_errors = err.toErrorDicts()
 
         except formencode.Invalid, error:
             print error

Modified: wasko/trunk/waskaweb/lib/helpers.py
===================================================================
--- wasko/trunk/waskaweb/lib/helpers.py	2009-03-19 10:02:10 UTC (rev 414)
+++ wasko/trunk/waskaweb/lib/helpers.py	2009-03-19 11:37:32 UTC (rev 415)
@@ -123,20 +123,6 @@
     value = value.replace('\r', '<br>')
     return value
 
-def toErrorDicts(error_list):
-    values, errors = {}, {}
-
-    for key, value, error in error_list:
-        values[key] = value
-        try:
-            old = errors[key]
-            errors[key] = u"%s, %s" % (old, error)
-        except KeyError:
-            errors[key] = error
-
-    return values, errors
-
-
 def dd_mm_YYYY(d, empty = ''):
     ''' datetime.strftime() dislikes years before 1900. '''
     if d is None: return empty

Modified: wasko/trunk/waskaweb/model/casedocument.py
===================================================================
--- wasko/trunk/waskaweb/model/casedocument.py	2009-03-19 10:02:10 UTC (rev 414)
+++ wasko/trunk/waskaweb/model/casedocument.py	2009-03-19 11:37:32 UTC (rev 415)
@@ -78,7 +78,21 @@
         Exception.__init__(self, desc)
         self.errors = errors
 
+    def toErrorDicts(self):
 
+        values, errors = {}, {}
+
+        for key, value, error in self.errors:
+            values[key] = value
+            try:
+                old = errors[key]
+                errors[key] = u"%s, %s" % (old, error)
+            except KeyError:
+                errors[key] = error
+
+        return values, errors
+
+
 class CaseDocument(Document):
 
     def __init__(self, root=None):
@@ -310,6 +324,102 @@
             okay = False
         return okay
 
+    def dryConvertAgainstDefaults(self, params):
+
+        not_converted = []
+
+        converted, delete_vars = {}, []
+
+        for k, v in params.iteritems():
+            if v == "": # no value -> delete it
+                if self.name2default.get(k) != None: # NULL already?
+                    delete_vars.append(k)
+            else:
+                widget = self.widgets[k]
+                try:
+                    nv = checkAndConvert(widget, v)
+                    if nv != self.name2default.get(k): # only if it's a change
+                        converted[k] = nv
+                except SematicError, inst:
+                    not_converted.append((key, v, inst.value))
+
+        if not_converted:
+            raise DataSaveException(
+                "Konnte Daten nicht konvertieren", not_converted)
+
+        # second step: simulate to apply the data
+        simulation = dict([(n, None) for n in delete_vars])
+
+        def getValue(n):
+            try:
+                return simulation[n]
+            except KeyError:
+                return self.name2default.get(n)
+
+        for k, v in converted.iteritems():
+            try:
+                rules = self.var2rules[k]
+            except KeyError: # no rules
+                simulation[k] = v
+                continue
+
+            simulation_succeed = True
+            for rule in rules:
+                mark = rule.getMark()
+                if mark and mark.find("warning:") >= 0 or mark.find("notice:") >= 0:
+                    continue
+                expr = rule.getExpr()
+                if not expr: continue
+                vars = {}
+                isNull = False
+                for dep in expr.getDependencies():
+                    if dep != k: 
+                        ov = getValue(dep)
+                        if ov is None: isNull = True; break
+                        vars[dep] = ov
+
+                if not isNull:
+                    vars[k] = v
+                    try:
+                        okay = expr.evaluate(vars)
+                    except:
+                        okay = False
+                    if not okay:
+                        simulation_succeed = False
+                        not_converted.append((k, params[k], rule.getValue()))
+
+            if simulation_succeed:
+                simulation[k] = v
+
+        if not_converted:
+            raise DataSaveException(
+                "Datenkonsistenz nicht eingehalten", not_converted)
+
+        return simulation
+        
+
+    def setDataNoChecks(self, converted, ds_id = None):
+        pages = {}
+        for kv in converted.iteritems():
+            try:
+                pages.setdefault(self.widgets2pages[kv[0]], []).append(kv)
+            except KeyError:
+                print >> sys.stderr, "cannot find page for '%s'" % repr(kv[0])
+                continue
+
+        if ds_id is None:
+            case = session.get('case')
+            if not case: return None
+            ds_id = case.id
+
+        for page_name, params in pages.iteritems():
+            if not params: continue
+            ps = self.getPageStore(page_name, ds_id)
+            for k, v in params:
+                ps.setData(k, v)
+            ps.store()
+
+
     def setData(self, params, ds_id = None, do_write = True):
 
         orig_params = params

Modified: wasko/trunk/waskaweb/model/datapage.py
===================================================================
--- wasko/trunk/waskaweb/model/datapage.py	2009-03-19 10:02:10 UTC (rev 414)
+++ wasko/trunk/waskaweb/model/datapage.py	2009-03-19 11:37:32 UTC (rev 415)
@@ -47,7 +47,7 @@
         self.items     = None
         self.widgets   = None
         self.data      = None
-        self.relation  = relation
+        self.relation  = relation.replace('-', '_')
         self.id        = id
 
     def getWidget(self):
@@ -105,11 +105,9 @@
 
         fields['id'] = int(self.id)
 
-        rel = self.relation.replace('-', '_')
+        stmnt = "UPDATE %s SET %s WHERE id = %%(id)s" % (
+            self.relation, ", ".join(keys))
 
-        stmnt = "UPDATE %s SET %s WHERE id = %%(id)s;" % (
-            rel, ", ".join(keys))
-
         try:
             con, cur = None, None
             try:
@@ -140,9 +138,9 @@
             fields = ", ".join(self.items)
         except:
             pass
-        rel = self.relation.replace('-', '_')
+
         stmnt = "SELECT %s FROM %s WHERE id = %%(id)s;" % (
-            fields, rel)
+            fields, self.relation)
 
         #print >> sys.stderr, "select: %s" % stmnt
         try:

Modified: wasko/trunk/waskaweb/templates/casemanagement/wiederaufnahme.mako
===================================================================
--- wasko/trunk/waskaweb/templates/casemanagement/wiederaufnahme.mako	2009-03-19 10:02:10 UTC (rev 414)
+++ wasko/trunk/waskaweb/templates/casemanagement/wiederaufnahme.mako	2009-03-19 11:37:32 UTC (rev 415)
@@ -53,7 +53,7 @@
 % endif
 </div>
 <div class="waska_form_element  w100">
-% if c.form_errors.has_key('cm_wiederauf_genehm_datum_1'):
+% if c.form_errors.has_key('cm2c_t'):
   <label for="cm2c_t" class="error_font">
   <a name="f_cm2c_t">Anmerkungen zur Wiederaufnahme</a>
   </label>



More information about the Mpuls-commits mailing list