remove vieux fichiers

darcs-hash:20070215153024-f46e9-3a40e2e74f6ab55e6297b3151795d84c628fefba.gz
This commit is contained in:
gdetrez 2007-02-15 16:30:24 +01:00
parent 5b31412e1e
commit 69cbf31bb0
7 changed files with 0 additions and 1131 deletions

View file

@ -1,73 +0,0 @@
#! /usr/bin/env python
import cherrypy, tempfile, shutil, os
import crans.impression
import crans.impression.digicode
import crans.cp
class root:
##########################
# affichage
##########################
#
# methode qui affiche la template
#
def index(self, submit = None, fileList = None, newFile = None ):
return {'template':'digicode',
'values':{},
'stylesheets':['digicode.css'],
'scripts':['digicode.js', 'popup.js'],
}
index.exposed = True
##########################
# AJAX
##########################
#
# methode qui renvoie la liste des codes
#
def codeList(self):
try:
listeBrute = crans.impression.digicode.list_code()
liste_formatee = []
for aCode in listeBrute:
age = aCode[1]
age_jours = (age/3600)/24
age_heures = (age/3600) - age_jours*24
age_minutes = (age/60) - (age/3600)*60
if age_jours > 0:
age_string = "%sj %sh %smin" % (str(age_jours), str(age_heures), str( age_minutes ))
elif age_heures > 0:
age_string = "%sh %smin" % (str(age_heures), str( age_minutes ))
else:
age_string = "%smin" % (str( age_minutes ))
liste_formatee.append({'code':aCode[0], 'age':age_string, 'desc':aCode[2]})
return {'codes': liste_formatee}
except Exception, e:
crans.cp.log('erreur lors de la creation de la liste de codes :' + str(e), 'DIGICODE', 1)
return {'erreur':str(e)}
codeList.exposed= True
#
# methode qui cree un code
#
def createCode(self, code=None, adherent=''):
try:
if adherent == '':
adherent = cherrypy.session['uid']
if code:
try:
int(code)
if code.__len__() != 6:
raise
except:
return {'formatErreur':1}
code = crans.impression.digicode.save_code(code, adherent)
else:
code = crans.impression.digicode.gen_code(adherent)
crans.cp.log("code cree : %s" % code, 'DIGICODE')
return {'code': code, "age" : "new", "desc":adherent}
except Exception, e:
crans.cp.log("erreur lors de la creation de code : " + str(e), 'DIGICODE', 1)
return {'erreur':str(e)}
createCode.exposed= True

View file

@ -1,93 +0,0 @@
#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
# ##################################################################################################### #
# Factures
# ##################################################################################################### #
# Description:
# Affiche la liste des factures et l'historique de débits/crédits de l'adhérent.
# Informations:
#
# Pages:
# index:liste des factures
# historique: historique des débits/crédits
#
# ##################################################################################################### #
import cherrypy, sys, os, datetime
class root:
def index(self, message = '', error = ''):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
t = {}
t['message'] = message
t['error'] = error
############## liste des factures ##############
listeFactures = []
for f in adh.factures():
facture = {}
facture['no'] = f.numero()
facture['intitule'] = f.articles()[0]['designation']
facture['details'] = [
{
'intitule':art['designation'],
'quantite':art['nombre'],
'prixUnitaire':art['pu'],
'prixTotal':art['pu']*art['nombre'],
} for art in f.articles()]
facture['montant'] = f.total()
facture['paypal'] = f.urlPaypal(useSandbox = cherrypy.config.get("paypal.useSandbox", False),
businessMail = cherrypy.config.get("paypal.businessAdress", "paypal@crans.org"),
return_page = "https://intranet.crans.org/monCompte/paypalReturn",
cancel_return_page = "https://intranet.crans.org/monCompte/paypalCancel",
)
facture['payee'] = f.recuPaiement()
listeFactures.append(facture)
t['listeFactures'] = listeFactures
return {
'template' :'factures',
'values' :t,
'stylesheets' :['cransFactures.css'],
'scripts' :[],
}
index.exposed = True
def historique(self):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
lst = [ x for x in adh.historique() if x.split(u' : ',1)[1].startswith(u'credit') or x.split(u' : ',1)[1].startswith(u'debit') ]
histLst = []
for anItem in lst:
aLine = {}
aLine["date"] = anItem.split(u",")[0]
aLine["type"] = anItem.split(u' : ',2)[1].split(u' ')[0]
aLine["montant"] = anItem.split(u' : ',2)[1].split(u' ')[1]
try:
aLine["intitule"] = anItem.split(u'[')[1].split(u']')[0]
except Exception:
aLine["intitule"] = ""
histLst.append(aLine)
return {
'template' :'factures-historique',
'values' :{'liste':lst, 'historic_items':histLst},
'stylesheets' :['cransFactures.css'],
'scripts' :[],
}
historique.exposed = True
def delFacture(self, no):
try:
# trrouver la factures
fact = cherrypy.session['LDAP'].search('fid=' + no, 'w')['facture'][0]
#verifier qu'elle appartient bien a l'adherent
if not fact.proprietaire().mail() == cherrypy.session['uid']:
raise Exception, "Impossible de supprimer cette facture"
# la supprimer
fact.delete()
except Exception, e:
cherrypy.log(str(e), "FACTURES", 1)
return self.index()
delFacture.exposed = True

