add solis apa connector (#5188)

This commit is contained in:
Josue Kouka 2016-04-25 17:35:31 +02:00
parent b733c4a5f4
commit 795e49d38a
11 changed files with 1642 additions and 0 deletions

View File

@ -0,0 +1,27 @@
# Passerelle - uniform access to data and services
# Copyright (C) 2015 Entr'ouvert
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
import django.apps
class AppConfig(django.apps.AppConfig):
name = 'passerelle.contrib.solis_apa'
label = 'solis_apa'
def get_after_urls(self):
from . import urls
return urls.urlpatterns
default_app_config = 'passerelle.contrib.solis_apa.AppConfig'

View File

@ -0,0 +1,234 @@
# Passerelle - uniform access to data and services
# Copyright (C) 2015 Entr'ouvert
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
CONCILIATION_INDIVIDU = {
'block': {
'name': 'Individu',
'pk': "PK/IndexIndividu/@V"
},
'criteria': {
5: ({
'EtatCivil/Nom/@V': 'equal',
'EtatCivil/Prenom/@V': 'equal',
'EtatCivil/DateNaissance/@V': 'equal',
},
{
'EtatCivil/NomJeuneFille/@V': 'equal',
'EtatCivil/Prenom/@V': 'equal',
'EtatCivil/DateNaissance/@V': 'equal',
},),
4: ({
'EtatCivil/Nom/@V': 'equal',
'EtatCivil/DateNaissance/@V': 'equal',
},
{
'EtatCivil/NomJeuneFille/@V': 'equal',
'EtatCivil/DateNaissance/@V': 'equal',
},
{
'EtatCivil/Nom/@V': 'equal',
'EtatCivil/Prenom/@V': 'equal',
},
{
'EtatCivil/NomJeuneFille/@V': 'equal',
'EtatCivil/Prenom/@V': 'equal',
},
),
},
'input': {
'EtatCivil/Nom/@V': 'nom',
'EtatCivil/Prenom/@V': 'prenom',
'EtatCivil/DateNaissance/@V': 'dn',
'EtatCivil/NomJeuneFille/@V': 'nom',
},
'output': [
"Dossier/PK/IndexDossier/@V",
"PK/IndexIndividu/@V",
"EtatCivil/Nom/@V",
"EtatCivil/NomJeuneFille/@V",
"EtatCivil/Prenom/@V",
"EtatCivil/DateNaissance/@V",
"Dossier/Adresse/NumeroLieu/@V",
"Dossier/Adresse/NatureLieu/@Lc",
"Dossier/Adresse/NomLieu/@V",
"Dossier/Adresse/ComplementLieu/@V",
"Dossier/Adresse/CpLieu/@V",
"Dossier/Adresse/Commune/NomCom/@V"
]
}
CONCILIATION_INDIVIDU_SANS_DN = {
'block': {
'name': 'Individu',
'pk': "PK/IndexIndividu/@V"
},
'criteria': {
5: ({
'EtatCivil/Nom/@V': 'equal',
'EtatCivil/Prenom/@V': 'equal',
},{
'EtatCivil/NomJeuneFille/@V': 'equal',
'EtatCivil/Prenom/@V': 'equal',
},),
4: ({
'EtatCivil/Nom/@V': 'equal',
'EtatCivil/Prenom/@V': 'approx',
},),
3: ({
'EtatCivil/Nom/@V': 'approx',
'EtatCivil/Prenom/@V': 'equal',
},),
},
'input': {
'EtatCivil/Nom/@V': 'nom',
'EtatCivil/Prenom/@V': 'prenom',
'EtatCivil/NomJeuneFille/@V': 'nom',
},
'output': [
"Dossier/PK/IndexDossier/@V",
"PK/IndexIndividu/@V",
"EtatCivil/Nom/@V",
"EtatCivil/NomJeuneFille/@V",
"EtatCivil/Prenom/@V",
"EtatCivil/DateNaissance/@V",
"Dossier/Adresse/NumeroLieu/@V",
"Dossier/Adresse/NatureLieu/@Lc",
"Dossier/Adresse/NomLieu/@V",
"Dossier/Adresse/ComplementLieu/@V",
"Dossier/Adresse/CpLieu/@V",
"Dossier/Adresse/Commune/NomCom/@V"
]
}
CONCILIATION_ADRESSE = {
'block': {
'name': 'Adresse',
'pk': "CodeLieu/@V"
},
'criteria': {
5: ({
'NomLieu/@V': 'matches',
'Commune/PK/CodeDepartement/@V': 'equal',
'Commune/PK/CodeCommune/@V': 'equal',
},),
},
'input': {
'NomLieu/@V': 'lieu',
'Commune/PK/CodeDepartement/@V': 'departement',
'Commune/PK/CodeCommune/@V': 'commune',
},
'output': [
"CodeLieu/@V",
"NatureLieu/@Lc",
"NomLieu/@V",
"CodePostal/@V",
"Commune/PK/CodeCommune/@V",
"Commune/NomCom/@V",
"CodeDepartement/@V",
]
}
CONCILIATION_PARTICULIER = {
'block': {
'name': 'Particulier',
'pk': "PK/IndexParticulier/@V"
},
'criteria': {
5: ({
'EtatCivil/Nom/@V': 'equal',
'EtatCivil/Prenom/@V': 'equal',
},{
'EtatCivil/NomJeuneFille/@V': 'equal',
'EtatCivil/Prenom/@V': 'equal',
},),
4: ({
'EtatCivil/Nom/@V': 'equal',
'EtatCivil/Prenom/@V': 'approx',
},),
3: ({
'EtatCivil/Nom/@V': 'approx',
'EtatCivil/Prenom/@V': 'equal',
},),
},
'input': {
'EtatCivil/Nom/@V': 'nom',
'EtatCivil/Prenom/@V': 'prenom',
'EtatCivil/NomJeuneFille/@V': 'nom',
},
'output': [
"PK/IndexParticulier/@V",
"EtatCivil/Nom/@V",
"EtatCivil/NomJeuneFille/@V",
"EtatCivil/Prenom/@V",
"EtatCivil/DateNaissance/@V",
"Adresse/NumeroLieu/@V",
"Adresse/NatureLieu/@Lc",
"Adresse/NomLieu/@V",
"Adresse/ComplementLieu/@V",
"Adresse/CpLieu/@V",
"Adresse/Commune/NomCom/@V"
]
}
def conciliation_payload(config, **data):
block = {
"name": config['block']['name'],
"PrimaryKey": { "key": [ config['block']['pk'] ] }
}
setting = []
for affinity, afflist in config['criteria'].items():
for aff in afflist:
criterium = []
for xpath, op in aff.items():
criterium.append({
'key': xpath,
'operator': op
})
setting.append({
"affinity": affinity,
"Criterium": criterium,
})
criterium = []
for xpath, local in config['input'].items():
criterium.append({
'key': xpath,
'value': data.get(local, u'')
})
returndata = []
for xpath in config['output']:
returndata.append(xpath)
return {
"ConciliationInputWS": {
"Block": block,
"Input": {
"Settings": { "Setting": setting, },
"Criteria": { "Criterium": criterium },
},
"Output": { "ReturnDatas": { "returnData": returndata }, },
}
}
def conciliation_output2dict(config, entity):
d = {}
for xpath in config['output']:
x = entity
for k in xpath.split('/'):
x = x.get(k, {})
d[xpath] = x or u''
return d

View File

@ -0,0 +1,35 @@
# passerelle.contrib.iparapheur
# Copyright (C) 2015 Entr'ouvert
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
from django.utils.text import slugify
from django import forms
from .models import SolisAPA
class SolisAPAForm(forms.ModelForm):
class Meta:
model = SolisAPA
exclude = ('slug', 'users')
def save(self, commit=True):
if not self.instance.slug:
self.instance.slug = slugify(self.instance.title)
return super(SolisAPAForm, self).save(commit=commit)
class SolisAPAUpdateForm(SolisAPAForm):
class Meta:
model = SolisAPA
exclude = ('users',)

View File

@ -0,0 +1,514 @@
# Passerelle - uniform access to data and services
# Copyright (C) 2015 Entr'ouvert
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
import datetime
def build_message(data):
message = {}
fields = data['fields']
wf = data['workflow']['data']
date_completude = datetime.date.today().strftime('%Y-%m-%d')
if 'numero' in fields:
statut_demande = 2
else:
statut_demande = 1
try:
aide_ccas = (fields.get('aide_ccas') or '').strip().upper().startswith('OUI')
except:
aide_ccas = True
protection = get_protection(fields, wf)
if protection:
message['MesureProtection'] = protection
demandeur = get_demandeur(fields, wf)
if demandeur:
message['Demandeur'] = demandeur
message['Beneficiaire'] = get_beneficiare(fields, wf)
conjoint = get_conjoint(fields, wf)
if conjoint:
message['Conjoint'] = conjoint
revenus = get_revenu(fields, wf)
if revenus:
message['RevenusImposition'] = revenus
message['InformationsBancaires'] = get_info_bancaire(fields, wf)
message['Patrimoine'] = get_patrimoine(fields, wf)
etablissement, etablissement_date_entree = get_etablissement(fields, wf)
demande_apa = {
'statutDemande': statut_demande,
'dateDepot': data['receipt_time'][0:10],
'dateArrivee': data['receipt_time'][0:10],
'dateCompletude': date_completude
}
demande_apa_nomenclature = {'codeNature':1, 'codeType': 68} if\
etablissement else {'codeNature': 2, 'codeType': 70}
demande_apa['Nomenclature'] = demande_apa_nomenclature
demande_apa['codeLieuDepot'] = 8 if aide_ccas else 7
message['DemandeApa'] = demande_apa
return message
def get_protection(fields, wf):
protection_type = wf.get('supp2_var_typeprotectionorga') or fields['typeprotectionorga'] or fields['typeprotectionpers']
if protection_type:
protection_type = protection_type.strip().upper()
if 'TUTELLE' in protection_type:
protection_type = 4
elif 'CURATELLE' in protection_type:
protection_type = 3
elif 'SAUVEGARDE' in protection_type:
protection_type = 5
else:
protection_type = None
else:
protection_type = None
protection_organisme = wf.get('tutelle_var_organisme_raw') or wf.get('supp2_var_organisme_raw') or fields.get('papier_organisme_raw')
if protection_organisme:
protection_organisme = protection_organisme.split('-')[1]
else:
protection_organisme = None
message = {}
if protection_organisme:
message['indexOrganismeTutelle'] = protection_organisme
message['codeTypeProtection'] = protection_type
return message
def get_demandeur(fields, wf):
protection = get_protection(fields, wf)
protection_type = protection.get('codeTypeProtection', None)
protection_organisme = protection.get('indexOrganismeTutelle', None)
demandeur_profil = fields['profildemandeur'].strip().upper()
if 'PERSONNE' in demandeur_profil:
demandeur_profil = 'PERSONNE'
elif 'PROCHE' in demandeur_profil:
demandeur_profil = 'PROCHE'
elif 'ORGANISME' in demandeur_profil:
demandeur_profil = 'ORGANISME'
else:
demandeur_profil = 'BENEFICIAIRE'
if demandeur_profil in ('PERSONNE', 'PROCHE'):
demandeur_id = None
demandeur_nom = wf.get('supp1_var_nomdemandeur') or fields['nomdemandeur']
demandeur_nom = demandeur_nom.strip().upper()
demandeur_prenom = wf.get('supp1_var_prenomdemandeur') or fields['prenomdemandeur']
demandeur_prenom = demandeur_prenom.strip().upper()
demandeur_civilite = wf.get('supp1_var_civilitedemandeur') or fields['civilitedemandeur'] or ''
demandeur_civilite = demandeur_civilite.strip().upper()
if 'MONSIEUR' in demandeur_civilite:
demandeur_sexe = 'H'
else:
demandeur_sexe = 'F'
demandeur_tel = wf.get('supp1_var_teldemandeur') or fields['teldemandeur']
demandeur_email = wf.get('supp1_var_courrieldemandeur') or fields['courrieldemandeur']
message = {}
if demandeur_id:
message['indexParticulier'] = demandeur_id
if not protection_type and not protection_organisme:
message['typeProtection'] = protection_type
message.update({
'nom': demandeur_nom,
'prenom': demandeur_prenom,
'sexe': demandeur_sexe,
'Adresse': {
'codeDepartement': 14,
'codeCommune': 990,
'codeLieu': '9999'
}
})
contact = {'email': demandeur_email}
if demandeur_tel:
contact['telephone'] = demandeur_tel
message['Contact'] = contact
return message
return None
def get_etablissement(fields, wf):
etablissement = wf.get('etablissement_var_nometablissement_raw') or fields.get('papier_nometablissement_raw')
if etablissement:
etablissement = etablissement.split('-')[1]
etablissement_date_entree = fields.get('date_etablissement') or ''
etablissement_date_entree = etablissement_date_entree[0:10]
else:
etablissement = None
etablissement_date_entree = None
return (etablissement, etablissement_date_entree)
def get_beneficiare(fields, wf):
beneficiaire_id = None
if not wf.get('homonymie_var_homonyme_new_user'):
beneficiaire_id = wf.get('homonymie_var_homonyme_force_id')
if not beneficiaire_id:
beneficiaire_id = wf.get('homonymie_var_homonyme_id_raw')
beneficiaire_civilite = wf.get('supp3_var_civilitebeneficiaire') or fields['civilitebeneficiaire']
beneficiaire_civilite = beneficiaire_civilite.strip().upper()
if 'MONSIEUR' in beneficiaire_civilite:
beneficiaire_sexe = 'H'
else:
beneficiaire_sexe = 'F'
beneficiaire_nom = wf.get('supp3_var_nombeneficiaire') or fields['nombeneficiaire']
beneficiaire_nom = beneficiaire_nom.strip().upper()
beneficiaire_nomnaissance = wf.get('supp3_var_nomdenaissance') or fields['nomdenaissance'] or ''
beneficiaire_nomnaissance = beneficiaire_nomnaissance.strip().upper()
if beneficiaire_nomnaissance == '':
beneficiaire_nomnaissance = None
beneficiaire_prenom = wf.get('supp3_var_prenombeneficiaire') or fields['prenombeneficiaire']
beneficiaire_prenom = beneficiaire_prenom.strip().upper()
beneficiaire_dn = wf.get('supp3_var_dnnbeneficiaire') or fields['dnnbeneficiaire']
beneficiaire_dn = beneficiaire_dn[0:10]
beneficiaire_ln = wf.get('supp3_var_lieunbeneficiaire') or fields['lieunbeneficiaire']
beneficiaire_ln = beneficiaire_ln.strip().upper()
beneficiaire_nationalite = wf.get('supp3_var_nationalitebeneficiaire') or fields['nationalitebeneficiaire']
beneficiaire_nationalite = beneficiaire_nationalite.strip().upper()
if 'NATIONAL' in beneficiaire_nationalite:
beneficiaire_nationalite = 1
elif 'RESSORTISSANT' in beneficiaire_nationalite:
beneficiaire_nationalite = 2
else:
beneficiaire_nationalite = 3
beneficiaire_situation = wf.get('supp3_var_situationfamillebeneficiaire') or fields['situationfamillebeneficiaire']
beneficiaire_situation = beneficiaire_situation.strip().upper()
if 'MARI' in beneficiaire_situation:
beneficiaire_situation = 2
elif 'DIVOR' in beneficiaire_situation:
beneficiaire_situation = 5
elif 'VEUF' in beneficiaire_situation:
beneficiaire_situation = 3
elif 'CONCUB' in beneficiaire_situation:
beneficiaire_situation = 7
elif 'PACS' in beneficiaire_situation:
beneficiaire_situation = 8
else:
beneficiaire_situation = 1 # celibataire
beneficiaire_tel = wf.get('supp3_var_telbeneficiaire') or fields['telbeneficiaire']
beneficiaire_email = wf.get('supp3_var_courrielbeneficiaire') or fields['courrielbeneficiaire']
beneficiaire_code_commune_raw = wf.get('adresse_var_code_commune_raw') or fields.get('papier_code_commune_raw')
beneficiaire_code_commune = beneficiaire_code_commune_raw.split('-')[2]
beneficiaire_code_departement = beneficiaire_code_commune_raw.split('-')[1]
beneficiaire_numero_lieu = wf.get('adresse_var_num_lieu') or fields.get('papier_num_lieu')
beneficiaire_code_lieu = wf.get('adresse_var_code_lieu_raw') or fields.get('papier_code_lieu_raw')
beneficiaire_retraite = wf.get('supp3_var_retraitebeneficiaire') or fields['retraitebeneficiaire']
beneficiaire_retraite = beneficiaire_retraite.strip().upper()
beneficiaire_retraite = 'OUI' in beneficiaire_retraite
if beneficiaire_retraite:
info = wf.get('supp3_var_regretraitebeneficiaire_raw') or wf.get('retraite_var_listeretraite_raw') or fields.get('papier_listeretraite_raw')
beneficiaire_retraite_code = info.split('-')[1]
message = {}
if beneficiaire_id:
message['indexIndividu'] = beneficiaire_id
message.update({'nom': beneficiaire_nom, 'prenom': beneficiaire_prenom})
if beneficiaire_nomnaissance:
message['nomJeuneFille'] = beneficiaire_nomnaissance
message.update({
'sexe': beneficiaire_sexe,
'dateNaissance': beneficiaire_dn
})
if beneficiaire_ln:
message['lieuNaissance'] = beneficiaire_ln
message.update({
'nationalite': beneficiaire_nationalite,
'situationFamiliale': beneficiaire_situation
})
if beneficiaire_tel or beneficiaire_email:
contact = {}
if beneficiaire_tel:
contact['telephone'] = beneficiaire_tel
if beneficiaire_email:
contact['email'] = beneficiaire_email
message['Contact'] = contact
etablissement, etablissement_date_entree = get_etablissement(fields, wf)
if etablissement:
message.update({
'indexEtablissementAccueil': etablissement,
'dateInstallBeneficiaire': etablissement_date_entree
})
if beneficiaire_retraite:
message.update({
'Retraite': {
'codeOrganismeRetraite': int(beneficiaire_retraite_code),
'periodicite': 4,
'Nomenclature': {
'indexFamille': 7,
'indexNature': 2
}
}
})
adresse = {
'codeCommune': int(beneficiaire_code_commune),
'codeDepartement': int(beneficiaire_code_departement),
}
if beneficiaire_numero_lieu:
adresse['numeroLieu'] = beneficiaire_numero_lieu
adresse['codeLieu'] = beneficiaire_code_lieu
message['Adresse'] = adresse
return message
def get_conjoint(fields, wf):
conjoint_id = None
if not wf.get('homonymie_conjoint_var_homonyme_new_user'):
conjoint_id = wf.get('homonymie_conjoint_var_homonyme_force_id')
if not conjoint_id:
conjoint_id = wf.get('homonymie_conjoint_var_homonyme_id_raw')
conjoint_civilite = wf.get('supp5_var_civiliteconjoint') or fields['civiliteconjoint'] or ''
conjoint_civilite = conjoint_civilite.strip().upper()
if 'MONSIEUR' in conjoint_civilite:
conjoint_sexe = 'H'
else:
conjoint_sexe = 'F'
conjoint_nom = wf.get('supp5_var_nomconjoint') or fields['nomconjoint'] or ''
conjoint_nom = conjoint_nom.strip().upper()
if conjoint_nom == '':
conjoint_nom = None
conjoint_nomnaissance = wf.get('supp5_var_nomnaissanceconjoint') or fields['nomnaissanceconjoint'] or ''
conjoint_nomnaissance = conjoint_nomnaissance.strip().upper()
if conjoint_nomnaissance == '':
conjoint_nomnaissance = None
conjoint_prenom = wf.get('supp5_var_prenomconjoint') or fields['prenomconjoint'] or ''
conjoint_prenom = conjoint_prenom.strip().upper()
conjoint_dn = wf.get('supp5_var_dnnconjoint') or fields['dnnconjoint'] or ''
conjoint_dn = conjoint_dn[0:10]
conjoint_participation = wf.get('supp5_var_participationconjoint') or fields['participationconjoint'] or 'NON'
conjoint_participation = conjoint_participation.strip().upper()
if 'OUI' in conjoint_participation:
conjoint_participation = 'true'
else:
conjoint_participation = 'false'
if not conjoint_nom:
return None
message = {}
if conjoint_id:
message['indexIndividu'] = conjoint_id
message.update({
'nom': conjoint_nom,
'prenom': conjoint_prenom,
})
if conjoint_nomnaissance:
message['nomJeuneFille'] = conjoint_nomnaissance
message.update({
'dateNaissance': conjoint_dn,
'sexe': conjoint_sexe,
'bParticipeRevenus': conjoint_participation,
'situationFamiliale': beneficiaire_situation
})
return message
def get_revenu(fields, wf):
salaire = wf.get('supp6_var_revenuSalaire') or fields.get('revenuSalaire')
try:
salaire = float(salaire)
except:
salaire = 0.0
retraite = wf.get('supp6_var_revenuRetraite') or fields.get('revenuRetraite')
try:
retraite = float(retraite)
except:
retraite = 0.0
revenus = salaire + retraite
revenus_annee = wf.get('supp6_var_anneerefrevenu') or fields.get('anneerefrevenu')
conjoint_participation = wf.get('supp5_var_participationconjoint') or fields['participationconjoint'] or 'NON'
conjoint_participation = conjoint_participation.strip().upper()
if conjoint_participation == 'true':
salaire = wf.get('supp6_var_revenuSalaireConjoint') or fields.get('revenuSalaireConjoint')
try:
salaire = float(salaire)
except:
salaire = 0.0
retraite = wf.get('supp6_var_revenuRetraiteConjoint') or fields.get('revenuRetraiteConjoint')
try:
retraite = float(retraite)
except:
retraite = 0.0
revenus = revenus + salaire + retraite
if not revenus_annee:
return None
message = {
'anneeReference': int(revenus_annee),
'revenuReference': revenus
}
return message
def get_info_bancaire(fields, wf):
banque_titulaire = wf.get('supp8_var_titulairecompte') or fields.get('titulairecompte')
banque_domiciliation = wf.get('supp8_var_domicilebanque') or fields.get('domicilebanque')
banque_codebanque = wf.get('supp8_var_codebanque') or fields.get('codebanque')
banque_codeguichet = wf.get('supp8_var_codeguichet') or fields.get('codeguichet')
banque_numero = wf.get('supp8_var_numcompte') or fields.get('numcompte')
banque_cle = wf.get('supp8_var_clerib') or fields.get('clerib')
return {
"titulaireCompte": banque_titulaire,
"domiciliation": banque_domiciliation,
"codeBanque": banque_codebanque,
"codeGuichet": banque_codeguichet,
"numeroCompte": banque_numero,
"cleRib": banque_cle,
"modeReglement": 1
}
def get_patrimoine(fields, wf):
try:
immobilier_bati = float(wf.get('supp7_var_bienbatis') or fields.get('bienbatis'))
except:
immobilier_bati = 0.0
try:
immobilier_non_bati = float(wf.get('supp7_var_biennonbatis') or fields.get('biennonbatis'))
except:
immobilier_non_bati = 0.0
try:
prelevements = float(wf.get('supp6_var_revenuPrelevement') or fields.get('revenuPrelevement'))
except:
prelevements = 0.0
try:
prelevements = prelevements + float(wf.get('supp6_var_revenuPrelevementConjoint') or fields.get('revenuPrelevementConjoint'))
except:
pass
try:
fonciers = float(wf.get('supp6_var_revenuFoncier') or fields.get('revenuFoncier'))
except:
fonciers = 0.0
try:
fonciers = fonciers + float(wf.get('supp6_var_revenuFoncierConjoint') or fields.get('revenuFoncierConjoint', 0.0))
except:
pass
fonciers_annee = wf.get('supp7_var_anneefoncier') or fields.get('anneefoncier')
revenus_annee = wf.get('supp6_var_anneerefrevenu') or fields.get('anneerefrevenu')
message = [
{
"Nomenclature": {
"indexFamille": 2,
"indexNature": 1
},
"anneeReference": int(revenus_annee),
"valeurPrelevement": immobilier_bati
},
{
"Nomenclature": {
"indexFamille": 2,
"indexNature": 2
},
"anneeReference": int(revenus_annee),
"valeurPrelevement": immobilier_non_bati
},
{
"Nomenclature": {
"indexFamille": 3,
"indexNature": 1
},
"anneeReference": int(revenus_annee),
"valeurPrelevement": prelevements
}
]
if fonciers > 0 and fonciers_annee is not None:
message.update({
"Nomenclature": {
"indexFamille": 4,
"indexNature": 1
},
"anneeReference": int(fonciers_annee),
"valeurPrelevement": fonciers
})
return message

View File

@ -0,0 +1,34 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0002_auto_20151009_0326'),
]
operations = [
migrations.CreateModel(
name='SolisAPA',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(max_length=50)),
('slug', models.SlugField()),
('description', models.TextField()),
('log_level', models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'NOTSET', b'NOTSET'), (b'DEBUG', b'DEBUG'), (b'INFO', b'INFO'), (b'WARNING', b'WARNING'), (b'ERROR', b'ERROR'), (b'CRITICAL', b'CRITICAL'), (b'FATAL', b'FATAL')])),
('base_url', models.CharField(max_length=128, verbose_name='url')),
('verify_cert', models.BooleanField(default=True, verbose_name='Check HTTPS Certificate validity')),
('username', models.CharField(max_length=128, verbose_name='Username', blank=True)),
('password', models.CharField(max_length=128, verbose_name='Password', blank=True)),
('keystore', models.FileField(help_text='Certificate and private key in PEM format', upload_to=b'solis_apa', null=True, verbose_name='Keystore', blank=True)),
('users', models.ManyToManyField(to='base.ApiUser', blank=True)),
],
options={
'verbose_name': 'Solis',
},
bases=(models.Model,),
),
]

