[Mpuls-commits] r827 - in wasko/branches/2.0: . waskaweb/model
scm-commit@wald.intevation.org
scm-commit at wald.intevation.org
Fri Jan 22 12:12:59 CET 2010
Author: bh
Date: 2010-01-22 12:12:57 +0100 (Fri, 22 Jan 2010)
New Revision: 827
Modified:
wasko/branches/2.0/ChangeLog
wasko/branches/2.0/waskaweb/model/case.py
Log:
* waskaweb/model/case.py: Fix formatting.
Modified: wasko/branches/2.0/ChangeLog
===================================================================
--- wasko/branches/2.0/ChangeLog 2010-01-22 11:05:58 UTC (rev 826)
+++ wasko/branches/2.0/ChangeLog 2010-01-22 11:12:57 UTC (rev 827)
@@ -1,3 +1,7 @@
+2010-01-22 Bernhard Herzog <bh at intevation.de>
+
+ * waskaweb/model/case.py: Fix formatting.
+
2010-01-22 Torsten Irländer <torsten.irlaender at intevation.de>
* waskaweb/lib/evaluation.py (Evaluation._build_eval_where_clause):
Modified: wasko/branches/2.0/waskaweb/model/case.py
===================================================================
--- wasko/branches/2.0/waskaweb/model/case.py 2010-01-22 11:05:58 UTC (rev 826)
+++ wasko/branches/2.0/waskaweb/model/case.py 2010-01-22 11:12:57 UTC (rev 827)
@@ -1,27 +1,27 @@
# -*- coding: utf-8 -*-
#
# Copyright 2007, 2008 Intevation GmbH, Germany, <info at intevation.de>
-#
-# This file is part of mpuls WASKA (CoMPUter-based case fiLeS -
+#
+# 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
+#
+# 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
+# the Bundesministerium fuer Familie, Senioren, Frauen und Jugend and
# European Social Fund resources.
# Authors:
# Torsten Irländer <torsten.irlaender at intevation.de>
@@ -31,47 +31,53 @@
import re
from datetime import date, datetime, timedelta
import traceback
-import psycopg2.extras
import codecs
import cStringIO as StringIO
import shutil
from locale import strcoll
from sets import Set
-from pylons.i18n import _, ungettext, N_
-from waskaweb.lib.db import db
-from waskaweb.lib.sql_helper import where_ids, range_compress
+
+import psycopg2.extras
+
+from pylons.i18n import _, ungettext, N_
+
+from formed.instance.backends.postgres import DBFactory as InstanceFactory
+from formed.instance.tree import SetDataException, RepeatInstanceContainerNode
+from formed.meta.data import RepeatNode
+
+from waskaweb.lib.base import session, g, h, config
+import waskaweb.lib.filters as F
+from waskaweb.lib.helpers import dd_mm_yyyy_HH_MM, dd_mm_YYYY
+from waskaweb.lib.db import db, PostgresDBInterface
+from waskaweb.lib.sql_helper import where_ids, range_compress
from waskaweb.lib.search import CaseSearch
#from waskaweb.lib.csv import exportAsCSV
#from waskaweb.lib.excel import exportAsXLS
#from waskaweb.lib.xmlexport import exportAsXML
-from waskaweb.lib.base import session, g, h, config
-import waskaweb.lib.filters as F
+
from waskaweb.model import UNKNOWN_DATE
from waskaweb.model.user import UserObject, UserGroupFactory
from waskaweb.model.agencysettings import Agency
-from waskaweb.model.repeatgroup import AidList, CREATE_RG_BILDEN_DS,CREATE_RG_LEBEN_DS, CREATE_RG_QUALI_DS, CREATE_RG_BERUF_DS
-from waskaweb.model.statement import PrivacyStatement, AidPlanStatement, DiscretionStatement
-from waskaweb.model.document import listDocuments
-from waskaweb.lib.db import PostgresDBInterface
-from formed.instance.backends.postgres import DBFactory as InstanceFactory
-from formed.instance.tree import SetDataException, RepeatInstanceContainerNode
-from formed.meta.data import RepeatNode
-from waskaweb.controllers.formularpage import convert2dic
-
+from waskaweb.model.repeatgroup import AidList, CREATE_RG_BILDEN_DS,\
+ CREATE_RG_LEBEN_DS, CREATE_RG_QUALI_DS, CREATE_RG_BERUF_DS
+from waskaweb.model.statement import PrivacyStatement, AidPlanStatement, \
+ DiscretionStatement
+from waskaweb.model.document import listDocuments
from waskaweb.model.phase_transition import phase_description, phase_end, \
- CM_START, CLEAR_START, CLEAR_ENDE
-
+ CM_START, CLEAR_START, CLEAR_ENDE
from waskaweb.model.phases_factory import RequiredFields
-from waskaweb.lib.helpers import dd_mm_yyyy_HH_MM, dd_mm_YYYY
+from waskaweb.controllers.formularpage import convert2dic
+
def get_field_identifier(id, name, it=None, idx=0):
- '''Will return the identifier of a field. If the field in in a rg the
- identifier of the first occourance will be returned on default.'''
+ """Will return the identifier of a field. If the field in in a rg the
+ identifier of the first occourance will be returned on default."""
# Map generic fieldnames to specific fieldnames
# get name of the field
nc = g.formedTree.findByName(name)
- if not nc: return None
+ if not nc:
+ return None
# is the field within a rg. if so get name
parent = nc.getParent()
@@ -82,12 +88,13 @@
break
parent = parent.getParent()
- if not rg:
+ if not rg:
return "%s:%d" % (name, id)
# get instance of the rg
rgc = it.getItem("%s:%d" % (rg.getName(), id))
- if not rgc: return None
+ if not rgc:
+ return None
rgs = rgc.getChildren()
if not rgs:
print >> sys.stderr, "No repeat group found: create new"
@@ -96,122 +103,166 @@
rg = rgs[idx]
return '%s:%s:%s' % (name, rg.getInternalIdentifier(), id)
+
def save_getone(params, k, v):
try:
return params.getone(k)
except KeyError:
return v
+
# SQL STATEMENTS
LOAD_CASESTATE_SQL = """
-SELECT
- s.id,
- s.status,
- s.zugriff,
- m.nbtr AS cm_beendet,
- m.cm_end_art AS cm_abbruch,
+SELECT
+ s.id,
+ s.status,
+ s.zugriff,
+ m.nbtr AS cm_beendet,
+ m.cm_end_art AS cm_abbruch,
getLastCaseAppointment(m.id) AS letzer_termin,
m.phase AS phase
-FROM ka_status_tbl_view s JOIN master_tbl_view m ON m.id = s.master_id
+FROM ka_status_tbl_view s JOIN master_tbl_view m ON m.id = s.master_id
WHERE s.master_id = %(id)s
"""
SET_CASESTATE_SQL = """
-UPDATE ka_status_tbl_view
- SET status = %(status)s
+UPDATE ka_status_tbl_view
+ SET status = %(status)s
WHERE id = %(id)s"""
SET_CASEPHASE_SQL = """
- UPDATE master_tbl_view
- SET phase = %(phase)s
+ UPDATE master_tbl_view
+ SET phase = %(phase)s
WHERE id IN (SELECT master_id FROM ka_status_tbl_view WHERE id = %(id)s)"""
#LOAD_CASE_DIGEST_SQL = """
#SELECT
-# name as name_1,
-# vorname as vorname_1,
-# fn as kundennummer,
+# name as name_1,
+# vorname as vorname_1,
+# fn as kundennummer,
# date_part('year', age(geburtsdatum::timestamp)) AS alter,
-# addresse_plz_1 as plz,
-# addresse_strasse_1 as strasse,
-# addresse_strassenr_1 as strassenr,
-# addresse_ort_1 as wohnort,
-# addresse1_vorwahl_1 as vorwahl,
+# addresse_plz_1 as plz,
+# addresse_strasse_1 as strasse,
+# addresse_strassenr_1 as strassenr,
+# addresse_ort_1 as wohnort,
+# addresse1_vorwahl_1 as vorwahl,
# addresse1_telefonnummer_1 as telefon_1,
-# addresse2_vorwahl_1 as vorwahl_2,
+# addresse2_vorwahl_1 as vorwahl_2,
# addresse2_telefonnummer_2 as telefon_2,
-# addresse_weiteretelefonnummern_1 as telefon_sonstige,
-# addresse_email_1 as email,
-# einwilligung as einverstaendniserklaerung,
-# mutter_n,
-# mutter_vn,
-# mutter_vorwahl1_1,
-# mutter_telefonnummer1_1,
-# mutter_vorwahl2_1,
-# mutter_telefonnummer2_1,
+# addresse_weiteretelefonnummern_1 as telefon_sonstige,
+# addresse_email_1 as email,
+# einwilligung as einverstaendniserklaerung,
+# mutter_n,
+# mutter_vn,
+# mutter_vorwahl1_1,
+# mutter_telefonnummer1_1,
+# mutter_vorwahl2_1,
+# mutter_telefonnummer2_1,
# mutter_email_1,
-# vater_n ,
-# vater_vn ,
-# vater_vorwahl1_1 ,
-# vater_telefonnummer1_1 ,
-# vater_vorwahl2_1 ,
-# vater_telefonnummer2_1 ,
-# vater_email_1
+# vater_n ,
+# vater_vn ,
+# vater_vorwahl1_1 ,
+# vater_telefonnummer1_1 ,
+# vater_vorwahl2_1 ,
+# vater_telefonnummer2_1 ,
+# vater_email_1
#FROM master_tbl_view WHERE id = %(id)s
#"""
LOAD_CASE_DIGEST_SQL = """
SELECT
- name as name_1,
- vorname as vorname_1,
- fn as kundennummer,
+ name as name_1,
+ vorname as vorname_1,
+ fn as kundennummer,
date_part('year', age(geburtsdatum::timestamp)) AS alter,
- einwilligung as einverstaendniserklaerung
+ einwilligung as einverstaendniserklaerung
FROM master_tbl_view WHERE id = %(id)s
"""
-LOAD_CASE_SQL = """SELECT name as name_1, vorname as vorname_1, bearbeiter_id, fn as kundennummer, erstgespraech, datum_cm_ende from master_tbl_view WHERE id = %(id)s"""
-DELETE_CASE_SQL = """select delete_master_ds(%(id)s)"""
+LOAD_CASE_SQL = """
+SELECT
+ name as name_1,
+ vorname as vorname_1,
+ bearbeiter_id, fn as kundennummer,
+ erstgespraech,
+ datum_cm_ende
+FROM master_tbl_view WHERE id = %(id)s
+"""
+DELETE_CASE_SQL = """select delete_master_ds(%(id)s)"""
CREATE_CASE_SQL = """SELECT create_master_tbl(%(uuid)s)"""
-UPDATE_CASE_ON_CREATE_SQL = """UPDATE master_tbl_view set name = %(name)s, vorname = %(vorname)s, mitarb_vv = %(gvorname)s, mitarb_vn = %(gname)s, einwilligung = %(einwilligung)s, addresse_strassenr_1 = %(strassenr)s, addresse_strasse_1 = %(strasse)s, addresse_plz_1 = %(plz)s, addresse_ort_1 = %(ort)s WHERE id = %(id)s"""
-INIT_CASE_SQL= """UPDATE master_tbl_view SET ks = %(ka_name)s, fkz = %(fkz)s, mitarb_zv = %(vorname)s, mitarb_zn = %(nachname)s WHERE id = %(id)s"""
+UPDATE_CASE_ON_CREATE_SQL = """
+UPDATE master_tbl_view
+SET
+ name = %(name)s,
+ vorname = %(vorname)s,
+ mitarb_vv = %(gvorname)s,
+ mitarb_vn = %(gname)s,
+ einwilligung = %(einwilligung)s,
+ addresse_strassenr_1 = %(strassenr)s,
+ addresse_strasse_1 = %(strasse)s,
+ addresse_plz_1 = %(plz)s,
+ addresse_ort_1 = %(ort)s
+WHERE id = %(id)s
+"""
+INIT_CASE_SQL = """
+UPDATE master_tbl_view
+SET
+ ks = %(ka_name)s,
+ fkz = %(fkz)s,
+ mitarb_zv = %(vorname)s,
+ mitarb_zn = %(nachname)s
+WHERE id = %(id)s"""
CREATE_RG_KOMPETENZ_DS = """SELECT create_rg_kompetenz_ds(%(id)s, %(uuid)s)"""
-LOAD_STANDIN_SQL = """SELECT n.benutzer_id FROM nm_benutzer_master_tbl_view n
- JOIN master_tbl_view m ON
- m.id = n.master_id
- WHERE m.id = %(id)s"""
-ADD_STANDIN_SQL = """SELECT create_nm_benutzer_master_ds(%(groupid)s, %(caseid)s)"""
-DELETE_STANDIN_SQL = """SELECT delete_nm_benutzer_master_ds(%(groupid)s, %(caseid)s)"""
+LOAD_STANDIN_SQL = """
+SELECT n.benutzer_id
+FROM nm_benutzer_master_tbl_view n
+JOIN master_tbl_view m ON m.id = n.master_id
+WHERE m.id = %(id)s"""
+ADD_STANDIN_SQL = """
+SELECT create_nm_benutzer_master_ds(%(groupid)s, %(caseid)s)"""
+DELETE_STANDIN_SQL = """
+SELECT delete_nm_benutzer_master_ds(%(groupid)s, %(caseid)s)"""
SET_EDITOR_SQL = """SELECT set_case_editor(%(userid)s, %(caseid)s)"""
-SET_EDITOR_NAME_SQL = """SELECT set_case_editor_name(%(firstname)s, %(lastname)s, %(caseid)s)"""
-FETCH_KOMPETENZ_ID = """SELECT id from rg_kompetenzfestellung_tbl_view WHERE master_id = %(id)s LIMIT 1"""
+SET_EDITOR_NAME_SQL = """
+SELECT set_case_editor_name(%(firstname)s, %(lastname)s, %(caseid)s)"""
+FETCH_KOMPETENZ_ID = """
+SELECT id from rg_kompetenzfestellung_tbl_view WHERE master_id = %(id)s LIMIT 1
+"""
CASE_EXISTS = "SELECT * FROM case_exists(%(knummer)s)"
CREATE_SQL = {
- 'rg_angebote_bildenden_bereich_tbl': CREATE_RG_BILDEN_DS,
- 'rg_angebote_lebensbewaeltigung_tbl': CREATE_RG_LEBEN_DS,
+ 'rg_angebote_bildenden_bereich_tbl': CREATE_RG_BILDEN_DS,
+ 'rg_angebote_lebensbewaeltigung_tbl': CREATE_RG_LEBEN_DS,
'rg_angebote_berufliche_qualifizierung_tbl': CREATE_RG_QUALI_DS,
- 'rg_angebote_berufsvorbereitung_tbl': CREATE_RG_BERUF_DS
+ 'rg_angebote_berufsvorbereitung_tbl': CREATE_RG_BERUF_DS
}
-ANONYMIZE_CASE = """SELECT anonymize_case_wrapper(%(id)s)"""
+ANONYMIZE_CASE = """SELECT anonymize_case_wrapper(%(id)s)"""
+
class LoadCaseNotExistsError(Exception):
+
def __init__(self, value):
self.value = value
+
def __str__(self):
return repr(self.value)
+
class ImportCaseExistsError(Exception):
+
def __init__(self, value):
self.value = value
+
def __str__(self):
return repr(self.value)
+
class CaseList:
+
def __init__(self, case_ids=None):
self.case_list = case_ids or []
@@ -222,7 +273,7 @@
return len(self.case_list) == 0
def numDatasets(self):
- return len(self.case_list)
+ return len(self.case_list)
def getCases(self, filter=None):
list = []
@@ -235,7 +286,9 @@
list.append(factory.loadById(id))
return list
+
class CaseBundle(CaseList):
+
def __init__(self, case_ids=None):
CaseList.__init__(self, case_ids)
@@ -309,7 +362,8 @@
case.getState().setState(4)
num += 1
except:
- print >> sys.stderr, "Could not mark case for anonymisation in bundle"
+ print >> sys.stderr, \
+ "Could not mark case for anonymisation in bundle"
return num
def markDelete(self):
@@ -341,7 +395,7 @@
finally:
db.recycleConnection(con, cur)
- def exportAsXML(self, case_parts = None, anonymize=False):
+ def exportAsXML(self, case_parts=None, anonymize=False):
con, cur = None, None
f = StringIO.StringIO()
Writer = codecs.getwriter('utf-8')
@@ -357,25 +411,30 @@
finally:
db.recycleConnection(con, cur)
- def exportAsXLS(self, case_parts = None, anonymize=False):
+ def exportAsXLS(self, case_parts=None, anonymize=False):
con, cur = None, None
try:
con = db.getConnection()
cur = con.cursor()
- return exportAsXLS(cur, self.listDatasetIds(), case_parts, anonymize)
+ return exportAsXLS(cur, self.listDatasetIds(), case_parts,
+ anonymize)
finally:
db.recycleConnection(con, cur)
class CaseOverview:
+
def __init__(self):
self.ds_list = []
def sortByLastname(self):
def _cmp(a, b):
- if a is None and b is None: return 0
- if a is None: return -1
- if b is None: return +1
+ if a is None and b is None:
+ return 0
+ if a is None:
+ return -1
+ if b is None:
+ return +1
return strcoll(a.last_name, b.last_name)
self.ds_list.sort(_cmp)
@@ -385,59 +444,64 @@
result = search.perform(search_str)
factory = CaseFactory()
for row in result:
- case = factory.loadByName( \
- row['id'], \
- row['vorname_1'], \
- row['name_1'], \
- row['kundennummer'], \
- row['bearbeiter_id'], \
- row['einverstaendniserklaerung'], \
- row['s_id'], \
- row['status'], \
- row['zugriff'], \
- row['zeitraum_nachbetreuung'], \
- row['art_beendigung'])
+ case = factory.loadByName(row['id'],
+ row['vorname_1'],
+ row['name_1'],
+ row['kundennummer'],
+ row['bearbeiter_id'],
+ row['einverstaendniserklaerung'],
+ row['s_id'],
+ row['status'],
+ row['zugriff'],
+ row['zeitraum_nachbetreuung'],
+ row['art_beendigung'])
self.ds_list.append(case)
return self.ds_list
def numDatasets(self):
- return len(self.ds_list)
+ return len(self.ds_list)
def getDatasets(self):
return self.ds_list
+
class CaseFactory:
- '''Factory for case object. This factory provides methods to either load
- existing cases from db or create new cases'''
+ """Factory for case object. This factory provides methods to either load
+ existing cases from db or create new cases"""
+
def loadById(self, id):
- '''Load a case with the given id. Return a case object'''
+ """Load a case with the given id. Return a case object"""
case = Case()
result = None
conn, c = None, None
try:
conn = db.getConnection()
- c = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
+ c = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
fields = {'id': id}
c.execute(LOAD_CASE_SQL, fields)
result = c.fetchone()
- if not result: raise LoadCaseNotExistsError("Es konnte keine Fallakte geladen werden.")
+ if not result:
+ raise LoadCaseNotExistsError("Es konnte keine Fallakte geladen"
+ " werden.")
finally:
db.recycleConnection(conn, c)
case.id = int(id)
- case.last_name = unicode(str(result.get('name_1', '')), 'utf-8')
- case.first_name = unicode(str(result.get('vorname_1', '')), 'utf-8')
- case.knr = unicode(str(result.get('kundennummer', '')), 'utf-8')
+ case.last_name = unicode(str(result.get('name_1', '')), 'utf-8')
+ case.first_name = unicode(str(result.get('vorname_1', '')), 'utf-8')
+ case.knr = unicode(str(result.get('kundennummer', '')), 'utf-8')
case.first_meeting = result.get('erstgespraech')
case.cm_end = result.get('datum_cm_ende')
case.editor = result.get('bearbeiter_id', None)
case.state = State(id)
return case
- def loadByName(self, id, first_name, last_name, knr, bearbeiter_id, einverst, s_id, s_state, s_access, s_cm_finished, s_cm_canceled):
- '''This method does not actually loads a case from the database. It
- just returns a case object initiated with the provided parameters'''
+ def loadByName(self, id, first_name, last_name, knr, bearbeiter_id,
+ einverst, s_id, s_state, s_access, s_cm_finished,
+ s_cm_canceled):
+ """This method does not actually loads a case from the database. It
+ just returns a case object initiated with the provided parameters"""
case = Case()
case.id = int(id)
case.first_name = unicode(str(first_name), 'utf-8')
@@ -445,19 +509,20 @@
case.knr = unicode(str(knr), 'utf-8')
case.editor = bearbeiter_id
case.state = State()
- case.state.setData(s_id, id, s_state, s_access, s_cm_finished, s_cm_canceled)
+ case.state.setData(s_id, id, s_state, s_access, s_cm_finished,
+ s_cm_canceled)
case.privacy_statement_signed = einverst in (1, -1) and True or False
return case
def createNew(self, init=True, uuid=None, data=None):
- '''This method creates a new case in the database and takes care about
+ """This method creates a new case in the database and takes care about
creating the right dependencies for repeat groups. If 'init' is true
- will get initiated. This method returns the case object'''
+ will get initiated. This method returns the case object"""
conn, cur = None, None
try:
try:
conn = db.getConnection()
- cur = conn.cursor()
+ cur = conn.cursor()
cur.execute(CREATE_CASE_SQL, {'uuid': uuid})
id = int(cur.fetchone()[0])
conn.commit()
@@ -489,7 +554,7 @@
def _updateMasterOnCreate(self, id, data):
factory = InstanceFactory(g.formedTree, PostgresDBInterface())
instance_tree = factory.loadInstanceTreeByIdentifier(
- id,
+ id,
session.get('uncommited_fields'))
try:
form_result = convert2dic(data)
@@ -498,7 +563,8 @@
nkey = None
for key, value in form_result.iteritems():
nkey = get_field_identifier(id, key, instance_tree)
- if not nkey: continue
+ if not nkey:
+ continue
data[nkey] = value
print data
@@ -525,11 +591,11 @@
user = session['USER_AUTHORIZED']
agency = Agency()
fields = {
- 'ka_name': agency.getName(),
- 'vorname': user.first_name,
+ 'ka_name': agency.getName(),
+ 'vorname': user.first_name,
'nachname': user.last_name,
- 'fkz': agency.getFKZ(),
- 'id': int(id)
+ 'fkz': agency.getFKZ(),
+ 'id': int(id)
}
conn = db.getConnection()
cur = conn.cursor()
@@ -550,7 +616,8 @@
cur = con.cursor()
cur.execute(CREATE_RG_KOMPETENZ_DS, { 'id': id, 'uuid': uuid})
komp_id = cur.fetchone()[0]
- cur.close(); cur = None
+ cur.close()
+ cur = None
# TODO: Uncomment the following as soon as the SP exist.
# create three Maßnahmen per master data set
@@ -589,20 +656,23 @@
# TODO: It seems that the following lines of code are doing already
# implemented functionality. Think about cleaning up here but i do
# not fully understand what is happening exctly here. Maybe the
- # next two outcommented lines could do the trick.
+ # next two outcommented lines could do the trick.
#case = self.creatNew()
#masterId = case.id
cur.execute(CREATE_CASE_SQL, {'uuid': uuid})
masterId = cur.fetchone()[0]
- cur.close(); cur = None
+ cur.close()
+ cur = None
createdTables['master_tbl'] = masterId
# kompetenz rg has to be created each time
cur = con.cursor()
- cur.execute(CREATE_RG_KOMPETENZ_DS, { 'id': masterId, 'uuid': uuid })
+ cur.execute(CREATE_RG_KOMPETENZ_DS,
+ {'id': masterId, 'uuid': uuid})
rid = cur.fetchone()[0]
- cur.close(); cur = None
+ cur.close()
+ cur = None
con.commit()
createdTables['rg_kompetenzfestellung_tbl'] = rid
@@ -616,12 +686,14 @@
try:
stmnt = CREATE_SQL[name]
except KeyError:
- print >> sys.stderr, "Kann Statement zur Erzeugung von '%s' nicht finden." % name
+ print >> sys.stderr, ("Kann Statement zur Erzeugung"
+ " von '%s' nicht finden." % name)
continue
cur = con.cursor()
- cur.execute(stmnt, { 'id': masterId, 'uuid': uuid })
+ cur.execute(stmnt, {'id': masterId, 'uuid': uuid})
id = cur.fetchone()[0]
- cur.close(); cur = None
+ cur.close()
+ cur = None
# write the relations
for rel in rels:
@@ -641,7 +713,7 @@
return rel.getColumn(u"kundennummer")
except KeyError:
pass
-
+
return None
@@ -652,14 +724,17 @@
cur = con.cursor()
cur.execute(CASE_EXISTS, { 'knummer': knummer })
row = cur.fetchone()
- if row is None: return False
+ if row is None:
+ return False
return row[0]
finally:
db.recycleConnection(con, cur)
class CaseStandin:
- '''This class represents the standin for a case'''
+
+ """This class represents the standin for a case"""
+
def __init__(self, case_id=None):
self.case_id = case_id
self.group_ids = []
@@ -679,11 +754,11 @@
db.recycleConnection(con, cur)
def getGroups(self):
- '''Returns a list of group ids'''
+ """Returns a list of group ids"""
return self.group_ids
def setGroups(self, groupid_list):
- '''Sets the Standin to the provided list of group ids'''
+ """Sets the Standin to the provided list of group ids"""
old = Set(self.getGroups())
new = Set(groupid_list)
self._delete(old - new)
@@ -701,7 +776,8 @@
cur.execute(DELETE_STANDIN_SQL, fields)
except:
con.rollback()
- cur.close(); cur = None
+ cur.close()
+ cur = None
con.commit()
finally:
db.recycleConnection(con, cur)
@@ -718,21 +794,24 @@
cur.execute(ADD_STANDIN_SQL, fields)
except:
con.rollback()
- cur.close(); cur = None
+ cur.close()
+ cur = None
con.commit()
finally:
db.recycleConnection(con, cur)
+
class CaseDigest:
+
def __init__(self, id):
self.resetValues(id)
self._loadFromDB(id)
def resetValues(self, id):
self.id = id
- self.first_name = ''
- self.last_name = ''
- self.knr = ''
+ self.first_name = ''
+ self.last_name = ''
+ self.knr = ''
self.age = '0'
self.plz = ''
self.city = ''
@@ -800,11 +879,14 @@
for name in fields:
fid = get_field_identifier(id, name, it)
print fid
- if not fid: continue
+ if not fid:
+ continue
item = it.getItem(fid)
- if not item: continue
+ if not item:
+ continue
value = item.getValue()
- if not value: continue
+ if not value:
+ continue
result[name] = value
except:
traceback.print_exc(file=sys.stderr)
@@ -824,7 +906,7 @@
self.email = unicode(str(result.get('addresse_email', '')), 'utf-8')
td = date.today() - result .get('geburtsdatum', date.today())
- self.age = td.days/365 or ""
+ self.age = td.days/365 or ""
self.statement = (result.get('einverstaendniserklaerung') >= 0)
# Parents of the kids
@@ -846,12 +928,17 @@
class SessionCase:
- '''This class holds all needed information for the currently selected case'''
+
+ """This class holds all needed information for the currently selected case
+ """
+
def __init__(self, id=None):
- if id is None: self.id = None
- else: self.id = int(id)
- self.page_id = None
- self.mode = "show"
+ if id is None:
+ self.id = None
+ else:
+ self.id = int(id)
+ self.page_id = None
+ self.mode = "show"
self.form_errors = {}
self.last_name = None
self.first_name = None
@@ -861,16 +948,17 @@
self.cm_end = None
self.privacy_statement = False
- self.street = None
- self.streetnr = None
- self.plz = None
+ self.street = None
+ self.streetnr = None
+ self.plz = None
self.city = None
def getState(self):
return self.state
def getEditor(self):
- #TODO: See issue432 (WASKO). Fix this function. It seems to be not used anyway.
+ # TODO: See issue432 (WASKO). Fix this function. It seems to be
+ # not used anyway.
return self.state
def getMode(self):
@@ -913,20 +1001,21 @@
}
def getFirstMeeting(self):
- #TODO: See issue432 (WASKO). Fix this function. It seems to be not used anyway.
+ # TODO: See issue432 (WASKO). Fix this function. It seems to be
+ # not used anyway.
return self.first_meeting
def isYoungerThan(self, mydate):
- '''Return True if case was active relative to mydate.
+ """Return True if case was active relative to mydate.
Case either started or finished after mdate, or no end date set.
- '''
- y,m,d = mydate.split('-')
+ """
+ y, m, d = mydate.split('-')
if self.first_meeting:
if self.first_meeting > date(int(y), int(m), int(d)):
return True
elif self.cm_end and (self.cm_end <= date(int(y), int(m), int(d))
- and self.cm_end != UNKNOWN_DATE):
+ and self.cm_end != UNKNOWN_DATE):
return False
else:
return True
@@ -935,14 +1024,16 @@
def save():
pass
+
class Case:
+
def __init__(self):
- self.id = None
- self.first_name = None
- self.last_name = None
- self.knr = None
+ self.id = None
+ self.first_name = None
+ self.last_name = None
+ self.knr = None
self.editor = None
- self.standin = None
+ self.standin = None
self.state = None
self.first_meeting = None
self.cm_end = None
@@ -957,7 +1048,8 @@
self.discretion_statement = None
def delete(self):
- '''Deletes the case from data base. Returns True if deletion succseeds'''
+ """Deletes the case from data base. Returns True if deletion succseeds
+ """
conn, cur = None, None
try:
try:
@@ -970,14 +1062,13 @@
db.recycleConnection(conn, cur)
except:
traceback.print_exc(file=sys.stderr)
- return False
+ return False
def getId(self):
return self.id
def getMode(self):
- session = self.getSessionCase()
- return session.getMode()
+ return self.getSessionCase().getMode()
def setMode(self, mode="show"):
s = self.getSessionCase(self.id)
@@ -991,23 +1082,24 @@
self.state.setState(value)
def getSessionCase(self):
- '''Returns a SessionCaseObject which is initiated with values from the current case'''
+ """Return a SessionCase object initialized from the current case"""
session = SessionCase(self.id)
session.last_name = self.last_name
- session.first_name = self.first_name
+ session.first_name = self.first_name
session.knr = self.knr
session.state = self.state
session.first_meeting = self.first_meeting
session.cm_end = self.cm_end
privacy_statement = self.getPrivacyStatement()
- session.privacy_statement = privacy_statement.isSigned()
+ session.privacy_statement = privacy_statement.isSigned()
return session
def getStandin(self):
- '''Returns the standin of the case'''
- if not self.standin is None: return self.standin
+ """Returns the standin of the case"""
+ if not self.standin is None:
+ return self.standin
try:
- self.standin = CaseStandin(self.id)
+ self.standin = CaseStandin(self.id)
return self.standin
except:
self.standin = None
@@ -1015,15 +1107,16 @@
return None
def getEditor(self):
- '''Returns the editor of the case'''
+ """Returns the editor of the case"""
return UserObject(self.editor)
def setEditor(self, userid):
- '''sets the editor of the case to the given userid'''
+ """sets the editor of the case to the given userid"""
con, curr = None, None
user = UserObject(userid)
fields1 = {'caseid': self.id, 'userid': userid}
- fields2 = {'caseid': self.id, 'firstname': user.first_name, 'lastname': user.last_name}
+ fields2 = {'caseid': self.id, 'firstname': user.first_name,
+ 'lastname': user.last_name}
try:
con = db.getConnection()
cur = con.cursor()
@@ -1038,8 +1131,9 @@
return self.editor
def getDigest(self, empty=False):
- '''Returns the digest of the case'''
- if not self.digest is None: return self.digest
+ """Returns the digest of the case"""
+ if not self.digest is None:
+ return self.digest
try:
# Create digest
self.digest = CaseDigest(self.id)
@@ -1053,12 +1147,13 @@
return None
def getPrivacyStatement(self):
- '''Returns the privacy statement of the case'''
- if not self.privacy_statement is None: return self.privacy_statement
+ """Returns the privacy statement of the case"""
+ if not self.privacy_statement is None:
+ return self.privacy_statement
try:
- # Create privacy_statement
+ # Create privacy_statement
self.privacy_statement = PrivacyStatement(self.id)
- self.privacy_statement.fillout(self.getDigest(), Agency())
+ self.privacy_statement.fillout(self.getDigest(), Agency())
return self.privacy_statement
except:
self.privacy_statement = None
@@ -1066,12 +1161,13 @@
return None
def getDiscretionStatement(self):
- '''Returns the privacy statement of the case'''
- if not self.discretion_statement is None: return self.discretion_statement
+ """Returns the privacy statement of the case"""
+ if not self.discretion_statement is None:
+ return self.discretion_statement
try:
- # Create discretion_statement
+ # Create discretion_statement
self.discretion_statement = DiscretionStatement(self.id)
- self.discretion_statement.fillout(self.getDigest(), Agency())
+ self.discretion_statement.fillout(self.getDigest(), Agency())
return self.discretion_statement
except:
self.discretion_statement = None
@@ -1079,13 +1175,16 @@
return None
def getAidPlanStatement(self):
- '''Returns the aid plan statement of the case'''
- if not self.aidplan_statement is None: return self.aidplan_statement
+ """Returns the aid plan statement of the case"""
+ if not self.aidplan_statement is None:
+ return self.aidplan_statement
try:
- # Create aidplan statement
+ # Create aidplan statement
rg_list = AidList(self.id)
- self.aidplan_statement = AidPlanStatement(self.id)
- self.aidplan_statement.fillout(client=self.getDigest(), agency=Agency(), rg_list=rg_list.getDatasets())
+ self.aidplan_statement = AidPlanStatement(self.id)
+ self.aidplan_statement.fillout(client=self.getDigest(),
+ agency=Agency(),
+ rg_list=rg_list.getDatasets())
return self.aidplan_statement
except:
self.aidplan_statement = None
@@ -1093,34 +1192,34 @@
return None
def getDocuments(self):
- '''Returns a list of documents which are attached to this case'''
+ """Returns a list of documents which are attached to this case"""
try:
- # Load list of documents
- self.documents = listDocuments(self.id)
+ # Load list of documents
+ self.documents = listDocuments(self.id)
return self.documents
except:
self.documents = []
raise
- return []
+ return []
def getAppointments(self):
- '''Returns a list of appointments which are attached to this case'''
+ """Returns a list of appointments which are attached to this case"""
try:
- # Load list of appointments
+ # Load list of appointments
pass
except:
self.documents = []
raise
- return []
+ return []
def anonymize(self):
- '''Deleted personal data in the case'''
+ """Deleted personal data in the case"""
conn, cur = None, None
try:
try:
conn = db.getConnection()
cur = conn.cursor()
- d = { 'id': self.id }
+ d = {'id': self.id}
cur.execute(ANONYMIZE_CASE, d)
finally:
db.recycleConnection(conn, cur)
@@ -1139,34 +1238,50 @@
self.getState().setState(1)
def getFirstMeeting(self):
- #TODO: See issue432 (WASKO). Fix this function. It seems to be not used anyway.
+ # TODO: See issue432 (WASKO). Fix this function. It seems to be
+ # not used anyway.
return self.first_meeting
def isYoungerThan(self, mydate):
- '''Return True if case was active relative to mydate.
+ """Return True if case was active relative to mydate.
Case either started or finished after mdate, or no end date set.
- '''
- y,m,d = mydate.split('-')
+ """
+ y, m, d = mydate.split('-')
if self.first_meeting:
if self.first_meeting > date(int(y), int(m), int(d)):
return True
elif self.cm_end and (self.cm_end <= date(int(y), int(m), int(d))
- and self.cm_end != UNKNOWN_DATE):
+ and self.cm_end != UNKNOWN_DATE):
return False
else:
return True
return True
+
class State(object):
- '''This class store the state and the last accesstime of the case.
+
+ """This class store the state and the last accesstime of the case.
Possible states are:
* Open (1)
* Closes (2)
* outstanding deletion (3)
* outstanding anonymision (4)
- * anonymised (5)'''
+ * anonymised (5)
+ """
+ def __init__(self, master_id=None):
+ self.master_id = master_id
+ self.id = None
+ self.state = None
+ self.access = None
+ self.phase = None
+ self._last_date = None
+
+ if master_id:
+ self.master_id = master_id
+ self._load()
+
def getLastDateFromDB(self):
if self._last_date:
return self._last_date
@@ -1179,19 +1294,6 @@
last_date = property(getLastDateFromDB)
- def __init__(self, master_id=None):
- self.master_id = master_id
- self.id = None
- self.state = None
- self.access = None
- self.phase = None
- self._last_date = None
-
- if master_id:
- self.master_id = master_id
- self._load()
-
-
def setData(self, id, master_id, state, access, cm_finished, cm_canceled):
self.master_id = master_id
self.id = id
@@ -1217,25 +1319,25 @@
db.recycleConnection(conn, cur)
except:
traceback.print_exc(file=sys.stderr)
- return False
+ return False
def getStateLabel(self):
- state_labels = {'1' : _('case_state_label_open'),
- '2' : _('case_state_label_open'),
- '3' : _('case_state_label_outstanding_delete'),
- '4' : _('case_state_label_outstanding_anon'),
- '5' : _('case_state_label_anon')
- }
+ state_labels = {'1': _('case_state_label_open'),
+ '2': _('case_state_label_open'),
+ '3': _('case_state_label_outstanding_delete'),
+ '4': _('case_state_label_outstanding_anon'),
+ '5': _('case_state_label_anon'),
+ }
return state_labels.get(str(self.state))
def getState(self):
return self.state
def isCmFinished(self):
- return self.phase in (4, )
+ return self.phase in (4,)
def isCmCanceled(self):
- return self.phase in (2,3)
+ return self.phase in (2, 3)
def setState(self, value):
conn, cur = None, None
@@ -1252,7 +1354,7 @@
return True
except:
traceback.print_exc(file=sys.stderr)
- return False
+ return False
def setPhase(self, phase):
conn, cur = None, None
@@ -1269,7 +1371,7 @@
return True
except:
traceback.print_exc(file=sys.stderr)
- return False
+ return False
def getPhase(self):
return self.phase
@@ -1278,12 +1380,12 @@
return phase_description(self.phase)
def phasesAreConsistent(self):
- '''Returns True when the required fields for the current phase are
- complete and there are no other inconsistencys. Else False'''
+ """Returns True when the required fields for the current phase are
+ complete and there are no other inconsistencys. Else False"""
#case = CaseFactory().loadById(self.master_id) # Ugly we need to load the case here :(
cf = self.getPhase()
rf = RequiredFields(g.formedTree)
- p_pairs = rf.phases_pairs(cf, master_id = self.master_id)
+ p_pairs = rf.phases_pairs(cf, master_id=self.master_id)
for pair in p_pairs:
p1, p2 = pair.getStart(), pair.getEnd()
@@ -1291,7 +1393,7 @@
if p1.isRunning() and not p1.isRecursiveComplete():
return False
elif p2.isRunning() and not p2.isRecursiveComplete():
- return False
+ return False
# Deaktiviert, da noch keine weiteren Inkonsistezen geprüft (bekannt
# sind)) werden
@@ -1304,23 +1406,24 @@
return True
def phasesAreCompleted(self):
- '''Returns True if the required fields for the ending of the
- current phase pair are completed and the phase ist finished.
- Else False.'''
+ """Returns True if the required fields for the ending of the
+ current phase pair are completed and the phase ist finished.
+ Else False."""
cf = self.getPhase()
rf = RequiredFields(g.formedTree)
- current_phase = rf.currentPhase(cf, master_id = self.master_id)
+ current_phase = rf.currentPhase(cf, master_id=self.master_id)
# WASKO requires a special handling of CM_START:
- # - if CM_START is completed and
+ # - if CM_START is completed and
# - cm_end_art == 3 (Abbruch) and
# - datum_cm_ende is set.
if cf == CM_START:
- if current_phase.isRecursiveComplete() \
- and g.formedTree.getData('cm_end_art', self.master_id) == 3 \
- and g.formedTree.getData('datum_cm_ende', self.master_id) \
- and str(g.formedTree.getData('datum_cm_ende', self.master_id)) != '0001-01-01':
- return True
+ if (current_phase.isRecursiveComplete()
+ and g.formedTree.getData('cm_end_art', self.master_id) == 3
+ and g.formedTree.getData('datum_cm_ende', self.master_id)
+ and (str(g.formedTree.getData('datum_cm_ende', self.master_id))
+ != '0001-01-01')):
+ return True
else:
return False
elif cf == CLEAR_START or cf == CLEAR_ENDE:
@@ -1328,7 +1431,7 @@
elif phase_end(cf) and current_phase.isRecursiveComplete():
return True
else:
- return False
+ return False
def getAccessTime(self, format=None):
if format:
@@ -1339,7 +1442,9 @@
return self.access
def getLastDate(self, format=None):
- '''Returns the last occouring date from appointments, aids, or the last accesstime'''
+ """Returns the last occuring date from appointments, aids, or
+ the last accesstime
+ """
if format:
try:
return self.last_date.strftime(format)
@@ -1351,15 +1456,14 @@
pass
def getMaxSavetime(self):
- agency = Agency()
- return agency.getMaxSavetime()
+ return Agency().getMaxSavetime()
def daysToMaxSavetime(self):
- maxage = self.getMaxSavetime()
+ maxage = self.getMaxSavetime()
if self.isCmFinished() or self.isCmCanceled():
- age = datetime.now() - self.getAccessTime()
+ age = datetime.now() - self.getAccessTime()
else:
- age = datetime.now() - self.getLastDate()
+ age = datetime.now() - self.getLastDate()
if int(maxage) != 0:
return int(maxage) - age.days
return None
More information about the Mpuls-commits
mailing list