View file

@ -1,134 +0,0 @@
#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
# ##################################################################################################### #
# Factures (gestion)
# ##################################################################################################### #
# Description:
# Permet de chercher dans les facture, d'en créditer et d'en supprimer
# Informations:
#
# Pages:
# index:afiche le formulaire et les factures
#
# ##################################################################################################### #
import cherrypy, sys, os, datetime
import crans.cp
class root:
def index(self, message = '', erreur = ''):
if cherrypy.session.has_key('gestion_factures-current_search'):
del cherrypy.session['gestion_factures-current_search']
return self.displayTemplate()
index.exposed = True
def search(self, fid=None, uid=None, aid=None):
cherrypy.session['gestion_factures-current_search'] = {
"fid":fid,
"uid":uid,
"aid":aid,
}
return self.displayTemplate()
search.exposed = True
def displayTemplate(self, message = '', erreur = ''):
t = {}
t['message'] = message
t['error'] = erreur
if cherrypy.session.has_key('gestion_factures-current_search'):
fid = cherrypy.session['gestion_factures-current_search']['fid']
uid = cherrypy.session['gestion_factures-current_search']['uid']
aid = cherrypy.session['gestion_factures-current_search']['aid']
t['listeFactures'] = self.buildInvoiceList(
fid = fid,
uid = uid,
aid = aid,
)
else:
fid = ""
uid = ""
aid = ""
t["form"] = []
t["form"]+= [{'name':'fid', 'label':'fid', 'value':fid}]
t["form"]+= [{'name':'uid', 'label':'login', 'value':uid}]
t["form"]+= [{'name':'aid', 'label':'aid', 'value':aid}]
return {
'template' :'factures-gestion',
'values' :t,
'stylesheets' :['cransFactures.css'],
}
def buildInvoiceList(self, fid=None, uid=None, aid=None):
############## liste des factures ##############
if fid:
search_string = "fid=%s" % str(fid)
liste_factures_ldap = cherrypy.session['LDAP'].search(search_string)['facture']
elif uid:
search_string = "uid=%s" % str(uid)
try:
liste_factures_ldap = cherrypy.session['LDAP'].search(search_string)['adherent'][0].factures()
except:
liste_factures_ldap = []
elif aid:
search_string = "aid=%s" % str(aid)
try:
liste_factures_ldap = cherrypy.session['LDAP'].search(search_string)['adherent'][0].factures()
except:
liste_factures_ldap = []
else:
return []
liste_factures_affichees = []
for f in liste_factures_ldap:
try:
facture = {}
facture['no'] = f.numero()
facture['adherent'] = f.proprietaire().mail()
facture['montant'] = f.total()
facture['payee'] = f.recuPaiement()
facture['intitule'] = f.articles()[0]['designation']
facture['details'] = [
{
'intitule':art['designation'],
'quantite':art['nombre'],
'prixUnitaire':art['pu'],
'prixTotal':art['pu']*art['nombre'],
} for art in f.articles()]
liste_factures_affichees.append(facture)
except:
crans.cp.log("Facture non affichable : fid=%s" % str(f.numero()), "GESTION FACTURES", 1)
return liste_factures_affichees
def delFacture(self, fid):
try:
# trrouver la factures
fact = cherrypy.session['LDAP'].search('fid=' + fid, 'w')['facture'][0]
# la supprimer
fact.delete()
except Exception, e:
crans.cp.log(unicode(e), "GESTION FACTURES", 1)
return self.index(erreur=u"Probleme lors de la suppression")
crans.cp.log(u"Facture supprimee [fid=%s]" % fid, "GESTION FACTURES")
return self.displayTemplate(message=u"Facture suprimée")
delFacture.exposed = True
def crediteFacture(self, fid):
try:
# trrouver la factures
fact = cherrypy.session['LDAP'].search('fid=' + fid, 'w')['facture'][0]
# la supprimer
fact.recuPaiement(cherrypy.session['uid'])
fact.save()
except Exception, e:
crans.cp.log("pb crédit", "GESTION FACTURES", 1)
return self.index(erreur=u"Problème lors du crédit")
crans.cp.log("Facture creditee [fid=%s]" % fid, "GESTION FACTURES")
return self.displayTemplate(message=u"Facture créditée")
crediteFacture.exposed = True