View File

@ -0,0 +1,332 @@
# Passerelle - uniform access to data and services
# Copyright (C) 2015 Entr'ouvert
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
import re
import json
import urlparse
from django.db import models
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponse
from passerelle.base.models import BaseResource
import conciliation, suivi, integration
HEADERS = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
APPLICATION = 'AsgTeleprocedureApa14'
class SolisAPA(BaseResource):
base_url = models.CharField(max_length=128, blank=False,
verbose_name=_('url'))
verify_cert = models.BooleanField(default=True,
verbose_name=_('Check HTTPS Certificate validity'))
username = models.CharField(max_length=128, blank=True,
verbose_name=_('Username'))
password = models.CharField(max_length=128, blank=True,
verbose_name=_('Password'))
keystore = models.FileField(upload_to='solis_apa', null=True, blank=True,
verbose_name=_('Keystore'),
help_text=_('Certificate and private key in PEM format'))
category = _('Business Process Connectors')
class Meta:
verbose_name = _('Solis')
@classmethod
def get_icon_class(cls):
return 'ressources'
@classmethod
def get_verbose_name(cls):
return cls._meta.verbose_name
def get_absolute_url(self):
return reverse('solis-apa-view', kwargs={'slug': self.slug})
@classmethod
def get_add_url(cls):
return reverse('solis-apa-add')
def _check_requests_response(self, response):
try:
ret = response.json()
return ret
except(ValueError) as e:
raise Exception('Response content is not a valid JSON')
def get_resource_url(self, uri):
return urlparse.urljoin(self.base_url,uri)
# Referentials methods
def _referential(self, referential, keys=True, order_by=False,
stop_on_error=False, attributes=[], **filters):
uri = 'referential?referential=%s' % referential
url = self.get_resource_url(uri)
data = {
'ReferentialOptions': {
'processKeys': keys,
'processOrderBy': order_by,
'stopOnError': stop_on_error,
}}
if filters:
solis_filters = []
for k,v in filters.items():
solis_filters.append({
'key':k,
'value': v
})
data['ReferentialOptions']['Filters'] = {'Filter': solis_filters}
if attributes:
data['ReferentialOptions']['Attributes'] = {
"referential": [
{
"schema": "stdr",
"table": referential,
"field": attributes,
}
]
}
data = json.dumps(data)
response = self.requests.post(url, data=data, headers=HEADERS)
if response.status_code != 200:
raise ValueError('referential ws: error code %d' % response.status_code)
ret = self._check_requests_response(response)
l = []
count = int(ret['ReferentialOutputWS']['Entries']['@count'])
name = ret['ReferentialOutputWS']['Entries']['@name']
if count:
entries = ret['ReferentialOutputWS']['Entries']['Entry']
if type(entries) is not list:
entries = [entries]
l += entries
return {'results': l, 'name': name, 'count': count, 'error': False}
def _conciliation(self, config, **data):
uri = 'conciliation'
url = self.get_resource_url(uri)
name = config['block']['name'].lower()
data = json.dumps(conciliation.conciliation_payload(config, **data))
response = self.requests.post(url, data=data, headers=HEADERS)
if response.status_code != 200:
raise ValueError('conciliation ws: error code %d' % response.status_code)
ret = self._check_requests_response(response)
l = []
count = int(ret['ConciliationOutputWS']['Results']['@count'])
if count:
results = ret['ConciliationOutputWS']['Results']['ResultsByAffinity']
if type(results) is not list:
results = [results]
for r in results:
affinity = r['@affinity']
entities = r['Entities']['entity']
if type(entities) is not list:
entities = [entities]
for e in entities:
e = conciliation.conciliation_output2dict(config, e)
e['@affinity'] = affinity
l.append(e)
return {'results': l, 'name': name, 'count': count, 'error': False}
def get_communes(self, query, code_dep=14):
if query:
query = query.lower()
if re.match('^\d\d', query):
# query est le debut d'un code postal
code_dep = query[:2]
if not code_dep:
return {}
cache_key = 'solis-liste-communes-%s' % code_dep
ref = cache.get(cache_key)
if not ref:
ref = self._referential(referential='commune',
attributes=['cp_lieu'],
code_dep=code_dep)
cache.set(cache_key, ref, 60*60)
villes = ref.get('results')
ret = []
for v in villes:
# {u'Attributes': {u'Attribute': {u'id': u'stdr.commune.cp_lieu',
# u'value': 14210}}, u'Keys': {u'Key': [{u'id':
# u'stdr.commune.code_a_com', u'value': 771}, {u'id':
# u'stdr.commune.code_dep', u'value': 14}]}, u'id':
# u'commune-14-771', u'value': u'NEUILLY LE MALHERBE'},
attrs = {}
for attr in v['Attributes']['Attribute']:
attrs[attr['id']] = attr['value']
text = '%0.5d %s' % (attrs['stdr.commune.cp_lieu'], v['value'].strip())
if query and not query in text.lower():
continue
ret.append({'id': v['id'], 'text': text})
return ret
def _cache(self, key, value=None):
if value:
cache.set(key, value, 60*60)
return True
cache_data = cache.get(key)
if cache_data:
return cache_data
def get_lieux(self, q, commune, departement):
# si commune est un code solis de la forme commune-dep-com
if commune and commune.startswith('commune-'):
x, departement, commune = commune.split('-')
call = self._conciliation(conciliation.CONCILIATION_ADRESSE,
commune=commune, departement=departement,
lieu='%%%s%%' % q)
lieux = call.get('results')
ret = []
for l in lieux:
# '@affinity': u'5',
# 'CodeDepartement/@V': u'',
# 'CodeLieu/@V': u'0110',
# 'CodePostal/@V': u'14000',
# 'Commune/NomCom/@V': u'CAEN',
# 'Commune/PK/CodeCommune/@V': u'118',
# 'NatureLieu/@Lc': u'RUE',
# 'NomLieu/@V': u'DU BEAU SITE'
for k,v in l.items():
l[k] = v.strip()
ret.append({
'id': '%(CodeLieu/@V)s' % l,
'text': '%(NatureLieu/@Lc)s %(NomLieu/@V)s' % l,
'affinity': '%(@affinity)s' % l,
})
return ret
def get_homonymes(self, nom, prenom, dn):
if dn:
dn = dn[6:]+'-'+dn[3:5]+'-'+dn[:2]
call = self._conciliation(conciliation.CONCILIATION_INDIVIDU,
nom=nom, prenom=prenom, dn=dn)
else:
call = self._conciliation(conciliation.CONCILIATION_INDIVIDU_SANS_DN,
nom=nom, prenom=prenom)
individus = call.get('results')
ret = []
for i in individus:
# i = {'@affinity': u'3',
# 'Dossier/Adresse/Commune/NomCom/@V': u'ST JULIEN EN GENEVOIS',
# 'Dossier/Adresse/ComplementLieu/@V': u'ROUTE DE THOIRY',
# 'Dossier/Adresse/CpLieu/@V': u'74160',
# 'Dossier/Adresse/NatureLieu/@Lc': u'',
# 'Dossier/Adresse/NomLieu/@V': u'.',
# 'Dossier/Adresse/NumeroLieu/@V': u'39',
# 'Dossier/PK/IndexDossier/@V': u'162438',
# 'EtatCivil/DateNaissance/@V': u'1933-08-28',
# 'EtatCivil/Nom/@V': u'DUPONT',
# 'EtatCivil/NomJeuneFille/@V': u'BUATHIER',
# 'EtatCivil/Prenom/@V': u'JEANNE',
# 'PK/IndexIndividu/@V': u'208359'},
for k,v in i.items():
i[k] = v.strip()
njf = i['EtatCivil/NomJeuneFille/@V']
if njf:
i['EtatCivil/NomJeuneFille/@V'] = u' (%s)' % njf
if not i['EtatCivil/DateNaissance/@V']:
i['EtatCivil/DateNaissance/@V'] = u'date de naissance inconnue'
ret.append({
'id': '%(PK/IndexIndividu/@V)s' % i,
'text': ('%(EtatCivil/Nom/@V)s%(EtatCivil/NomJeuneFille/@V)s %(EtatCivil/Prenom/@V)s' + \
' - %(EtatCivil/DateNaissance/@V)s' + \
' - %(Dossier/Adresse/CpLieu/@V)s %(Dossier/Adresse/Commune/NomCom/@V)s') % i,
'affinity': '%(@affinity)s' % i,
})
ret.sort(lambda x,y: cmp(y['affinity'],x['affinity']))
return ret
def _process_common_ref(self, ref_name):
cache_key = 'solis-apa-%s' %ref_name.replace(' ','-')
ref = self._cache(cache_key)
if not ref:
ref = self._referential(ref_name)
self._cache(cache_key, ref)
ret = []
for result in ref.get('results'):
ret.append({'id': result['id'], 'text': result['value']})
return ret
def get_referential(self, reference_name):
return self._process_common_ref(reference_name.replace('-',' '))
def get_suivi(self, suivi_type, datedebut, datefin):
resource = {
'visite': 'ExportSuiviVisite',
'plan-aide': 'ExportSuiviPlanAide',
'presentation-commission': 'ExportSuiviPresentationCommission',
'decision-commission': 'ExportSuiviDecisionCommission'
}
uri = 'exportFlow?flow={}&application={}'.format(resource[suivi_type],
APPLICATION)
url = self.get_resource_url(uri)
payload = suivi.render_payload(suivi_type, datedebut, datefin)
payload = json.dumps(payload)
response = self.requests.post(url, data=payload, headers=HEADERS)
if response.status_code != 200:
raise ValueError('suivi %s ws: error code %d' %(suivi_type, response.status_code))
response = self._check_requests_response(response)
output = suivi.suivi_output(suivi_type, response)
return output
def import_flow(self, data):
uri = 'importFlow?flow=ImportIntegrationDemande&application=%s' %APPLICATION
url = self.get_resource_url(uri)
data = {'ImportInputWSDemandeApa': integration.build_message(json.loads(data))}
data = json.dumps(data)
self.logger.debug('Demande APA: %s' % data, extra={'solis_apa_demande': data})
response = self.requests.post(url, data=data, headers=HEADERS)
if response.status_code != 200:
raise ValueError('integration ws: error code %d' %(response.status_code))
response = self._check_requests_response(response)
ret = {}
for x in response['ImportIdResults']['Items']:
ret[x['key']] = x['value']
return ret

