#! /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"]) from ClassesIntranet.ModuleBase import ModuleBase class main(ModuleBase): def title(self): return "Mon Compte" 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 ê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 è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