View file

@ -1,230 +0,0 @@
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# #############################################################
# ..
# .... ............ ........
# . ....... . .... ..
# . ... .. .. .. .. ..... . ..
# .. .. ....@@@. .. . ........ .
# .. . .. ..@.@@..@@. .@@@@@@@ @@@@@@. ....
# .@@@@. .@@@@. .@@@@..@@.@@..@@@..@@@..@@@@.... ....
# @@@@... .@@@.. @@ @@ .@..@@..@@...@@@. .@@@@@. ..
# .@@@.. . @@@. @@.@@..@@.@@..@@@ @@ .@@@@@@.. .....
# ...@@@.... @@@ .@@.......... ........ ..... ..
# . ..@@@@.. . .@@@@. .. ....... . .............
# . .. .... .. .. . ... ....
# . . .... ............. .. ...
# .. .. ... ........ ... ...
# ................................
#
# #############################################################
# impression.py
#
# interface d'impression
#
# Copyright (c) 2006 by www.crans.org
# #############################################################
import cherrypy, tempfile, shutil, os
import crans.impression
import crans.impression.digicode
import crans.impression.etat_imprimante
import crans.cp
FILE_UPLOAD_BASE_FOLDER = cherrypy.config.get('fileUpload.folder', "/var/impression/fichiers/")
class FileError(Exception):
pass
class root:
##########################
# affichage
##########################
#
# template principale
#
def index(self, submit = None, fileList = None, newFile = None ):
data = {}
# on efface un eventuel objet impression existant
cherrypy.session['impression'] = None
if submit == "Envoyer":
try:
self.savePDF(newFile)
data['fileName'] = newFile.filename
except FileError, e:
data['openError'] = e.args[0]
elif submit == "Choisir":
if (fileList):
data['fileName'] = fileList
else:
data['openError'] = "Choisissez un fichier"
data['fileList'] = self.getUploadedFileListFor(cherrypy.session['uid'])
try:
crans.impression.etat_imprimante.etat()
except Exception, e:
data['Erreur_imprimante'] = str(e).replace("\"", "\\\"")
data['errorMsg'] = u"Imprimante injoignable"
if not cherrypy.config.get('crans.activate', True):
data['Erreur_imprimante'] = "Config impression"
data['errorMsg'] = cherrypy.config.get('crans.activate.errorMsg', u"Imprimante HS")
return {'template':'impression',
'values':data,
'stylesheets':['impression.css'],
'scripts':['impression.js', 'popup.js'],
}
index.exposed = True
##########################
# devis
##########################
#
# methode qui affiche la template du devis
#
def devis(self):
return {
'template':'impression-devis',
'values':
{
'devis':cherrypy.session['impression'].devisDetaille(),
'total':cherrypy.session['impression'].prix(),
'nomFichier':cherrypy.session['impression'].fileName(),
},
'standalone':True,
}
devis.exposed=True
##########################
# AJAX
##########################
#
# methode qui renvoie la liste des codes de l'adherent
#
def codeList(self):
try:
listeBrute = crans.impression.digicode.list_code()
# liste de la forme :
# [(code, age, description),...]
listeBrute = [item[0] for item in listeBrute if item[2] == cherrypy.session['uid']]
return {'codes': listeBrute}
except Exception, e:
crans.cp.log('erreur lors de la creation de la liste de codes :' + str(e), 'IMPRESSION', 1)
return {'erreur':str(e)}
codeList.exposed= True
#
# methode qui indique quel fichier utiliser
#
def useFile(self, fileName):
try:
filepath = os.path.join(os.path.join(FILE_UPLOAD_BASE_FOLDER, cherrypy.session['uid']+"/"), fileName)
cherrypy.session['impression'] = crans.impression.impression(filepath, cherrypy.session['uid'])
return {'nbPages': cherrypy.session['impression'].pages()}
except crans.impression.FichierInvalide, e:
crans.cp.log("useFile : %s (%s)" % (str(e), e.file()), 'IMPRESSION', 1)
return {'erreur':str(e) }
except Exception, e:
crans.cp.log("useFile : %s" % str(e), 'IMPRESSION', 1)
return {'erreur':str(e) }
useFile.exposed= True
#
# methode pour changer les parametres
#
def changeSettings(self, copies=None, couleurs=None, recto_verso=None, agrafes=None, papier=None):
try:
nouvPrix = cherrypy.session['impression'].changeSettings(papier=papier, couleurs=couleurs, agraphes=agrafes, recto_verso=recto_verso, copies=int(copies))
except Exception, e:
crans.cp.log("changeSettings : %s" % str(e), 'IMPRESSION', 1)
return {"erreur":str(e)}
return {'nouvPrix':nouvPrix}
changeSettings.exposed = True
#
# methode pour lancer l'impression
#
def lancerImpression(self):
try:
cherrypy.session['impression'].imprime()
except crans.impression.SoldeInsuffisant:
return {"SoldeInsuffisant":1}
except Exception, e:
crans.cp.log("lancerImpression : %s" % str(e), 'IMPRESSION', 1)
return {"erreur":str(e)}
crans.cp.log("impression", 'IMPRESSION')
return {'code':str(crans.impression.digicode.gen_code(cherrypy.session['uid'])) + "#"}
lancerImpression.exposed = True
#
# methode pour recuperer l'etat de l'imprimante
#
def etatImprimante(self):
if not cherrypy.config.get('crans.activate', True):
return {"printer_state" : u"Système down"}
try:
return {"printer_state" : u"\\n".join(crans.impression.etat_imprimante.etat())}
except Exception, e:
return {"printer_state" : 'Imprimante hors ligne'}
etatImprimante.exposed = True
#
# methode pour le solde
#
def AJAXGetSolde(self):
try:
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
return {"solde" : adh.solde() }
except Exception, e:
return {"erreur" : str(e)}
AJAXGetSolde.exposed = True
##########################
# privees
##########################
#
# methode pour obtenir la liste des fichiers uploadés
#
def getUploadedFileListFor(self, adh):
file_folder = os.path.join(FILE_UPLOAD_BASE_FOLDER, cherrypy.session['uid']+"/")
if not os.path.isdir(file_folder):
return []
return os.listdir(file_folder)
#
# methode pour enregistrer un fichier
#
def savePDF(self, aFile):
_, tempFileName = tempfile.mkstemp()
f = open(tempFileName, 'w+b')
size=0
while True:
data = aFile.file.read(1024 * 8) # Read blocks of 8KB at a time
if not data:
break
f.write(data)
size += len(data)
f.close()
if size == 0:
raise FileError("Fichier vide")
file_folder = os.path.join(FILE_UPLOAD_BASE_FOLDER, cherrypy.session['uid']+"/")
if not os.path.isdir(file_folder):
os.makedirs(file_folder)
newFilePath = os.path.join(file_folder, aFile.filename)
shutil.move(tempFileName, newFilePath)
crans.cp.log("New file uploaded at : %s" % newFilePath, "IMPRESSION")
return newFilePath