View File

@ -0,0 +1,178 @@
# Passerelle - uniform access to data and services
# Copyright (C) 2015 Entr'ouvert
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
import json
import datetime
PAYLOAD = {
"visite": {
},
"plan-aide": {
"DemandeAsg": {
"DateDebut": "%(datedebut)s",
"DateFin":"%(datefin)s"
}
},
"presentation-commission": {
"OrdreJourAsg": {
"DateDebut": "%(datedebut)s",
"DateFin":"%(datefin)s"
}
},
"decision-commission": {
"DemandeAsg": {
"EtatDecision": "R",
"DateDebutNotification": "%(datedebut)s",
"DateFinNotification":"%(datefin)s",
"DateDebutDecision": "%(datedebut)s",
"DateFinDecision":"%(datefin)s"
}
}
}
def get_dates(datedebut, datefin):
if datedebut:
datedebut = datedebut[0][:10]
else:
datedebut = (datetime.datetime.now() -
datetime.timedelta(180)).strftime('%Y-%m-%d')
if datefin:
datefin = datefin[0][:10]
else:
datefin = (datetime.datetime.now() +
datetime.timedelta(180)).strftime('%Y-%m-%d')
return datedebut, datefin
def render_payload(suivi_type, datedebut, datefin):
datedebut, datefin = get_dates(datedebut, datefin)
payload = json.dumps(PAYLOAD[suivi_type]) %{
'datedebut': datedebut, 'datefin': datefin}
return json.loads(payload)
def suivi_output(suivi_type, data):
suivi_type = suivi_type.replace('-','_')
return globals().get('suivi_%s_output' %suivi_type)(data)
def suivi_visite_output(data):
results = []
visites = data.get('VisiteAsgs')
if visites:
visites = visites.get('VisiteAsg')
if visites:
if not isinstance(visites, list):
visites = [visites]
for visite in visites:
info = {}
info['visite_date'] = visite['Rencontre']['Date']['@V']
info['visite_heure'] = visite['Rencontre']['Heure']['@V']
participants = visite.get('Participants', {})
intervenants = []
if isinstance(participants, dict):
_intervenants = participants.get('ListeIntervenants', {}).get('Intervenant', [])
if not isinstance(_intervenants, list):
_intervenants = [_intervenants]
for _intervenant in _intervenants:
intervenant = {}
intervenant['id'] = _intervenant['PK']['IndexIntervenantSocial']['@V']
intervenant['nom'] = _intervenant['Nom']['@V']
intervenant['prenom'] = _intervenant['Prenom']['@V']
coords = _intervenant.get('Coordonnees',{})
intervenant['email'] = coords.get('Email',{}).get('@V',u'')
intervenant['telephone'] = coords.get('Telephone',{}).get('@V',u'')
intervenants.append(intervenant)
info['visite_intervenants'] = intervenants
select = {}
select['integration_response_data_indexDemande'] = \
visite['VisiteDemandeAsg']['PK']['Index']['@V']
#select['integration_response_data_indexBeneficiaire'] = \
# visite['VisiteDemandeAsg']['BeneficiaireAsgDemande']['IndividuBeneficiaire']['PK']['IndexIndividu']['@V']
results.append({
'data': info,
'select': select,
# 'debug': visite
})
return results
def suivi_decision_commission_output(data):
results = []
dems = data.get('DemandeAsgs')
if dems:
dems = dems.get('DemandeAsg')
if dems:
if not isinstance(dems, list):
dems = [dems]
for dem in dems:
info = {}
suivi = dem.get('Suivi', {})
info['decision_v'] = suivi.get('Decision', {}).get('@I', '')
info['decision_v_long'] = suivi.get('Decision', {}).get('@Lc', '')
info['decision_commentairenotification'] = suivi.get('CommentaireNotification', {}).get('@V', '')
info['decision_datenotification'] = (suivi.get('DateNotification') or {}).get('@V', '')
info['decision_datedecision'] = (suivi.get('DateDecision') or {}).get('@V', '')
#if not info['decision_datenotification'] or info['decision_v'] not in ('A', 'R'):
# continue
select = {}
select['integration_response_data_indexDemande'] = \
dem['PK']['Index']['@V']
results.append({
'data': info,
'select': select,
#'debug': dem
})
return results
def suivi_plan_aide_output(data):
results = []
return results
def suivi_presentation_commission_output(data):
results = []
odjs = data.get('OrdreJourAsgs')
if odjs:
odjs = odjs.get('OrdreJourAsg')
if odjs:
if not isinstance(odjs, list):
odjs = [odjs]
for odj in odjs:
info = {}
info['presentation_dateseance'] = odj['DateSeance']['@V']
select = {}
select['integration_response_data_indexDemande'] = \
odj['OrdreJourAsgDemandeAsg']['PK']['Index']['@V']
#select['integration_response_data_indexBeneficiaire'] = \
# odj['OrdreJourAsgDemandeAsg']['BeneficiaireAsgDemande']['IndividuBeneficiaire']['PK']['IndexIndividu']['@V']
results.append({
'data': info,
'select': select,
# 'debug': odj
})
return results

View File

@ -0,0 +1,97 @@
{% extends "passerelle/manage.html" %}
{% load i18n passerelle %}
{% block more-user-links %}
{{ block.super }}
{% if object.id %}
<a href="{% url 'solis-apa-view' slug=object.slug %}">{{ object.title }}</a>
{% endif %}
{% endblock %}
{% block appbar %}
<h2>SolisAPA - {{ object.title }}</h2>
{% if perms.passerelle_solis_apa.change_passerelle_solis_apa %}
<a rel="popup" class="button" href="{% url 'solis-apa-edit' slug=object.slug %}">{% trans 'edit' %}</a>
{% endif %}
{% if perms.passerelle_solis_apa.delete_passerelle_solis_apa %}
<a rel="popup" class="button" href="{% url 'solis-apa-delete' slug=object.slug %}">{% trans 'delete' %}</a>
{% endif %}
{% endblock %}
{% block content %}
<div>
<h3>{% trans 'Endpoints' %}</h3>
<ul>
<li>
{%url 'solis-apa-integration' slug=object.slug as integration %}
<strong>POST</strong> - {%trans 'Import Demand'%} <a href="{{integration}}">{{site_base_uri}}{{integration}}</a>
</li>
<li>
<h4>{%trans 'Referential'%}</h4>
<ul>
<li>
{%url 'solis-apa-communes' slug=object.slug as get_communes %}
<strong>GET</strong> - {%trans 'Communes:' %} <a href="{{get_communes}}">{{ site_base_uri }}{{get_communes}}?q=14600&code_dep=14</a> [?q=query&code_dep=code_dep]
</li>
<li>
{%url 'solis-apa-lieux' slug=object.slug as get_lieux %}
<strong>GET</strong> - {%trans 'Lieux:' %} <a href="{{get_lieux}}">{{ site_base_uri }}{{get_lieux}}?commune=commune-14-753&q=LES</a> [?commune=code_commune&q=query]
</li>
<li>
{%url 'solis-apa-homonymes' slug=object.slug as get_homonymes %}
<strong>GET</strong> - {%trans 'Homonymes:' %} <a href="{{get_homonymes}}">{{ site_base_uri }}{{get_homonymes}}?nom=dupont&prenom=thomas</a> [?nom=nom&prenom=prenom&dn=dn]
</li>
<li>
{%url 'solis-apa-referential' slug=object.slug reference_name='caisse-de-retraite' as get_caisse_retraite%}
<strong>GET</strong> - {%trans 'Caisses de retraite'%} <a href="{{get_caisse_retraite}}"> {{site_base_uri}}{{get_caisse_retraite}}</a>
</li>
<li>
{%url 'solis-apa-referential' reference_name='organisme-de-tutelle' slug=object.slug as get_organisme_tutelle%}
<strong>GET</strong> - {%trans 'Organimes de tutelle'%} <a href="{{get_organisme_tutelle}}"> {{site_base_uri}}{{get_organisme_tutelle}}</a>
</li>
<li>
{%url 'solis-apa-referential' reference_name='etablissement-asg' slug=object.slug as get_etablissement%}
<strong>GET</strong> - {%trans 'Etablissement'%} <a href="{{get_etablissement}}"> {{site_base_uri}}{{get_etablissement}}</a>
</li>
</ul>
</li>
<li>
<h4>{%trans 'Suivi' %} </h4>
<ul>
<li>
{%url 'solis-apa-suivi' suivi_type='visite' slug=object.slug as suivi_visite%}
<strong>GET</strong> - {%trans 'Visite'%} <a href="{{suivi_visite}}">{{site_base_uri}}{{suivi_visite}}</a> [?datedebut=2015-11-04&datefin=2016-10-29]
</li>
<li>
{%url 'solis-apa-suivi' suivi_type='plan-aide' slug=object.slug as suivi_plan_aide%}
<strong>GET</strong> - {%trans 'Plan d aide '%} <a href="{{suivi_plan_aide}}">{{site_base_uri}}{{suivi_plan_aide}}</a> [?datedebut=2015-11-04&datefin=2016-10-29]
</li>
<li>
{%url 'solis-apa-suivi' suivi_type='presentation-commission' slug=object.slug as suivi_presentation_commission%}
<strong>GET</strong> - {%trans 'Presentation Commission'%} <a href="{{suivi_presentation_commission}}">{{site_base_uri}}{{suivi_presentation_commission}}</a> [?datedebut=2015-11-04&datefin=2016-10-29]
</li>
<li>
{%url 'solis-apa-suivi' suivi_type='decision-commission' slug=object.slug as suivi_decision_commission%}
<strong>GET</strong> - {%trans 'Decision Commission'%} <a href="{{suivi_decision_commission}}">{{site_base_uri}}{{suivi_decision_commission}}</a> [?datedebut=2015-11-04&datefin=2016-10-29]
</li>
</ul>
</li>
</ul>
</div>
{% if perms.base.view_accessright %}
<div>
<h3>{% trans "Security" %}</h3>
<p>
{% trans 'Access is limited to the following API users:' %}
</p>
{% access_rights_table resource=object permission='can_access' %}
{% endif %}
</div>
{% endblock %}