View file

@ -1,245 +0,0 @@
#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
# ##################################################################################################### #
# Machines
# ##################################################################################################### #
# Description:
# Affiche la liste des machies, les infons sur une machine et permet des modifications
# Informations:
#
# Pages:
# index:liste des machines + le reste (AJAX)
#
# ##################################################################################################### #
import cherrypy, sys, os, datetime
from time import strftime, localtime, time
# libraries crans
sys.path.append('/usr/scripts/gestion/')
import crans.cp
if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
from ldap_crans_test import *
# print("mesmachines : unsing test ldap : env=" + cherrypy.config.configMap["global"]["server.environment"])
else:
from ldap_crans import *
# print("mesmachines : unsing prod ldap : env=" + cherrypy.config.configMap["global"]["server.environment"])
class root:
def AJAXListeMachines(self):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
machines = []
for une_machine in adh.machines():
machineInfos = {}
# nom, mac, mid, ip
machineInfos['nom'] = une_machine.nom()
machineInfos['nomCourt'] = une_machine.nom().split('.',1)[0]
machineInfos['mid'] = une_machine.id()
# type
if une_machine.objectClass == 'machineFixe':
machineInfos['type'] = 'fixe'
#machineInfos['type'] = 'Machine fixe'
else:
machineInfos['type'] = 'wifi'
#machineInfos['type'] = 'Machine wifi'
# clef ipsec
machines.append(machineInfos)
return {"machines":machines}
AJAXListeMachines.exposed = True
def AJAXMachineInfo(self, mid):
try:
machine = cherrypy.session['LDAP'].search('mid=' + mid)['machine'][0]
if machine.proprietaire().mail() != cherrypy.session['uid']:
raise Exception
# zamok -> pour tester l'affichage des ports, des alias
#machine = cherrypy.session['LDAP'].search('mid=896')['machine'][0]
machineInfos = {}
# nom, mac, mid, ip
machineInfos['nom'] = machine.nom()
machineInfos['nomCourt'] = machine.nom().split('.',1)[0]
machineInfos['mac'] = machine.mac()
machineInfos['mid'] = machine.id()
machineInfos['ip'] = machine.ip()
# type
if machine.objectClass == 'machineFixe':
machineInfos['type'] = 'fixe'
else:
machineInfos['type'] = 'wifi'
# clef ipsec
try:
machineInfos['ipsec'] = machine.ipsec()
except:
machineInfos['ipsec'] = ''
# alias
machineInfos['alias'] = machine.alias()
# blacklists
machineInfos['blacklist'] = []
for blacklist_type in machine.blacklist_all()[0].keys():
for (begin, end) in machine.blacklist_all()[0][blacklist_type]:
blacklist = {}
blacklist['begin'] = strftime('%d/%m/%Y %H:%M', localtime(int(begin)))
blacklist['end'] = strftime('%d/%m/%Y %H:%M', localtime(int(end)))
blacklist['type'] = blacklist_type
blacklist['actif'] = 1
machineInfos['blacklist'].append(blacklist)
for blacklist_type in machine.blacklist_all()[1].keys():
for (begin, end) in machine.blacklist_all()[1][blacklist_type]:
blacklist = {}
blacklist['begin'] = strftime('%d/%m/%Y %H:%M', localtime(int(begin)))
blacklist['end'] = strftime('%d/%m/%Y %H:%M', localtime(int(end)))
blacklist['type'] = blacklist_type
blacklist['actif'] = 0
machineInfos['blacklist'].append(blacklist)
# ports
machineInfos['ports'] = []
if machine.portTCPin() != []:
machineInfos['ports'].append(
{
'titre':'Ports TCP ouvert ext->machine',
'ports':machine.portTCPin()
}
)
if machine.portTCPout() != []:
machineInfos['ports'].append(
{
'titre':'Ports TCP ouvert machine->ext',
'ports':machine.portTCPout()
}
)
if machine.portUDPin() != []:
machineInfos['ports'].append(
{
'titre':'Ports UDP ouvert ext->machine',
'ports':machine.portUDPin()
}
)
if machine.portUDPout() != []:
machineInfos['ports'].append(
{
'titre':'Ports TCP ouvert machine->ext',
'ports':machine.portUDPout()
}
)
return machineInfos
except Exception, e:
return {"erreur":str(e)}
AJAXMachineInfo.exposed = True
##########################
# affichage
##########################
#
# methode qui affiche la template
#
def index(self):
return {
'template' :'machines',
'values' :{},
'stylesheets' :['machines.css'],
'scripts':['machines.js'],
}
index.exposed = True
###########################################################################
# methodes pour changer
# des valeurs
###########################################################################
#
##########################
# machine:nom
##########################
def AJAXChangerNom(self, mid, nouveauNom):
try:
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
mach = cherrypy.session['LDAP'].search('mid=' + mid, 'w')['machine'][0]
# tester si c'est bien la machine de l'adherent
if mach.proprietaire().compte() != cherrypy.session['uid']:
del adh, mach
raise Exception(u"L'uid de l'adherent ne correspond mas au proprietaire de la machine.")
anciennom = mach.nom()
nouveauNom = mach.nom(nouveauNom)
mach.save()
del mach
except ValueError, e:
raise e
#return {'error':str(e)}
crans.cp.log("Changer nom machine : %s->%s" % (anciennom, nouveauNom), "MESMACHINES")
return {'message':u"Modification réussie", 'mid':mid}
AJAXChangerNom.exposed = True
##########################
# machine:mac
##########################
def AJAXchangerMAC(self, mid, nouvelleMAC):
try:
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
mach = cherrypy.session['LDAP'].search('mid=' + mid, 'w')['machine'][0]
# tester si c'est bien la machine de l'adherent
if mach.proprietaire().compte() != cherrypy.session['uid']:
del adh, mach
raise Exception(u"L'uid de l'adherent ne correspond mas au proprietaire de la machine.")
anciennemac = mach.mac()
nommachine = mach.nom()
mach.mac(nouvelleMAC)
mach.save()
del mach
except ValueError, e:
return {'error':e.args[0]}
crans.cp.log("Change mac machine %s : %s->%s" % (nommachine, anciennemac, nouvelleMAC), "MESMACHINES")
return {'message':u"Modification réussie", 'mid':mid}
AJAXchangerMAC.exposed = True
##########################
# machine:suppression
##########################
def AJAXSupprimerMachine(self, mid):
try:
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
mach = cherrypy.session['LDAP'].search('mid=' + mid, 'w')['machine'][0]
# tester si c'est bien la machine de l'adherent
if mach.proprietaire().compte() != cherrypy.session['uid']:
del adh, mach
raise Exception(u"L'uid de l'adherent ne correspond mas au proprietaire de la machine.")
mach.delete()
except ValueError, e:
return {'error':e.args[0]}
crans.cp.log("Machine supprimee", "MACHINES")
return {'message':u"Machine supprimée"}
AJAXSupprimerMachine.exposed = True
##########################
# machine:creation
##########################
def AJAXCreerMachine(self, nomNouvelleMachine, MACNouvelleMachine, typeNouvelleMachine):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
if typeNouvelleMachine=='fixe' and adh.droits() == [] and adh.machines_fixes() != []:
return {'error':'Vous avez deja une machine fixe. Vous ne pouvez ajouter que des machines WiFi.'}
try:
if typeNouvelleMachine=='wifi':
m = MachineWifi(adh)
elif typeNouvelleMachine=='fixe':
m = MachineFixe(adh)
else:
raise Exception, "type de machine inconnu : %s " % typeNouvelleMachine
m.nom(nomNouvelleMachine)
m.mac(MACNouvelleMachine)
m.ip("<automatique>")
message = m.save()
del m
except ValueError, e:
del m
return {'error':e.args[0].replace("\n","\\n")}
crans.cp.log("Nouvelle machine %s" % nomNouvelleMachine, "MACHINES")
return {'message':u"Machine enregistrée avec succès"}
AJAXCreerMachine.exposed = True