View File

@ -0,0 +1,56 @@
# Passerelle - uniform access to data and services
# Copyright (C) 2015 Entr'ouvert
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls import patterns, include, url
from passerelle.urls_utils import decorated_includes, required, app_enabled
from django.contrib.auth.decorators import login_required
from .views import *
public_urlpatterns = patterns('',
url(r'^(?P<slug>[\w,-]+)/$', SolisAPADetailView.as_view(),
name='solis-apa-view'),
url(r'^(?P<slug>[\w,-]+)/communes/$', CommunesView.as_view(),
name='solis-apa-communes'),
url(r'^(?P<slug>[\w,-]+)/lieux/$', LieuxView.as_view(),
name='solis-apa-lieux'),
url(r'^(?P<slug>[\w,-]+)/homonymes/$', HomonymesView.as_view(),
name='solis-apa-homonymes'),
url(r'^(?P<slug>[\w,-]+)/referential/(?P<reference_name>[\w,-]+)/$',
ReferentialView.as_view(), name='solis-apa-referential'),
url(r'^(?P<slug>[\w,-]+)/suivi/(?P<suivi_type>[\w,-]+)/$',
SuiviView.as_view(), name='solis-apa-suivi'),
url(r'^(?P<slug>[\w,-]+)/integration/$', IntegrationView.as_view(),
name='solis-apa-integration')
)
management_urlpatterns = patterns('',
url(r'^add$', SolisAPACreateView.as_view(),
name='solis-apa-add'),
url(r'^(?P<slug>[\w,-]+)/edit$', SolisAPAUpdateView.as_view(),
name='solis-apa-edit'),
url(r'^(?P<slug>[\w,-]+)/delete$', SolisAPADeleteView.as_view(),
name='solis-apa-delete'),
)
urlpatterns = required(
app_enabled('solis_apa'),
patterns('',
url(r'^solis-apa/', include(public_urlpatterns)),
url(r'^manage/solis-apa/',
decorated_includes(login_required, include(management_urlpatterns))),
)
)

View File

@ -0,0 +1,135 @@
# Passerelle - uniform access to data and services
# Copyright (C) 2015 Entr'ouvert
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
from django.core.urlresolvers import reverse
from django.views.generic import DetailView as GenericDetailView, View
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.detail import SingleObjectMixin
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.utils.translation import ugettext_lazy as _
from passerelle import utils
from .models import SolisAPA
from .forms import SolisAPAForm, SolisAPAUpdateForm
class CommissionTypeNotFound(Exception):
http_status = 404
class SolisAPADetailView(GenericDetailView):
model = SolisAPA
template_name = 'passerelle/contrib/solis_apa/detail.html'
class SolisAPACreateView(CreateView):
model = SolisAPA
form_class = SolisAPAForm
template_name = 'passerelle/manage/service_form.html'
class SolisAPAUpdateView(UpdateView):
model = SolisAPA
form_class = SolisAPAUpdateForm
template_name = 'passerelle/manage/service_form.html'
class SolisAPADeleteView(DeleteView):
model = SolisAPA
template_name = 'passerelle/manage/service_confirm_delete.html'
def get_success_url(self):
return reverse('manage-home')
class DetailView(GenericDetailView):
model = SolisAPA
def get_data(self, request, *args, **kwargs):
raise NotImplementedError
@utils.protected_api('can_access')
@utils.to_json('api')
def get(self, request, *args, **kwargs):
return self.get_data(request, *args, **kwargs)
def _get_params(self, request, *params):
return [ request.GET.get(item, None) for item in params]
class CommunesView(DetailView):
def get_data(self, request, *args, **kwargs):
params = self._get_params(request, 'q', 'code_dep')
return self.get_object().get_communes(*params)
class LieuxView(DetailView):
def get_data(self, request, *args, **kwargs):
params = self._get_params(request, 'q', 'commune', 'departement')
return self.get_object().get_lieux(*params)
class HomonymesView(DetailView):
def get_data(self, request, *args, **kwargs):
params = self._get_params(request, 'nom', 'prenom', 'dn')
return self.get_object().get_homonymes(*params)
class CaisseDeRetraiteView(DetailView):
def get_data(self, request, *args, **kwargs):
return self.get_object().get_caisse_retraite()
class OrganismeDeTutelleView(DetailView):
def get_data(self, request, *args, **kwargs):
return self.get_object().get_organisme_tutelle()
class EtablissementView(DetailView):
def get_data(self, request, *args, **kwargs):
return self.get_object().get_etablissement()
class ReferentialView(DetailView):
def get_data(self, request, *args, **kwargs):
reference_name = kwargs['reference_name']
return self.get_object().get_referential(reference_name)
class SuiviView(DetailView):
def get_data(self, request, *args, **kwargs):
suivi_type = kwargs['suivi_type']
if suivi_type not in ('visite','plan-aide',
'presentation-commission','decision-commission'):
raise CommissionTypeNotFound(_('Unknown suivi type'))
params = self._get_params(request, 'datedebut', 'datefin')
return self.get_object().get_suivi(suivi_type, *params)
class IntegrationView(View, SingleObjectMixin):
model = SolisAPA
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(IntegrationView, self).dispatch(request, *args, **kwargs)
@utils.protected_api('can_access')
@utils.to_json('api')
def post(self, request, *args, **kwargs):
data = request.body
return self.get_object().import_flow(data)