View file

@ -1,356 +0,0 @@
#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
# ##################################################################################################### #
# MonCompte
# ##################################################################################################### #
# Description:
#
# Informations:
#
# Pages:
#
#
# ##################################################################################################### #
import cherrypy, sys, os, datetime
# libraries crans
import crans.cp as _crans_cp
sys.path.append('/usr/scripts/gestion/')
from config_mail import MailConfig
if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
from ldap_crans_test import *
# print("monCompte : unsing test ldap : env=" + cherrypy.config.configMap["global"]["server.environment"])
else:
from ldap_crans import *
# print("monCompte : unsing prod ldap : env=" + cherrypy.config.configMap["global"]["server.environment"])
class monCompte:
def getCurrentAdministrativeYear(self):
'''
premiere partie de l''annee scolaire en cours
ex : le 5 juin 2006 retourne 2005
'''
now = datetime.datetime.now()
currentYear = int(now.strftime("%Y"))
currentMonth = int(now.strftime("%m"))
if currentMonth > 8:
administrativeYear = currentYear
else:
administrativeYear = currentYear - 1
return administrativeYear
##########################
# affichage
##########################
#
# methode qui affiche la template avec toutes les infos de
# l'adherent + les formulaires
#
def index(self, message = '', error = '', currentTab = 'mainTab'):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
t = {}
t['message'] = message
t['error'] = error
############## info adherent ##############
adherent = {}
# nom, prenom, chambre, tel, solde, droits, mail
adherent['prenom'] = adh.prenom()
adherent['nom'] = adh.nom()
adherent['chambre'] = adh.chbre()
if adherent['chambre'] == "EXT":
adr = adh.adresse()
adherent['adresse'] = {}
adherent['adresse']['ligne1'] = adr[0]
adherent['adresse']['ligne2'] = adr[1]
adherent['adresse']['cp'] = adr[2]
adherent['adresse']['ville'] = adr[3]
adherent['telephone'] = adh.tel
adherent['solde'] = adh.solde
adherent['droits'] = u", ".join(adh.droits())
adherent['mail'] = adh.email()
# cotisation
administrativeYear = self.getCurrentAdministrativeYear()
if administrativeYear in adh.paiement():
adherent['cotisationOK'] = 'OK'
else:
adherent['cotisationOK'] = None
# carte etudiant
if administrativeYear in adh.carteEtudiant():
adherent['carteOK'] = 'OK'
else:
adherent['carteOK'] = None
# annee scolaire (ex 2001-2002)
adherent['anneeScolaire'] = str(administrativeYear) + '-' + str(administrativeYear + 1)
t['adherent'] = adherent
############## info mail ##############
mailInfos = {}
try:
mailConfig = MailConfig(cherrypy.session['uid'])
mailInfos['forwarding_address'] = mailConfig['forward']
mailInfos['spam'] = {}
mailInfos['spam']['no'] = mailConfig['spam'] == 'accepte'
mailInfos['spam']['mark'] = mailConfig['spam'] == 'marque'
mailInfos['spam']['drop'] = mailConfig['spam'] == 'supprime'
except Exception, e:
t['mailError'] = u"Erreur:fichiers de configuration mail personnels"
mailInfos['alias'] = adh.alias()
mailInfos['contourneGreylist'] = adh.contourneGreylist()
mailInfos['rewriteMailHeaders'] = adh.rewriteMailHeaders()
t['mailInfos'] = mailInfos
return {
'template' :'monCompte',
'values' :t,
'stylesheets' :['monCompte.css'],
'scripts':['crans_domtab.js','moncompte.js','passwordGenerator.js'],
}
index.exposed = True
##########################
# paypal
##########################
#
# methode qui affiche successivement les
# templates du popup pour recharger son compte impression
# via paypal
#
def rechargerCompteImpression(self, etape = '1', combien = None):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
if (etape == "1"): # Introduction
return {
'template' :'MonCompteRechargePaypal1',
'standalone' :True,
'values' :{},
}
elif (etape == "2"): # choix montant
return {
'template' :'MonCompteRechargePaypal2',
'standalone' :True,
'values' :{},
}
elif (etape == "3"): # confirmer facture
# creer objet facture
f = Facture(adh)
# /!\ verifier que combien est un nombre
# et qu'il n'y a pas plus de 2 chiffres après le point...
# (ce serait bien aussi si on pouvait mettre une virgue a la place du point)
try:
# remplacage des virgules
combien = combien.replace(u',', u'.')
# convertissage
combien = float(combien)
# arrondissage-tronquage :
combien = float(int(combien*100)/100.0)
# nombre positif
if combien < 0:
raise ValueError
except Exception:
return {
'template' :'MonCompteRechargePaypal2',
'standalone' :True,
'values' :{'error':"Le montant doit &ecirc;tre un nombre positif !", 'combien':combien},
}
f.ajoute({'nombre': 1, 'code': 'SOLDE', 'designation': 'Credit du compte impression (intranet)', 'pu': combien})
cherrypy.session['freshFacture'] = f
pageData = {}
pageData['details'] = [
{
'intitule':art['designation'],
'quantite':art['nombre'],
'prixUnitaire':art['pu'],
'prixTotal':art['pu']*art['nombre'],
} for art in f.articles()]
pageData['total'] = f.total()
return {
'template' :'MonCompteRechargePaypal3',
'standalone' :True,
'values' :pageData,
}
elif (etape == "4"):# payer maintenant ?
# sauver objet facture
f = cherrypy.session['freshFacture']
f.save()
return {
'template' :'MonCompteRechargePaypal4',
'standalone' :True,
'values' :{'lienPaypal' : f.urlPaypal(useSandbox = cherrypy.config.get("paypal.useSandbox", False),
businessMail = cherrypy.config.get("paypal.businessAdress", "paypal@crans.org"),
return_page = "https://intranet.crans.org/monCompte/paypalReturn",
cancel_return_page = "https://intranet.crans.org/monCompte/paypalCancel",
)},
}
rechargerCompteImpression.exposed = True
def paypalReturn(self, **kw):
_crans_cp.log("retour de paypal avec les infos : %s" % " ".join( [ "[%s: %s]" % (str(a), str(kw[a])) for a in kw] ) )
return {
'template' :'MonComptePaypalReturn',
'standalone' :True,
'values' :{},
}
paypalReturn.exposed = True
def paypalCancel(self, **kw):
_crans_cp.log("annulation de paypal avec les infos : %s" % " ".join( [ "[%s: %s]" % (str(a), str(kw[a])) for a in kw] ) )
return {
'template' :'MonComptePaypalCancel',
'standalone' :True,
'values' :{},
}
paypalCancel.exposed = True
###########################################################################
# methodes pour changer
# des valeurs
###########################################################################
#
# En fait, les methodes recoivent les valeurs d'un formulaire
# (ou equivalent de javascript), font la modification puis
# appellent la methode principale d'affichage
# en lui passant eventuellement un message a afficher
# (pour indiquer la reussite ou non de l'operation)
#
##########################
# Adherent:nom
##########################
def changeNomAdherent(self, nouveauNom):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'], 'w')['adherent'][0]
try:
ancienNom = adh.nom()
adh.nom(nouveauNom)
adh.save()
except ValueError, e:
return self.index(error=e.args[0])
del adh
_crans_cp.log("Change nom : %s -> %s" % (ancienNom, nouveauNom), "MONCOMPTE")
return self.index(message=u'Modification réussie')
changeNomAdherent.exposed = True
##########################
# Adherent:password
##########################
def changePasswordAdherent(self, ancienPassword, nouveauPassword1, nouveauPassword2):
if ancienPassword=='':
msg = 'Erreur, mot de passe incorrect'
return self.index(error=msg)
if nouveauPassword1=='':
msg = 'Erreur, le nouveau mot de passe ne doit pas &egrave;tre vide.'
return self.index(error=msg)
if nouveauPassword1!=nouveauPassword2:
msg = 'Erreur, la confirmation ne correspond pas au nouveau mot de passe.'
return self.index(error=msg)
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'],'w')['adherent'][0]
if adh.checkPassword(ancienPassword):
adh.changePasswd(nouveauPassword1)
adh.save()
msg = u'Changement effectué'
else:
msg = 'Erreur, mot de passe incorrect'
return self.index(error=msg)
del adh
_crans_cp.log("Change password", "MONCOMPTE")
return self.index(message=msg)
changePasswordAdherent.exposed = True
##########################
# Adherent:prenom
##########################
def changePrenomAdherent(self, nouveauPrenom):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'], 'w')['adherent'][0]
try:
ancienPrenom = adh.prenom()
adh.prenom(nouveauPrenom)
adh.save()
except ValueError, e:
return self.index(error=e.args[0])
del adh
_crans_cp.log("Change prenom : %s -> %s" % (ancienPrenom, nouveauPrenom), "MONCOMPTE")
return self.index(message=u'Modification réussie')
changePrenomAdherent.exposed = True
##########################
# Adherent:tel
##########################
def changeTelAdherent(self, nouveauTel):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'], 'w')['adherent'][0]
try:
ancienTel = adh.tel()
adh.tel(nouveauTel)
adh.save()
except ValueError, e:
return self.index(error=e.args[0])
del adh
_crans_cp.log("Change tel : %s -> %s" % (ancienTel, nouveauTel), "MONCOMPTE")
return self.index(message=u'Modification réussie')
changeTelAdherent.exposed = True
##########################
# mail:alias:creation
##########################
def newAlias(self, alias):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'],'w')['adherent'][0]
if adh.alias().__len__() >= 3 and adh.droits() == []:
return self.index(error=u"Vous avez plus de 2 alias. Demander a un cableur pour en rajouter.")
try:
adh.alias(alias)
adh.save()
del adh
except ValueError, e:
return self.index(error=e.args[0])
except RuntimeError:
return self.index(error=u"Vous possèdez déjà  cet alias")
except EnvironmentError:
return self.index(error=u"Vous possèdez déjà  cet alias")
_crans_cp.log("Nouvel alias : %s" % alias, "MONCOMPTE")
return self.index(message=u'Alias enregistré')
newAlias.exposed = True
##########################
# mail:sauver
##########################
def saveMailPrefs(self, forwarding_address=None, spanTreatment=None, contourneGreylist=False, rewriteMailHeaders=False):
if spanTreatment == 'no':
spanTreatment = 'accepte'
if spanTreatment == 'mark':
spanTreatment = 'marque'
if spanTreatment == 'drop':
spanTreatment = 'supprime'
if contourneGreylist == 'oui':
contourneGreylist = True
if rewriteMailHeaders == 'oui':
rewriteMailHeaders = True
try:
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'],'w')['adherent'][0]
if forwarding_address!=None:
MailConfig(cherrypy.session['uid'], forward=forwarding_address, spam=spanTreatment)
adh.contourneGreylist(contourneGreylist)
adh.rewriteMailHeaders(rewriteMailHeaders)
adh.save()
del adh
except ValueError, e:
return self.index(error=e.args[0])
except Exception, e:
return self.index(error=u"Une erreur est survenue lors de lenregistrement. Vérifiez que l'adresse mail fournie est correcte.")
_crans_cp.log("Change mail prefs", "MONCOMPTE ACTION")
return self.index(message=u'Vos préférences ont été enregistrées')
saveMailPrefs.exposed = True