Le repo des sources pour le site web des JM2L
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

2052 lines
91 KiB

  1. # -*- coding: utf8 -*-
  2. from pyramid.httpexceptions import HTTPFound, HTTPNotFound, HTTPForbidden
  3. from pyramid.httpexceptions import HTTPBadRequest, HTTPUnauthorized
  4. from pyramid.renderers import render_to_response
  5. from pyramid.view import notfound_view_config, forbidden_view_config
  6. from pyramid.view import view_config
  7. from pyramid.response import Response
  8. from mako.template import Template
  9. from pyramid_mailer.message import Message
  10. from .upload import IMAGEPATH
  11. # Import Web Forms
  12. from .forms import *
  13. # Database access imports
  14. from .models import *
  15. from .helpers import Orga_helpers
  16. from sqlalchemy import func, or_, text, and_
  17. from sqlalchemy.orm import aliased
  18. from os import path, makedirs, listdir
  19. # Usefull tools
  20. from slugify import slugify
  21. from icalendar import Calendar
  22. from pytz import timezone
  23. from icalendar import Event as Evt
  24. from pyramid_mailer.message import Message
  25. # Then, standard libs
  26. import csv
  27. import cStringIO as StringIO
  28. import webhelpers.paginate as paginate
  29. import unicodedata
  30. import datetime
  31. import re
  32. import shutil
  33. import glob
  34. from jm2l.const import CurrentYear
  35. ## =-=- Here, We keep some usefull function -=-=
  36. def remove_accents(input_str):
  37. """ This function is intended to remove all accent from input unicode string """
  38. nkfd_form = unicodedata.normalize('NFKD', input_str)
  39. only_ascii = nkfd_form.encode('ASCII', 'ignore')
  40. return only_ascii
  41. def embeed_video(mime_type, link):
  42. Container = "<video controls='controls' preload='metadata' style='width:60%'>"
  43. Container += "<source type='%s' " % mime_type
  44. Container += "src='%s' />" % link
  45. Container += "</video>"
  46. return Container
  47. @view_config(route_name='Live', renderer="jm2l:templates/Live.mako")
  48. def Live(request):
  49. year = int(request.matchdict.get('year', CurrentYear))
  50. tz = timezone('Europe/Paris')
  51. curtime = datetime.datetime.now().replace(tzinfo=tz, day=28) #, hour=10, minute=00 )
  52. Events = DBSession.query(Event)\
  53. .filter(Event.for_year == year)\
  54. .filter(Event.event_type != 'Stand')\
  55. .filter(and_(Event.start_time <= curtime, Event.end_time >= curtime) )\
  56. .order_by(Event.start_time)
  57. return {'year': year, "DisplayYear": year, 'events':Events, "logged_in":request.authenticated_userid }
  58. ## =-=- Here, We handle ICal requests -=-=
  59. @view_config(route_name='progr_iCal', renderer="string")
  60. def ICal_Progamme_Request(request):
  61. year = int(request.matchdict.get('year', CurrentYear))
  62. # Initialization
  63. # Compute days used by all events matching the specified input year
  64. Events = DBSession.query(Event)\
  65. .filter(Event.for_year == year)\
  66. .filter(Event.event_type != 'Stand')\
  67. .order_by(Event.start_time)
  68. cal = Calendar()
  69. cal.add('prodid', '-//Programme %d//jm2l.linux-azur.org//' % year)
  70. cal.add('version', '2.0')
  71. tz = timezone('Europe/Paris')
  72. for ev in Events:
  73. if ev.event_type:
  74. event = Evt()
  75. event['uid'] = "%d/%d" % ( year, ev.uid )
  76. event.add('summary', ev.name )
  77. event.add('dtstart', ev.start_time.replace(tzinfo=tz) )
  78. event.add('dtend', ev.end_time.replace(tzinfo=tz) )
  79. event.add('created', ev.last_change.replace(tzinfo=tz) )
  80. event.add('description', "http://www.linux-azur.org/event/%s/%s" % (ev.for_year, ev.slug) )
  81. event.add('url', "http://www.linux-azur.org/event/%s/%s" % (ev.for_year, ev.slug) )
  82. event.add('priority', 5)
  83. cal.add_component(event)
  84. request.response.content_type = "text/calendar"
  85. return cal.to_ical()
  86. ## =-=- Here, We handle ICal requests -=-=
  87. @view_config(route_name='progr_dyn_iCal', renderer="string")
  88. def ICal_Progamme_Dyn_Request(request):
  89. year = int(request.matchdict.get('year', CurrentYear))
  90. # Initialization
  91. # Compute days used by all events matching the specified input year
  92. Events = DBSession.query(Event)\
  93. .filter(Event.for_year == year)\
  94. .filter(Event.event_type != 'Stand')\
  95. .order_by(Event.start_time)
  96. cal = Calendar()
  97. cal.add('prodid', '-//Programme %d//jm2l.linux-azur.org//' % year)
  98. cal.add('version', '2.0')
  99. today = datetime.datetime.now()
  100. tz = timezone('Europe/Paris')
  101. event = Evt()
  102. event['uid'] = "%d/%d" % ( year, 100 )
  103. event.add('summary', "Les stands JM2L %s" % year )
  104. event.add('dtstart', datetime.datetime.now().replace(tzinfo=tz, hour=10, minute=00 ) )
  105. event.add('dtend', datetime.datetime.now().replace(tzinfo=tz, hour=18, minute=00 ) )
  106. event.add('created', datetime.datetime.now().replace(tzinfo=tz, hour=10, minute=00 ) )
  107. event.add('description', "https://www.youtube.com/watch?v=91X65eEKxvU&t=6s" )
  108. event.add('location', "http://jm2l.linux-azur.org/img/325.gif" )
  109. event.add('url', "http://jm2l.linux-azur.org/%s/le-programme" % CurrentYear)
  110. event.add('priority', 5)
  111. cal.add_component(event)
  112. TabCorr = {
  113. 135:"Koneko",
  114. 131:"cam-jm2l-a",
  115. 132:"cam-jm2l-b",
  116. 115:"cam-jm2l-e",
  117. 114:"cam-jm2l-f",
  118. 116:"cam-jm2l-g",
  119. 139:"cam-jm2l-y"
  120. }
  121. for i, ev in enumerate(Events):
  122. if ev.event_type:
  123. event = Evt()
  124. event['uid'] = "%d/%d" % ( year, ev.uid )
  125. event.add('summary', ev.name )
  126. event.add('dtstart', ev.start_time.replace(tzinfo=tz, day=today.day, month = today.month, hour=(ev.start_time.hour)%24 ) )
  127. event.add('dtend', ev.end_time.replace(tzinfo=tz, day=today.day, month = today.month, hour=(ev.end_time.hour)%24 ) )
  128. event.add('created', ev.last_change.replace(tzinfo=tz) )
  129. event.add('description', "http://jm2l.linux-azur.org:8080/%s.webm" % TabCorr.get(ev.Salle.phy_salle_id, ev.Salle.phy_salle_id) )
  130. event.add('location', "http://jm2l.linux-azur.org/img/%d.gif" % ev.Salle.phy_salle_id )
  131. event.add('url', "http://www.linux-azur.org/event/%s/%s" % (ev.for_year, ev.slug) )
  132. event.add('priority', 5)
  133. cal.add_component(event)
  134. request.response.content_type = "text/calendar"
  135. return cal.to_ical()
  136. ## =-=- Here, We handle Json requests -=-=
  137. @view_config(route_name='users_json', renderer="json")
  138. def JSON_User_Request(request):
  139. """ Build a JSON answer with active users and pagination handling """
  140. # Check arguments consitency
  141. pageSize = request.params.get('pageSize',"8")
  142. current_page = request.params.get('pageNum',"1")
  143. UserQuery = request.params.get('searchTerm', u"")
  144. # Don't answer to users that aren't logged
  145. if not request.user:
  146. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  147. # Check consistancy of parameters
  148. if pageSize.isdigit() and current_page.isdigit():
  149. current_page = int(current_page)
  150. pageSize = int(pageSize)
  151. else:
  152. return HTTPBadRequest('pageSize and pageNum accept only digits.')
  153. # Query database
  154. Users = DBSession.query(User.uid, User.nom, User.prenom)\
  155. .filter(User.slug.contains( remove_accents(UserQuery) ))
  156. page_url = paginate.PageURL_WebOb(request)
  157. records = paginate.Page(Users, current_page, url=page_url, items_per_page=pageSize)
  158. ListMatchUser = map( lambda u:{"id": u.uid, "text":"%s %s" % ( u.prenom, u.nom )}, records )
  159. return { "Results": ListMatchUser, "Total":records.item_count,
  160. "logged_in":request.authenticated_userid }
  161. @view_config(route_name='tiers_json', renderer="json")
  162. def JSON_Tiers_Request(request):
  163. """ Build a JSON answer with active users and pagination handling """
  164. # Check arguments consitency
  165. pageSize = request.params.get('pageSize',"8")
  166. current_page = request.params.get('pageNum',"1")
  167. TiersQuery = request.params.get('searchTerm', u"")
  168. # Don't answer to users that aren't logged
  169. if not request.user:
  170. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  171. # Check consistancy of parameters
  172. if pageSize.isdigit() and current_page.isdigit():
  173. current_page = int(current_page)
  174. pageSize = int(pageSize)
  175. else:
  176. return HTTPBadRequest('pageSize and pageNum accept only digits.')
  177. # Query database
  178. JTiers = DBSession.query(Tiers.uid, Tiers.name)\
  179. .filter(Tiers.slug.contains( remove_accents(TiersQuery) ))
  180. page_url = paginate.PageURL_WebOb(request)
  181. records = paginate.Page(JTiers, current_page, url=page_url, items_per_page=pageSize)
  182. ListMatchTiers = map( lambda t:{"id": t.uid, "text": t.name }, records )
  183. return { "Results": ListMatchTiers, "Total":records.item_count,
  184. "logged_in":request.authenticated_userid }
  185. @view_config(route_name='progr_json', renderer="json")
  186. def JSON_Progamme_Request(request):
  187. year = int(request.matchdict.get('year', CurrentYear))
  188. # Initialization
  189. DicResult = dict()
  190. # Query database
  191. # Compute days used by all events matching the specified input year
  192. Days = DBSession.query( func.strftime('%d', Event.start_time).label('day') )\
  193. .filter(Event.for_year == year)\
  194. .filter(Event.event_type != None)\
  195. .group_by(func.strftime('%d', Event.start_time)).all()
  196. for Day in Days:
  197. Events = DBSession.query(Event)\
  198. .filter(Event.for_year == year)\
  199. .filter(Event.event_type != 'Stand')\
  200. .filter(text("strftime('%d', start_time) = :dow")).params(dow=Day.day)\
  201. .order_by(Event.start_time)
  202. ListEv = []
  203. for ev in Events:
  204. if ev.event_type:
  205. ListEv.append( {
  206. "uid":"%d/%d" % ( year, ev.uid ),
  207. "desc":ev.name,
  208. "startDate":ev.start_time.strftime('%Y-%m-%dT%H:%M:%S+01:00'),
  209. "endDate":ev.end_time.strftime('%Y-%m-%dT%H:%M:%S+01:00'),
  210. "placeName":ev.Salle and (ev.Salle.name or "unk") ,
  211. "status":ev.event_type
  212. } )
  213. DicResult[Day.day] = ListEv
  214. return { 'all':DicResult }
  215. @view_config(route_name='timeline_json', renderer="json")
  216. def JSON_TimeLine_Request(request):
  217. year = int(request.matchdict.get('year', CurrentYear))
  218. # Initialization
  219. DicResult = dict()
  220. # Query database
  221. # Compute days used by all events matching the specified input year
  222. Days = DBSession.query( func.strftime('%d', Event.start_time).label('day') )\
  223. .filter(Event.for_year == year)\
  224. .filter(Event.event_type != None)\
  225. .group_by(func.strftime('%d', Event.start_time)).all()
  226. ListEv = []
  227. for Day in Days:
  228. Events = DBSession.query(Event)\
  229. .filter(Event.for_year == year)\
  230. .filter(Event.event_type != 'Stand')\
  231. .filter(text("strftime('%d', start_time) = :dow")).params(dow=Day.day)\
  232. .order_by(Event.start_time)
  233. #ListEv = []
  234. for ev in Events:
  235. if ev.event_type:
  236. CurMedia = ev.video.first() or ""
  237. if CurMedia:
  238. Container = "<video controls='controls' preload='metadata' style='width:60%'>"
  239. Container += "<source type='%s' " % CurMedia.mime_type
  240. Container += "src='%s' />" % CurMedia.get_path
  241. Container += "</video>"
  242. else:
  243. Container = ""
  244. ListEv.append( {
  245. #"uid":"%d/%d" % ( year, ev.uid ),
  246. "headline":'<a href="/event/%s/%s">%s</a>' % (ev.for_year, ev.slug, ev.name),
  247. "startDate":ev.start_time.strftime('%Y,%m,%d,%H,%M'),
  248. "endDate":ev.end_time.strftime('%Y,%m,%d,%H,%M'),
  249. "text": ev.Salle and (ev.Salle.name or "unk"),
  250. #"text":ev.description[:100],
  251. "tags":ev.Salle and (ev.Salle.salle_id or "unk") ,
  252. #"status":ev.event_type,
  253. "asset": {
  254. "media": Container,
  255. "credit": ",".join(["%s %s" % (i.prenom, i.nom) for i in ev.intervenants]),
  256. "caption":"" }
  257. } )
  258. if year==2017:
  259. DicResult = {
  260. "lang":"fr",
  261. "headline":"JM2L 2017",
  262. "type":"default",
  263. "startDate":"2017,11,25,10",
  264. "text":"<i><span class='c1'>10ème Édition</span></i>",
  265. "asset":
  266. {
  267. #"media":"https://www.youtube.com/watch?v=91X65eEKxvU&t=6s",
  268. "media":embeed_video("video/ogg","http://jm2l.linux-azur.org/resources/2015/Video/jm2l_france3-2015.ogv"),
  269. "credit":"Reportage France 3",
  270. "caption":"JM2L 2015"
  271. }
  272. }
  273. elif year==2015:
  274. DicResult = {
  275. "lang":"fr",
  276. "headline":"JM2L 2015",
  277. "type":"default",
  278. "startDate":"2015,11,28,10",
  279. "text":"<i><span class='c1'>9ème Édition</span></i>",
  280. "asset":
  281. {
  282. #"media":"https://www.youtube.com/watch?v=91X65eEKxvU&t=6s",
  283. "media":embeed_video("video/ogg","http://jm2l.linux-azur.org/resources/2015/Video/jm2l_france3-2015.ogv"),
  284. "credit":"Reportage France 3",
  285. "caption":"JM2L 2015"
  286. }
  287. }
  288. elif year==2011:
  289. DicResult = {
  290. "lang":"fr",
  291. "headline":"JM2L 2011",
  292. "type":"default",
  293. "startDate":"2011,11,25,10",
  294. "text":"<i><span class='c1'>6ème Édition</span></i>",
  295. "asset":
  296. {
  297. "media":"https://www.youtube.com/embed/rcaNeXuAEhs",
  298. "credit":"JM2L",
  299. "caption":"Reportage FR3"
  300. },
  301. }
  302. elif year==2010:
  303. DicResult = {
  304. "lang":"fr",
  305. "headline":"JM2L 2010",
  306. "type":"default",
  307. "text":"<i><span class='c1'>5ème Édition</span></i>",
  308. "asset":
  309. {
  310. "media":embeed_video("video/ogg","http://jm2l.linux-azur.org/resources/2010/Video/reportages/JM2L2010-PleinSudTV.ogv"),
  311. "credit":"<a href='http://pleinsudtv.com/index.php/casa/affichage-en-vignettes/93-casa-culture/582-les-jm-du-logiciel-libre-2010'>Le reportage Plein-sud TV</a>",
  312. "caption":"JM2L",
  313. }
  314. }
  315. elif year==2007:
  316. DicResult = {
  317. "lang":"fr",
  318. "headline":"JM2L 2007",
  319. "type":"default",
  320. "text":"<i><span class='c1'>2ème Édition</span></i>",
  321. "asset":
  322. {
  323. "media":embeed_video("video/ogg","http://jm2l.linux-azur.org/resources/2007/Video/20071110-linux.ogv"),
  324. "credit":"<a href='http://pleinsudtv.com/index.php/casa/affichage-en-vignettes/93-casa-culture/245-logiciel-libre-linux-jm2l'>Le reportage Plein-sud TV</a>",
  325. "caption":"JM2L 2007",
  326. }
  327. }
  328. else:
  329. DicResult = {
  330. "lang":"fr",
  331. "headline":"JM2L %d" % year,
  332. "type":"default",
  333. "asset":
  334. {
  335. "media":"",
  336. "credit":"JM2L",
  337. "caption":""
  338. }
  339. }
  340. DicResult["date"] = ListEv
  341. return { 'timeline':DicResult }
  342. ## =-=- Here, We handle HTTP requests - Public Part -=-=
  343. @view_config(route_name='home', renderer="jm2l:templates/NewIndex.mako")
  344. def index_page(request):
  345. year = request.matchdict.get('year')
  346. if year:
  347. year=int(year[:-1])
  348. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==year).first()
  349. if content:
  350. content = content.description
  351. else:
  352. content = ""
  353. if 2004<year<=CurrentYear:
  354. if year==2006:
  355. return {'year': year, 'content':content, 'edition':u"1<sup>ère</sup>" }
  356. elif year==2015:
  357. return {'year': year, 'content':content, 'edition':u"9<sup>ème</sup>" }
  358. elif year==2017:
  359. return {'year': year, 'content':content, 'edition':u"10<sup>ème</sup>" }
  360. else:
  361. edition = year - 2005
  362. return {'year': year, 'content':content, 'edition':u"%d<sup>ème</sup>" % edition }
  363. else:
  364. raise HTTPNotFound()
  365. else:
  366. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==CurrentYear).first().description
  367. TargetDir = "jm2l/static/img/%s/Photos" % (year or CurrentYear)
  368. TargetUrl = "/static/img/%s/Photos/" % (year or CurrentYear)
  369. if path.isdir(TargetDir):
  370. ListPhotos = map(lambda x: TargetUrl + x, listdir(TargetDir))
  371. else:
  372. ListPhotos = []
  373. return {'year': CurrentYear, 'content':content, 'edition':u"10<sup>ème</sup>", 'ListPhotos': ListPhotos}
  374. @view_config(route_name='edit_index', renderer="jm2l:templates/Staff/EditIndex.mako")
  375. def edit_index(request):
  376. year = int(request.matchdict.get('year', CurrentYear))
  377. if not request.user.Staff:
  378. # Don't answer to users that aren't logged
  379. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  380. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==year).first()
  381. form = IndexForm(request.POST, content, meta={'csrf_context': request.session})
  382. if request.method == 'POST' and form.validate():
  383. form.populate_obj(content)
  384. return HTTPFound(location=request.route_url('home', year="%d/" % year))
  385. MainTab = {'home':'active', "logged_in":request.authenticated_userid,
  386. 'form':form, 'DisplayYear':year}
  387. return MainTab
  388. @view_config(route_name='programme', renderer="jm2l:templates/Public/Programme.mako")
  389. def programme(request):
  390. year = int(request.matchdict.get('year'))
  391. if 2006 > year:
  392. return HTTPBadRequest('The first JM2L event was in 2006.')
  393. # Query database about selected Year.
  394. Events = DBSession.query(Event)\
  395. .filter(Event.for_year == year)\
  396. .order_by(Event.start_time)
  397. Days = DBSession.query(func.strftime('%d-%m-%Y', Event.start_time))\
  398. .filter(Event.for_year == year)\
  399. .filter(Event.event_type != None)\
  400. .group_by(func.strftime('%d', Event.start_time)).all()
  401. ListDay = []
  402. for day in Days:
  403. RefDay = datetime.datetime.strptime(day[0],'%d-%m-%Y')
  404. ListDay.append( ( RefDay.strftime('%A %d %b %Y'),
  405. RefDay.strftime('%d') ) )
  406. MainTab = {'programme':'active','DisplayYear':year, \
  407. 'Events':Events, 'Event':Event, 'Days':ListDay, "logged_in":request.authenticated_userid }
  408. return MainTab
  409. @view_config(route_name='presse', renderer="jm2l:templates/Public/Presse.mako")
  410. def static_presse(request):
  411. year = int(request.matchdict.get('year', None))
  412. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==year).first()
  413. MainTab = {'presse':'active', "logged_in":request.authenticated_userid, 'content':content, 'DisplayYear':year}
  414. return MainTab
  415. @view_config(route_name='edit_presse', renderer="jm2l:templates/Staff/EditPresse.mako")
  416. def edit_presse(request):
  417. year = int(request.matchdict.get('year', None))
  418. if request.user is None:
  419. # Don't answer to users that aren't logged
  420. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  421. if not request.user.Staff:
  422. # Don't answer to users that aren't logged
  423. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  424. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==year).first()
  425. form = DossPresse(request.POST, content, meta={'csrf_context': request.session})
  426. if request.method == 'POST' and form.validate():
  427. form.populate_obj(content)
  428. MainTab = {'presse':'active', "logged_in":request.authenticated_userid, 'form':form, 'DisplayYear':year}
  429. return MainTab
  430. @view_config(route_name='plan', renderer="jm2l:templates/Public/Plan.mako")
  431. def static_plan(request):
  432. session = request.session
  433. session['year'] = CurrentYear
  434. MainTab = {'plan':'active', "logged_in":request.authenticated_userid }
  435. return MainTab
  436. ## =-=- Here, We handle HTTP requests - Staff Logged Part -=-=
  437. @view_config(route_name='list_task', renderer='jm2l:templates/Staff/list.mako')
  438. def list_view(request):
  439. year = int(request.matchdict.get('year', CurrentYear))
  440. if request.user is None:
  441. # Don't answer to users that aren't logged
  442. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  443. if not request.user.Staff:
  444. # Don't answer to users that aren't logged
  445. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  446. DicTask = {}
  447. taskgroup = DBSession.query( TasksArea ).filter( TasksArea.year_uid == year).all()
  448. for grp in taskgroup:
  449. tasks = DBSession.query( Tasks )\
  450. .filter( Tasks.area_uid==grp.uid ) \
  451. .filter( Tasks.year_uid == year) \
  452. .order_by(Tasks.closed, Tasks.due_date).all()
  453. DicTask[grp] = tasks
  454. return {'tasks': DicTask, 'year':year }
  455. @view_config(route_name='list_expenses', renderer='jm2l:templates/Staff/compta.mako')
  456. def expenses(request):
  457. year = int(request.matchdict.get('year', CurrentYear))
  458. if request.user is None:
  459. # Don't answer to users that aren't logged
  460. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  461. if not request.user.Staff:
  462. # Don't answer to users that aren't logged
  463. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  464. output = []
  465. dic_out = {}
  466. for name in glob.glob('jm2l/upload/images/users/*/RIB/*'):
  467. tab_path = name.split('/')
  468. if tab_path[6]=='thumbnails' or tab_path[6].endswith('.type'):
  469. continue
  470. if dic_out.get(tab_path[4]) is None:
  471. dic_out[tab_path[4]] = {}
  472. if dic_out[tab_path[4]].get('RIB') is None:
  473. dic_out[tab_path[4]]['RIB'] = {'files':[], 'thumb':[]}
  474. u = User.by_slug(tab_path[4])
  475. dic_out[tab_path[4]]['User'] = {
  476. 'uid':u.uid,
  477. 'nom':u.nom,
  478. 'prenom':u.prenom,
  479. 'slug':u.slug
  480. }
  481. dic_out[tab_path[4]]['RIB']['files'].append( name )
  482. dic_out[tab_path[4]]['RIB']['thumb'].append( name + ".jpg" )
  483. for name in glob.glob('jm2l/upload/images/users/*/Justif/*'):
  484. tab_path = name.split('/')
  485. if tab_path[6]=='thumbnails' or tab_path[6].endswith('.type'):
  486. continue
  487. if dic_out.get(tab_path[4]) is None:
  488. dic_out[tab_path[4]] = {}
  489. if dic_out[tab_path[4]].get('Justif') is None:
  490. dic_out[tab_path[4]]['Justif'] = {'files':[], 'thumb':[]}
  491. u = User.by_slug(tab_path[4])
  492. dic_out[tab_path[4]]['User'] = {
  493. 'uid':u.uid,
  494. 'nom':u.nom,
  495. 'prenom':u.prenom,
  496. 'slug':u.slug
  497. }
  498. dic_out[tab_path[4]]['Justif']['files'].append( name )
  499. dic_out[tab_path[4]]['Justif']['thumb'].append( name + ".jpg" )
  500. return dict(found=dic_out, year=year )
  501. @view_config(route_name='handle_task', renderer='jm2l:templates/Staff/tasks.mako')
  502. def tasks(request):
  503. year = int(request.matchdict.get('year', CurrentYear))
  504. if request.user is None:
  505. # Don't answer to users that aren't logged
  506. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  507. if not request.user.Staff:
  508. # Don't answer to users that aren't logged
  509. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  510. task_id = request.matchdict.get('task_id')
  511. # Convert the pole_id GET parameter to int or 0
  512. if request.params.get('pole_id') and request.params.get('pole_id').isdigit():
  513. pole_id = int(request.params.get('pole_id'))
  514. else:
  515. pole_id = None
  516. # Get areas from db
  517. Areas = DBSession.query(TasksArea.uid, TasksArea.name) \
  518. .filter(TasksArea.year_uid == year) \
  519. .order_by('name').all()
  520. # Get users from db
  521. Users = DBSession.query(User)\
  522. .filter(User.Staff==1)\
  523. .order_by('nom').all()
  524. if task_id:
  525. TmpTask = Tasks.by_id(int(task_id))
  526. if not TmpTask:
  527. raise HTTPNotFound()
  528. form = EditStaffTasks(request.POST, TmpTask, meta={'csrf_context': request.session})
  529. else:
  530. TmpTask = Tasks()
  531. # Check if the supplied pole_id is in the Areas' range
  532. form = StaffTasks(request.POST, TmpTask, meta={'csrf_context': request.session})
  533. Area = TasksArea.by_id(pole_id)
  534. if Area:
  535. form.area_uid.data = Area.uid
  536. # Put some areas on form
  537. form.area_uid.choices = Areas
  538. # Put some users on form
  539. form.closed_by.choices = [(u.uid, "%s %s" % (u.nom, u.prenom))
  540. for u in Users]
  541. form.due_date.type = "date"
  542. if request.method=='POST' and form.validate():
  543. form.populate_obj(TmpTask)
  544. TmpTask.closed = False
  545. if not TmpTask.year_uid:
  546. TmpTask.year_uid = year;
  547. if 'uid' in form._fields.keys():
  548. DBSession.merge(TmpTask)
  549. else:
  550. DBSession.add(TmpTask)
  551. DBSession.flush()
  552. return HTTPFound(location=request.route_url('list_task', year=year)+"#"+slugify(TmpTask.area.name))
  553. return {'form':form, 'area':TmpTask.area and slugify(TmpTask.area.name) or '', 'year':year}
  554. @view_config(route_name='handle_pole', renderer='jm2l:templates/Staff/pole.mako')
  555. def tasks_area(request):
  556. year = int(request.matchdict.get('year', CurrentYear))
  557. if request.user is None:
  558. # Don't answer to users that aren't logged
  559. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  560. if not request.user.Staff:
  561. # Don't answer to users that aren't logged
  562. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  563. pole_id = request.matchdict.get('pole_id')
  564. if pole_id:
  565. Pole = TasksArea.by_id(int(pole_id))
  566. if not Pole:
  567. raise HTTPNotFound()
  568. form = EditStaffArea(request.POST, Pole, meta={'csrf_context': request.session})
  569. else:
  570. Pole = TasksArea()
  571. form = StaffArea(request.POST, Pole, meta={'csrf_context': request.session})
  572. if request.method == 'POST' and form.validate():
  573. form.populate_obj(Pole)
  574. if not Pole.year_uid:
  575. Pole.year_uid = year;
  576. if 'uid' in form._fields.keys():
  577. DBSession.merge(Pole)
  578. else:
  579. DBSession.add(Pole)
  580. return HTTPFound(location=request.route_url('list_task', year=year)+"#"+slugify(Pole.name))
  581. return {'form':form, 'year':year }
  582. @view_config(route_name='action_task')
  583. def action_task(request):
  584. year = int(request.matchdict.get('year', CurrentYear))
  585. if request.user is None:
  586. # Don't answer to users that aren't logged
  587. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  588. if not request.user.Staff:
  589. # Don't answer to users that aren't logged
  590. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  591. action = request.matchdict.get('action')
  592. task_id = request.matchdict.get('task_id')
  593. Task = Tasks.by_id(int(task_id))
  594. if action=='close':
  595. Task.closed = True
  596. request.session.flash(('info', u'La tâche a été fermé, Félicitations !'))
  597. DBSession.merge(Task)
  598. if action=='open':
  599. Task.closed = False
  600. request.session.flash(('info', u'La tâche a été ré-ouverte !'))
  601. DBSession.merge(Task)
  602. if action=='delete':
  603. request.session.flash(('info', u'La tâche a été supprimée !'))
  604. DBSession.delete(Task)
  605. return HTTPFound(location=request.route_url('list_task', year=year)+"#"+slugify(Task.area.name))
  606. @view_config(route_name='action_task_area')
  607. def action_task_area(request):
  608. year = int(request.matchdict.get('year', CurrentYear))
  609. if request.user is None:
  610. # Don't answer to users that aren't logged
  611. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  612. if not request.user.Staff:
  613. # Don't answer to users that aren't logged
  614. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  615. action = request.matchdict.get('action')
  616. pole_id = request.matchdict.get('pole_id')
  617. Pole = TasksArea.by_id(int(pole_id))
  618. if not Pole:
  619. raise HTTPNotFound()
  620. if action=='delete':
  621. request.session.flash(('info', u'Le pôle a été supprimé !'))
  622. DBSession.delete(Pole)
  623. return HTTPFound(location=request.route_url('list_task', year=year))
  624. @view_config(route_name='list_salles', renderer='jm2l:templates/Salles/list.mako')
  625. def list_salles(request):
  626. if request.user is None:
  627. # Don't answer to users that aren't logged
  628. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  629. if not request.user.Staff:
  630. # Don't answer to users that aren't logged
  631. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  632. DicSalle = {}
  633. years = DBSession.query( JM2L_Year ).all()
  634. for year in years:
  635. salles = DBSession.query( Salles )\
  636. .filter( Salles.year_uid==year.year_uid )\
  637. .order_by(Salles.name).all()
  638. DicSalle[year] = salles
  639. return {'DicSalle': DicSalle }
  640. @view_config(route_name='list_salles_phy', renderer='jm2l:templates/Salles/list_phy.mako')
  641. def list_salles_phy(request):
  642. if request.user is None:
  643. # Don't answer to users that aren't logged
  644. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  645. if not request.user.Staff:
  646. # Don't answer to users that aren't logged
  647. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  648. salles_phy = DBSession.query( SallePhy )\
  649. .order_by(SallePhy.name).all()
  650. return {'DicSallePhy': salles_phy }
  651. @view_config(route_name='handle_salle', renderer='jm2l:templates/Salles/salle.mako')
  652. def handle_salle(request):
  653. if request.user is None:
  654. # Don't answer to users that aren't logged
  655. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  656. if not request.user.Staff:
  657. # Don't answer to users that aren't logged
  658. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  659. salle_id = request.matchdict.get('salle_id')
  660. if salle_id:
  661. Salle = Salles.by_id(int(salle_id))
  662. if not Salle:
  663. raise HTTPNotFound()
  664. form = EditSalleForm(request.POST, Salle, meta={'csrf_context': request.session})
  665. else:
  666. Salle = Salles()
  667. form = SalleForm(request.POST, Salle, meta={'csrf_context': request.session})
  668. form.year_uid.choices = map(tuple, DBSession.query(JM2L_Year.year_uid, JM2L_Year.year_uid).all())
  669. form.phy_salle_id.choices = map(tuple, DBSession.query(SallePhy.uid, SallePhy.name).all())
  670. if request.method == 'POST' and form.validate():
  671. form.populate_obj(Salle)
  672. if 'uid' in form._fields.keys():
  673. DBSession.merge(Salle)
  674. else:
  675. DBSession.add(Salle)
  676. return HTTPFound(location=request.route_url('list_salles'))
  677. return {'form':form }
  678. @view_config(route_name='handle_salle_phy', renderer='jm2l:templates/Salles/salle_phy.mako')
  679. def handle_salle_phy(request):
  680. if request.user is None:
  681. # Don't answer to users that aren't logged
  682. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  683. if not request.user.Staff:
  684. # Don't answer to users that aren't logged
  685. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  686. salle_id = request.matchdict.get('salle_id')
  687. if salle_id:
  688. Salle = SallePhy.by_id(int(salle_id))
  689. if not Salle:
  690. raise HTTPNotFound()
  691. form = EditSallePhyForm(request.POST, Salle, meta={'csrf_context': request.session})
  692. else:
  693. Salle = SallePhy()
  694. form = SallePhyForm(request.POST, Salle, meta={'csrf_context': request.session})
  695. if request.method == 'POST' and form.validate():
  696. form.populate_obj(Salle)
  697. Salle.slug = slugify(Salle.name)
  698. if 'uid' in form._fields.keys():
  699. DBSession.merge(Salle)
  700. else:
  701. DBSession.add(Salle)
  702. return HTTPFound(location=request.route_url('list_salles'))
  703. return {'form':form }
  704. @view_config(route_name='action_salle')
  705. def action_salle(request):
  706. if request.user is None:
  707. # Don't answer to users that aren't logged
  708. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  709. if not request.user.Staff:
  710. # Don't answer to users that aren't logged
  711. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  712. action = request.matchdict.get('action')
  713. salle_id = request.matchdict.get('salle_id')
  714. Salle = Salles.by_id(int(salle_id))
  715. if not Salle:
  716. raise HTTPNotFound()
  717. if action=='delete':
  718. request.session.flash(('info', u'La Salle a été supprimée !'))
  719. DBSession.delete(Salle)
  720. return HTTPFound(location=request.route_url('list_salles'))
  721. ## =-=- Here, We handle HTTP requests - User Logged Part -=-=
  722. @view_config(route_name='exchange', renderer="jm2l:templates/Logistique/Logistique.mako")
  723. def exchange(request):
  724. modtype = request.matchdict.get('modtype', None)
  725. action = request.matchdict.get('action', None)
  726. uid = int(request.matchdict.get('id', -1))
  727. Exch = Exchange.by_id(uid)
  728. if not Exch:
  729. MainTab = {
  730. 'Exchanges':Exchange,
  731. 'Type':modtype[-1:],
  732. 'reload':True,
  733. 'logged_in':request.authenticated_userid
  734. }
  735. return MainTab
  736. if action in ['delete', 'accept', 'refuse', 'deal']:
  737. if action=='delete': # delete exchange
  738. DBSession.delete(Exch)
  739. elif action=='accept': # accept exchange
  740. Exch.exch_done=True
  741. DBSession.merge(Exch)
  742. elif action=='refuse': # refuse exchange
  743. Exch.exch_done=False
  744. if Exch.exch_state=="Ask":
  745. Exch.provider_id = None
  746. elif Exch.exch_state=="Proposal":
  747. Exch.asker_id = None
  748. DBSession.merge(Exch)
  749. elif action=='deal':
  750. # ask to deal the exchange
  751. if Exch.exch_state=="Ask":
  752. Exch.provider_id = request.user.uid
  753. elif Exch.exch_state=="Proposal":
  754. Exch.asker_id = request.user.uid
  755. # Return javascript to parent page
  756. response = render_to_response('jm2l:templates/modals_js.mako',
  757. {'modtype':modtype, 'action':action},
  758. request=request)
  759. response.content_type = 'text/javascript'
  760. return response
  761. else:
  762. MainTab = {
  763. 'Exchanges':Exchange,
  764. 'Type':modtype[-1:],
  765. 'reload':True,
  766. 'logged_in':request.authenticated_userid
  767. }
  768. return MainTab
  769. @view_config(route_name='miam')
  770. def miam(request):
  771. if request.user is None:
  772. # Don't answer to users that aren't logged
  773. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  774. miam_form = MiamForm(request.POST, request.user, meta={'csrf_context': request.session})
  775. if request.method == 'POST' and miam_form.validate():
  776. FicheSejour = Sejour.by_user(request.user.uid, CurrentYear)
  777. if FicheSejour:
  778. Update=True
  779. else:
  780. FicheSejour = Sejour()
  781. FicheSejour.created = datetime.datetime.now()
  782. Update=False
  783. Repas=0
  784. for num, item in enumerate(['RepasVendredi', 'RepasSamediMidi', 'RepasSamediSoir']):
  785. if request.params.get(item)==u"1":
  786. Repas += 2**num
  787. FicheSejour.repas = Repas
  788. FicheSejour.repas_allerg = request.params.get('Allergies')
  789. FicheSejour.repas_contr = request.params.get('Contraintes')
  790. FicheSejour.user_id = request.user.uid
  791. FicheSejour.for_year = CurrentYear
  792. if Update:
  793. DBSession.merge(FicheSejour)
  794. else:
  795. DBSession.add(FicheSejour)
  796. request.session.flash(('info',u'Votre fiche a été mise à jour avec succès'))
  797. else:
  798. request.session.flash(('error',u'Un problème est survenu'))
  799. return HTTPFound(location='/MesJM2L#Miam')
  800. @view_config(route_name='sejour')
  801. def sejour(request):
  802. if request.user is None:
  803. # Don't answer to users that aren't logged
  804. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  805. if request.method == 'POST':
  806. FicheSejour = Sejour.by_user(request.user.uid, CurrentYear)
  807. if FicheSejour:
  808. Update=True
  809. else:
  810. FicheSejour = Sejour()
  811. FicheSejour.created = datetime.datetime.now()
  812. Update=False
  813. FicheSejour.user_id = request.user.uid
  814. FicheSejour.last_change = datetime.datetime.now()
  815. FicheSejour.for_year = CurrentYear
  816. # Arrival
  817. ArrDate = datetime.datetime.strptime(request.params.get('Arrival:Day'),"%d/%m/%y")
  818. ArrTime = datetime.datetime.strptime(request.params.get('Arrival:Hour'),"%H:%M")
  819. FicheSejour.arrival_time = datetime.datetime.combine(ArrDate.date(), ArrTime.time())
  820. ArrivalCheck=0
  821. for num, item in enumerate(['Arrival:PMR', 'Arrival:Cov', 'Arrival:Bras', 'Arrival:Other']):
  822. if request.params.get(item):
  823. ArrivalCheck += 2**num
  824. FicheSejour.arrival_check = ArrivalCheck
  825. FicheSejour.arrival_text = request.params.get('Arrival:Comment')
  826. FicheSejour.arrival_place = request.params.get('Arrival:Place')
  827. # Departure
  828. DepDate = datetime.datetime.strptime(request.params.get('Departure:Day'),"%d/%m/%y")
  829. DepTime = datetime.datetime.strptime(request.params.get('Departure:Hour'),"%H:%M")
  830. FicheSejour.depart_time = datetime.datetime.combine(DepDate.date(), DepTime.time())
  831. DepartCheck=0
  832. for num, item in enumerate(['Departure:PMR', 'Departure:Cov', 'Departure:Bras', 'Departure:Other']):
  833. if request.params.get(item):
  834. DepartCheck += 2**num
  835. FicheSejour.depart_check = DepartCheck
  836. FicheSejour.depart_text = request.params.get('Departure:Comment')
  837. FicheSejour.depart_place = request.params.get('Departure:Place')
  838. if Update:
  839. DBSession.merge(FicheSejour)
  840. request.session.flash(('info',u'Vos modifications de séjour ont été pris en compte.'))
  841. else:
  842. DBSession.add(FicheSejour)
  843. request.session.flash(('info',u'\\o/ Votre séjour est enregistré ! Complétez la partie Logistique.'))
  844. return HTTPFound(location='/MesJM2L#Sejour')
  845. @view_config(route_name='orga')
  846. def orga(request):
  847. if request.user is None:
  848. # Don't answer to users that aren't logged
  849. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  850. if request.method == 'POST':
  851. FicheSejour = Sejour.by_user(request.user.uid, CurrentYear)
  852. UpdateOrga=False
  853. if FicheSejour:
  854. Update=True
  855. if FicheSejour.orga_part:
  856. UpdateOrga=True
  857. else:
  858. FicheSejour = Sejour()
  859. FicheSejour.created = datetime.datetime.now()
  860. Update=False
  861. FicheSejour.user_id = request.user.uid
  862. FicheSejour.last_change = datetime.datetime.now()
  863. FicheSejour.for_year = CurrentYear
  864. OrgaPart=0
  865. for item in request.params:
  866. try:
  867. nb = int(item[1:])
  868. except:
  869. continue
  870. OrgaPart += 2**nb
  871. FicheSejour.orga_part = OrgaPart
  872. if UpdateOrga:
  873. request.session.flash(('info',u'Vos modifications de participation à l\'organisation ont été pris en compte.'))
  874. else:
  875. request.session.flash(('info',u'\\o/ Votre participation à l\'organisation est enregistrée !'))
  876. if Update:
  877. DBSession.merge(FicheSejour)
  878. else:
  879. DBSession.add(FicheSejour)
  880. return HTTPFound(location='/MesJM2L#Organisation')
  881. @view_config(route_name='vote_logo')
  882. def vote_logo(request):
  883. if request.user is None:
  884. # Don't answer to users that aren't logged
  885. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  886. else:
  887. vote = int(request.matchdict.get('num', -1))
  888. come = request.params.get('come_from')
  889. if vote:
  890. request.user.vote_logo=vote
  891. DBSession.merge(request.user)
  892. request.session.flash(('info',u'Votre vote à été pris en compte.'))
  893. return HTTPFound('/')
  894. else:
  895. request.session.flash(('warning',u"Votre vote n'a été pris en compte."))
  896. if come:
  897. return HTTPFound(location=come)
  898. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  899. @view_config(route_name='list_users_csv', renderer="string")
  900. def list_users_csv(request):
  901. for_year = int(request.matchdict.get('year', CurrentYear))
  902. if request.user is None:
  903. # Don't answer to users that aren't logged
  904. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  905. if not request.user.Staff:
  906. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  907. stmt = (DBSession.query(Sejour).filter(Sejour.for_year==for_year)).subquery()
  908. # stmt_event = (DBSession.query(User_Event).filter()
  909. adalias = aliased(Sejour, stmt)
  910. Data = DBSession.query(User, adalias ) \
  911. .outerjoin(adalias)\
  912. .order_by(User.slug)\
  913. .all()
  914. FileHandle = StringIO.StringIO()
  915. fileWriter = csv.writer(FileHandle, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
  916. fileWriter.writerow(["Identifiant_JM2L", "Nom", "Prenom", "Status_%s" % for_year ])
  917. for user, sejour in Data:
  918. tab_identifier = [user.slug, user.nom.encode('utf-8'), user.prenom.encode('utf-8'), '']
  919. if user.is_IntervenantOnYear(CurrentYear):
  920. tab_identifier[3] = "Intervenant"
  921. elif user.Staff:
  922. tab_identifier[3] = "Staff"
  923. elif sejour and sejour.orga_part:
  924. tab_identifier[3] = "Bénévole"
  925. elif sejour:
  926. tab_identifier[3] = "Visiteur"
  927. else:
  928. continue
  929. fileWriter.writerow(tab_identifier)
  930. return Response(app_iter=FileHandle.getvalue(), content_type="text/csv")
  931. @view_config(route_name='list_users', renderer="jm2l:templates/Participant/list_users.mako")
  932. def list_users(request):
  933. for_year = int(request.matchdict.get('year', CurrentYear))
  934. if request.user is None:
  935. # Don't answer to users that aren't logged
  936. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  937. if not request.user.Staff:
  938. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  939. stmt = (DBSession.query(Sejour).filter(Sejour.for_year==for_year)).subquery()
  940. adalias = aliased(Sejour, stmt)
  941. Data = DBSession.query(User, adalias ) \
  942. .outerjoin(adalias)\
  943. .all()
  944. Repas = DBSession.query(Sejour.repas) \
  945. .filter(Sejour.for_year == for_year ) \
  946. .all()
  947. DicRepas = {"Ven":0, "Midi":0, "Soir":0}
  948. for r in Repas:
  949. if r[0] is None:
  950. continue
  951. if (r[0] & 1 == 1): DicRepas["Ven"]+=1
  952. if (r[0] & 2 == 2): DicRepas["Midi"]+=1
  953. if (r[0] & 4 == 4): DicRepas["Soir"]+=1
  954. return { 'Users':Data, 'UserEvent' : User_Event, "DicRepas":DicRepas, "for_year": for_year }
  955. @view_config(route_name='list_orga', renderer="jm2l:templates/Participant/list_orga.mako")
  956. def list_orga(request):
  957. for_year = int(request.matchdict.get('year', CurrentYear))
  958. if request.user is None:
  959. # Don't answer to users that aren't logged
  960. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  961. if not request.user.Staff:
  962. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  963. Data = DBSession.query(User, Sejour)\
  964. .outerjoin(Sejour)\
  965. .filter(Sejour.for_year == for_year)\
  966. .all()
  967. return { 'Users':Data }
  968. @view_config(route_name='drop_sejour')
  969. def drop_sejour(request):
  970. if request.user is None:
  971. # Don't answer to users that aren't logged
  972. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  973. # Feed FicheSejour if any
  974. FicheSejour = Sejour.by_user(request.user.uid, CurrentYear)
  975. if FicheSejour:
  976. DBSession.delete(FicheSejour)
  977. request.session.flash(('warning', u'Votre participation %s a été supprimé avec succès.' % CurrentYear ))
  978. else:
  979. raise HTTPNotFound()
  980. return HTTPFound(location='/MesJM2L#Sejour')
  981. @view_config(route_name='jm2l', renderer="jm2l:templates/jm2l.mako")
  982. def jm2l_page(request):
  983. if request.user is None:
  984. # Don't answer to users that aren't logged
  985. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  986. UserNum = request.params.get('user')
  987. if UserNum:
  988. profil = User.by_id(int(UserNum))
  989. if not profil:
  990. raise HTTPNotFound()
  991. if not request.user.Staff:
  992. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  993. else:
  994. profil = request.user
  995. FicheSejour = Sejour()
  996. FicheSejour.created = datetime.datetime.now()
  997. # Build Form
  998. profil_form = ProfilForm(request.POST, profil, meta={'csrf_context': request.session})
  999. miam_form = MiamForm(request.POST, profil, meta={'csrf_context': request.session})
  1000. # Feed FicheSejour if any
  1001. FicheSejour = Sejour.by_user(profil.uid, CurrentYear)
  1002. if FicheSejour:
  1003. if FicheSejour.repas is not None:
  1004. for num, item in enumerate(['RepasVendredi', 'RepasSamediMidi', 'RepasSamediSoir']):
  1005. if FicheSejour.repas & 2**num:
  1006. miam_form._fields[item].data = "1"
  1007. else:
  1008. miam_form._fields[item].data = "0"
  1009. miam_form._fields['Allergies'].data = FicheSejour.repas_allerg
  1010. miam_form._fields['Contraintes'].data = FicheSejour.repas_contr
  1011. if request.method == 'POST' and profil_form.validate():
  1012. ToDelete = list()
  1013. # First, we remove entries no more present
  1014. for obj in profil_form.tiersship.object_data:
  1015. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  1016. profil_form.tiersship.entries )
  1017. if not MatchEntry:
  1018. ToDelete.append(obj)
  1019. # Then, it's time to consider new entries
  1020. for entry in profil_form.tiersship.entries:
  1021. if entry.object_data is None:
  1022. TmpUser = User_Tiers()
  1023. entry.object_data = TmpUser
  1024. profil.tiersship.append(TmpUser)
  1025. profil_form.tiersship.object_data = profil.tiersship
  1026. profil_form.populate_obj(profil)
  1027. # We should remove it as it's not in original data
  1028. for obj in ToDelete:
  1029. #profil.tiersship.remove(obj)
  1030. DBSession.delete(obj)
  1031. profil.last_change = datetime.datetime.utcnow()
  1032. profil.slug = slugify(remove_accents('%s %s' % (profil.prenom, profil.nom)).lower().strip())
  1033. DBSession.merge(profil)
  1034. request.session.flash(('info',u'Votre fiche a été mise à jour avec succès'))
  1035. MainTab = {'participer':'active',
  1036. 'Places':Place.get_list(False),
  1037. 'DBTiers':Tiers,
  1038. 'DBTiersOpt':TiersOpt,
  1039. 'Exchanges':Exchange,
  1040. 'profil_form':profil_form,
  1041. 'miam_form':miam_form,
  1042. 'uprofil':profil,
  1043. 'logged_in':request.authenticated_userid
  1044. }
  1045. return MainTab
  1046. @view_config(route_name='modal', renderer="jm2l:templates/modals.mako")
  1047. def Modal(request):
  1048. year = int(request.matchdict.get('year', None))
  1049. modtype = request.matchdict.get('modtype', None)
  1050. uid = int(request.matchdict.get('id', -1))
  1051. session = request.session
  1052. if modtype=='Password':
  1053. form = UserPasswordForm(request.POST, request.user, meta={'csrf_context': request.session})
  1054. if request.method == 'POST' and form.validate():
  1055. response = render_to_response('jm2l:templates/modals_js.mako',
  1056. {'modtype':modtype},
  1057. request=request)
  1058. request.user.password = form.password.data
  1059. DBSession.merge(request.user)
  1060. response.content_type = 'text/javascript'
  1061. return response
  1062. if modtype=='UserPicture':
  1063. form = None
  1064. if request.method == 'POST':
  1065. response = render_to_response('jm2l:templates/modals_js.mako',
  1066. {'modtype':modtype},
  1067. request=request)
  1068. response.content_type = 'text/javascript'
  1069. return response
  1070. if modtype=='Place':
  1071. if uid>0:
  1072. place = Place.by_id(uid)
  1073. if not place:
  1074. raise HTTPNotFound()
  1075. form = PlaceUpdateForm(request.POST, place, meta={'csrf_context': request.session})
  1076. else:
  1077. place = Place()
  1078. form = PlaceCreateForm(request.POST, meta={'csrf_context': request.session})
  1079. if request.method == 'POST' and form.validate():
  1080. form.populate_obj(place)
  1081. place.created_by=request.user.uid
  1082. if uid>0:
  1083. DBSession.merge(place)
  1084. else:
  1085. DBSession.add(place)
  1086. response = render_to_response('jm2l:templates/modals_js.mako',
  1087. {'modtype':modtype},
  1088. request=request)
  1089. response.content_type = 'text/javascript'
  1090. return response
  1091. if modtype in ['AskC', 'AskH', 'AskM', 'PropC', 'PropH', 'PropM']:
  1092. if uid>0:
  1093. Exch = Exchange.by_id(uid)
  1094. if not Exch:
  1095. raise HTTPNotFound()
  1096. if modtype in ['AskC','PropC']:
  1097. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  1098. start_place = Exch.Itin.start_place,
  1099. arrival_place = Exch.Itin.arrival_place,
  1100. Hour_start = Exch.start_time.strftime("%H:%M"),
  1101. Day_start = Exch.start_time.strftime("%w"),
  1102. exch_id = uid, meta={'csrf_context': request.session}
  1103. )
  1104. elif modtype in ['AskM','PropM']:
  1105. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  1106. description = Exch.description,
  1107. exch_categ = Exch.exch_categ,
  1108. Hour_start = Exch.start_time.strftime("%H:%M"),
  1109. Day_start = Exch.start_time.strftime("%w"),
  1110. Hour_end = Exch.end_time.strftime("%H:%M"),
  1111. Day_end = Exch.end_time.strftime("%w"),
  1112. exch_id = uid, meta={'csrf_context': request.session}
  1113. )
  1114. elif modtype in ['AskH','PropH']:
  1115. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  1116. description = Exch.description,
  1117. exch_categ = Exch.exch_categ,
  1118. Day_start = Exch.start_time.strftime("%w"),
  1119. exch_id = uid, meta={'csrf_context': request.session}
  1120. )
  1121. # Itinerary, first get itinerary
  1122. if 0:
  1123. form.itin.form.start_place.data = Exch.Itin.start_place
  1124. form.itin.form.arrival_place.data = Exch.Itin.arrival_place
  1125. form.dateform.form.Hour.data = Exch.start_time.strftime("%H:%M")
  1126. form.dateform.form.Day.data = Exch.start_time.strftime("%w")
  1127. form.exch_id.data = uid
  1128. else:
  1129. Exch = Exchange()
  1130. form = globals()["%sForm" % modtype](request.POST, meta={'csrf_context': request.session})
  1131. if modtype in ['AskC', 'PropC']:
  1132. # Put some place on form
  1133. Places = DBSession.query(Place.place_id, Place.display_name)\
  1134. .order_by('name').all()
  1135. form.start_place.choices = Places
  1136. form.arrival_place.choices = Places
  1137. if modtype in ['PropH']:
  1138. form.exch_categ.choices = DBSession.query( Exchange_Cat.cat_id, Exchange_Cat.exch_subtype)\
  1139. .filter( Exchange_Cat.exch_type=='H' ).all()
  1140. form.place_id.choices = DBSession.query( Place.place_id, Place.display_name)\
  1141. .filter( Place.created_by==request.user.uid ).all()
  1142. if modtype in ['AskM', 'PropM']:
  1143. form.exch_categ.choices = DBSession.query( Exchange_Cat.cat_id, Exchange_Cat.exch_subtype)\
  1144. .filter( Exchange_Cat.exch_type=='M' ).all()
  1145. if request.method == 'POST' and form.validate():
  1146. # Form has been validated, it's time to create our Exchange
  1147. Exch.for_year = year
  1148. Exch.exch_state = {'Ask':'Ask', 'Prop':'Proposal'}[modtype[:-1]]
  1149. Exch.exch_type = modtype[-1:]
  1150. if modtype in ['AskC', 'PropC']:
  1151. # Itinerary, first Let's see if itinerary exist
  1152. Itinerary = DBSession.query(Itineraire)\
  1153. .filter(Itineraire.start_place==form.start_place.data) \
  1154. .filter(Itineraire.arrival_place==form.arrival_place.data) \
  1155. .filter(Itineraire.tr_voiture==True) \
  1156. .first()
  1157. if not Itinerary: # Not exist yet !
  1158. Itinerary = Itineraire(start_place=form.start_place.data, \
  1159. arrival_place=form.arrival_place.data, \
  1160. tr_voiture=True, \
  1161. created_by=1
  1162. )
  1163. DBSession.add(Itinerary)
  1164. DBSession.flush()
  1165. Exch.itin_id = Itinerary.itin_id
  1166. # Start Time
  1167. StartEvent = DBSession.query(JM2L_Year.start_time).filter(JM2L_Year.year_uid==year).first()
  1168. Week = StartEvent[0].strftime("%W")
  1169. # populate
  1170. form.populate_obj(Exch)
  1171. if modtype in ['AskC', 'PropC']:
  1172. Exch.itin_id = Itinerary.itin_id
  1173. if form._fields.has_key("Hour_start"):
  1174. TargetTime = datetime.datetime.strptime('%d %d %d %s' % (year, int(Week), \
  1175. int(form.Day_start.data), form.Hour_start.data), "%Y %W %w %H:%M")
  1176. Exch.start_time = TargetTime
  1177. elif form._fields.has_key("Day_start"):
  1178. TargetTime = datetime.datetime.strptime('%d %d %d' % (year, int(Week), \
  1179. int(form.Day_start.data)), "%Y %W %w")
  1180. Exch.start_time = TargetTime
  1181. if form._fields.has_key("Hour_end"):
  1182. TargetTime = datetime.datetime.strptime('%d %d %d %s' % (year, int(Week), \
  1183. int(form.Day_end.data), form.Hour_end.data), "%Y %W %w %H:%M")
  1184. Exch.end_time = TargetTime
  1185. elif form._fields.has_key("Day_end"):
  1186. TargetTime = datetime.datetime.strptime('%d %d %d' % (year, int(Week), \
  1187. int(form.Day_end.data)), "%Y %W %w")
  1188. Exch.end_time = TargetTime
  1189. Exch.last_change = datetime.datetime.utcnow()
  1190. if Exch.exch_state=='Ask':
  1191. Exch.asker_id = request.user.uid
  1192. elif Exch.exch_state=='Proposal':
  1193. Exch.provider_id = request.user.uid
  1194. #print vars(form.itin.form)
  1195. if uid>0:
  1196. DBSession.merge(Exch)
  1197. else:
  1198. DBSession.add(Exch)
  1199. response = render_to_response('jm2l:templates/modals_js.mako',
  1200. {'modtype':modtype},
  1201. request=request)
  1202. response.content_type = 'text/javascript'
  1203. return response
  1204. # Fallback to HTML Display with errors
  1205. return {'modtype':modtype, 'form':form, 'update':uid>0,
  1206. 'logged_in':request.authenticated_userid }
  1207. if modtype in ['ShowC', 'ShowH', 'ShowM']:
  1208. if uid>0:
  1209. Exch = Exchange.by_id(uid)
  1210. if not Exch:
  1211. raise HTTPNotFound()
  1212. else:
  1213. raise HTTPNotFound()
  1214. # Show Details around the Current Exchange
  1215. return {'modtype':modtype, 'Exch':Exch, 'logged_in':request.authenticated_userid }
  1216. MainTab = {'modtype':modtype, 'form':form, 'update':uid>0, 'uid':uid,
  1217. 'DisplayYear':year, 'session':session,
  1218. 'logged_in':request.authenticated_userid }
  1219. return MainTab
  1220. @view_config(route_name='participer', renderer="jm2l:templates/Participer.mako")
  1221. def participer(request):
  1222. session = request.session
  1223. session['year'] = CurrentYear
  1224. TmpUsr = User()
  1225. form = UserRegisterForm(request.POST, TmpUsr, meta={'csrf_context': request.session})
  1226. MyLink=None
  1227. if request.method == 'POST' and form.validate():
  1228. # Prepare mailer
  1229. form.populate_obj(TmpUsr)
  1230. TmpUsr.nom = TmpUsr.nom.capitalize()
  1231. TmpUsr.prenom = TmpUsr.prenom.capitalize()
  1232. TmpUsr.slug = slugify(remove_accents('%s %s' % (form.prenom.data, form.nom.data)).lower().strip())
  1233. TmpUsr.password = TmpUsr.my_hash
  1234. if len(TmpUsr.slug):
  1235. CheckExist = DBSession.query(User)\
  1236. .filter(User.slug==TmpUsr.slug)\
  1237. .first()
  1238. else:
  1239. CheckExist=None
  1240. if CheckExist:
  1241. MyLink = CheckExist.my_hash
  1242. NewUser = CheckExist
  1243. else:
  1244. DBSession.add(TmpUsr)
  1245. DBSession.flush()
  1246. MyLink = TmpUsr.my_hash
  1247. NewUser = TmpUsr
  1248. # Send the Welcome Mail
  1249. mailer = request.registry['mailer']
  1250. # Prepare Plain Text Message :
  1251. Mail_template = Template(filename='jm2l/templates/mail_plain.mako')
  1252. mail_plain = Mail_template.render(request=request, User=NewUser, action="Welcome")
  1253. # Prepare HTML Message :
  1254. Mail_template = Template(filename='jm2l/templates/mail_html.mako')
  1255. mail_html = Mail_template.render(request=request, User=NewUser, action="Welcome")
  1256. # Prepare Message
  1257. message = Message(subject="[JM2L] Mon inscription au site web JM2L",
  1258. sender="contact@jm2l.linux-azur.org",
  1259. recipients=[NewUser.mail or TmpUsr.mail],
  1260. body=mail_plain, html=mail_html)
  1261. message.add_bcc("spam@style-python.fr")
  1262. mailer.send(message)
  1263. request.session.flash(('info',u"Un mail vous a été envoyé afin de continuer votre quête !"))
  1264. MainTab = {'programme':'','presse':'', 'plan':'',
  1265. 'participer':'active', 'form':form, "link": MyLink,
  1266. 'logged_in':request.authenticated_userid }
  1267. return MainTab
  1268. @view_config(route_name='year')
  1269. def change_year(request):
  1270. year = int(request.matchdict.get('year', -1))
  1271. session = request.session
  1272. if year>-1:
  1273. session['year'] = year
  1274. return HTTPFound(location='/%s/' % year)
  1275. return HTTPFound(location=request.route_url('home', year=''))
  1276. @view_config(route_name='pict_user', renderer="jm2l:templates/Profil/pict_user.mako")
  1277. def pict_user(request):
  1278. return {"uprofil":request.user}
  1279. @view_config(route_name='pict_salle', renderer="jm2l:templates/Salles/pict_salle.mako")
  1280. def pict_salle(request):
  1281. salle_id = int(request.matchdict.get('salle_id', -1))
  1282. return {"Salles":Salles, "IdSalle":salle_id}
  1283. @view_config(route_name='event', renderer="jm2l:templates/view_event.mako")
  1284. def show_event(request):
  1285. year = int(request.matchdict.get('year', -1))
  1286. event_id = request.matchdict.get('event_id')
  1287. if event_id.isdigit():
  1288. TheEvent = Event.by_id(event_id)
  1289. if TheEvent is None:
  1290. raise HTTPNotFound()
  1291. else:
  1292. TheEvent = Event.by_slug(event_id, year)
  1293. if TheEvent is None:
  1294. raise HTTPNotFound()
  1295. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1296. 'event':TheEvent, 'logged_in':request.authenticated_userid, "Salles":Salles }
  1297. return MainTab
  1298. @view_config(route_name='link_event_user')
  1299. def link_event_user(request):
  1300. """ Get user and add it to current event """
  1301. if request.user is None:
  1302. # Don't answer to users that aren't logged
  1303. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1304. year = int(request.matchdict.get('year', -1))
  1305. form = AddIntervenant(request.POST, meta={'csrf_context': request.session})
  1306. intervention = request.matchdict.get('intervention', None)
  1307. TargetEvent = Event.by_id(form.event_uid.data)
  1308. Exist = User.by_id(form.intervenant.data)
  1309. if not Exist:
  1310. request.session.flash(('error',u"Une erreur s'est produite lors de l'ajout de votre intervenant !"))
  1311. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1312. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  1313. else:
  1314. TargetUser = Exist
  1315. uev = User_Event(year_uid=year, role=u"Animateur d'un évènement JM2L", user_uid=TargetUser.uid)
  1316. TargetEvent.interventions.append( uev )
  1317. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1318. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  1319. @view_config(route_name='link_event_tiers')
  1320. def link_event_tiers(request):
  1321. """ Create user if not exist, add it to current event """
  1322. if request.user is None:
  1323. # Don't answer to users that aren't logged
  1324. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1325. year = int(request.matchdict.get('year', -1))
  1326. form = AddTiers(request.POST, meta={'csrf_context': request.session})
  1327. intervention = request.matchdict.get('intervention', None)
  1328. TargetEvent = Event.by_id(form.event_uid.data)
  1329. Exist = Tiers.by_id(form.tiers.data)
  1330. if not Exist:
  1331. request.session.flash(('error',u"Une erreur s'est produite lors de l'ajout de votre entité !"))
  1332. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1333. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  1334. else:
  1335. TargetTiers = Exist
  1336. Matching = DBSession.query(Role_Tiers)\
  1337. .filter(Role_Tiers.year_uid==year)\
  1338. .filter(Role_Tiers.tiers_role=="Exposant")\
  1339. .filter(Role_Tiers.tiers_uid==TargetTiers.uid)\
  1340. .filter(Role_Tiers.event_uid==TargetEvent.uid)\
  1341. .all()
  1342. if len(Matching)==0:
  1343. tev = Role_Tiers(year_uid=year, tiers_role="Exposant", tiers_uid=TargetTiers.uid, event_uid=TargetEvent.uid)
  1344. DBSession.add(tev)
  1345. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1346. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid), _anchor="Tiers"))
  1347. @view_config(route_name='delete_link_u')
  1348. def delete_link_event_user(request):
  1349. """ Create user if not exist, add it to current event """
  1350. if request.user is None:
  1351. # Don't answer to users that aren't logged
  1352. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1353. year = int(request.matchdict.get('year', -1))
  1354. intervention = request.matchdict.get('intervention', None)
  1355. TargetEvent = Event.by_id( request.params.get('eid') )
  1356. Exist = User.by_id( request.params.get('uid') )
  1357. if not Exist:
  1358. request.session.flash(('error',u"Une erreur s'est produite lors de votre suppression !"))
  1359. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1360. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  1361. else:
  1362. TargetUser = Exist
  1363. Matching = DBSession.query(User_Event)\
  1364. .filter(User_Event.year_uid==year)\
  1365. .filter(User_Event.user_uid==TargetUser.uid)\
  1366. .filter(User_Event.event_uid==TargetEvent.uid)\
  1367. .all()
  1368. if len(Matching)==0:
  1369. request.session.flash(('error',u"Une erreur s'est produite lors de la suppression !"))
  1370. else:
  1371. for item in Matching:
  1372. DBSession.delete(item)
  1373. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1374. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid), _anchor="Tiers"))
  1375. @view_config(route_name='delete_link_t')
  1376. def delete_link_event_tiers(request):
  1377. """ Create user if not exist, add it to current event """
  1378. if request.user is None:
  1379. # Don't answer to users that aren't logged
  1380. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1381. year = int(request.matchdict.get('year', -1))
  1382. intervention = request.matchdict.get('intervention', None)
  1383. TargetEvent = Event.by_id( request.params.get('uid') )
  1384. Exist = Tiers.by_id( request.params.get('tid') )
  1385. if not Exist:
  1386. request.session.flash(('error',u"Une erreur s'est produite lors de l'ajout de votre entité !"))
  1387. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1388. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  1389. else:
  1390. TargetTiers = Exist
  1391. Matching = DBSession.query(Role_Tiers)\
  1392. .filter(Role_Tiers.year_uid==year)\
  1393. .filter(Role_Tiers.tiers_role=="Exposant")\
  1394. .filter(Role_Tiers.tiers_uid==TargetTiers.uid)\
  1395. .filter(Role_Tiers.event_uid==TargetEvent.uid)\
  1396. .all()
  1397. if len(Matching)==0:
  1398. request.session.flash(('error',u"Une erreur s'est produite lors de la suppression de votre entité !"))
  1399. else:
  1400. for item in Matching:
  1401. DBSession.delete(item)
  1402. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1403. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid), _anchor="Tiers"))
  1404. @view_config(route_name='delete_event')
  1405. def delete_event(request):
  1406. if request.user is None:
  1407. # Don't answer to users that aren't logged
  1408. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1409. year = int(request.matchdict.get('year', -1))
  1410. event_id = request.matchdict.get('event_id')
  1411. intervention = request.matchdict.get('intervention', None)
  1412. # Check intervention
  1413. if not intervention in ['Stand', 'Table_ronde', 'Atelier', 'Conference', 'Concert']:
  1414. raise HTTPNotFound(u"Ce type d'évènement n'est pas reconnu")
  1415. # We should remove all links before to remove the event
  1416. if event_id.isdigit():
  1417. TheEvent = Event.by_id(event_id)
  1418. if TheEvent is None:
  1419. raise HTTPNotFound(u"Cette réference n'existe pas")
  1420. else:
  1421. TheEvent = Event.by_slug(event_id, year)
  1422. if TheEvent is None:
  1423. raise HTTPNotFound(u"Cette réference n'existe pas")
  1424. # Remove Roles
  1425. Roles_Link = DBSession.query(Role_Tiers).filter(Role_Tiers.event_uid==TheEvent.uid).all()
  1426. for tmp in Roles_Link:
  1427. DBSession.delete(tmp)
  1428. # Remove Intervenant
  1429. User_Link = DBSession.query(User_Event).filter(User_Event.event_uid==TheEvent.uid).all()
  1430. for tmp in User_Link:
  1431. DBSession.delete(tmp)
  1432. # Remove attachment if any
  1433. SRCPath = path.join('jm2l/upload', *(IMAGEPATH + ['event'] + [ str(year) ] + [ TheEvent.slug ]) )
  1434. shutil.rmtree(SRCPath, ignore_errors=True)
  1435. # Remove Event
  1436. DBSession.delete(TheEvent)
  1437. return HTTPFound(location=request.route_url('jm2l', _anchor="Interventions"))
  1438. @view_config(route_name='edit_event', renderer="jm2l:templates/edit_event.mako")
  1439. def edit_event(request):
  1440. if request.user is None:
  1441. # Don't answer to users that aren't logged
  1442. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1443. year = int(request.matchdict.get('year', -1))
  1444. event_id = request.matchdict.get('event_id')
  1445. intervention = request.matchdict.get('intervention', None)
  1446. IntervLabel = intervention.replace('_',' ').lower()
  1447. if intervention=='Conference':
  1448. IntervLabel = u'conférence'
  1449. elif intervention=='Table_ronde':
  1450. IntervLabel = u'Table ronde'
  1451. # Check intervention
  1452. if not intervention in ['Stand', 'Table_ronde', 'Atelier', 'Conference', 'Concert']:
  1453. raise HTTPNotFound(u"Ce type d'évènement n'est pas reconnu")
  1454. TheYear = DBSession.query(JM2L_Year)\
  1455. .filter(JM2L_Year.year_uid==year)\
  1456. .first()
  1457. # Check year avaibility
  1458. if not TheYear:
  1459. raise HTTPNotFound(u"Cette année n'est pas pris en charge")
  1460. # Generate Timeslots for current year
  1461. TimeSlots = list(enumerate( [ x.strftime('%a %d %b %H:%M') for x in
  1462. TheYear.AvailableTimeSlots ] ))
  1463. if event_id:
  1464. # We try to update an existing record
  1465. if event_id.isdigit():
  1466. TheEvent = Event.by_id(event_id)
  1467. if TheEvent is None:
  1468. raise HTTPNotFound(u"Cette réference n'existe pas")
  1469. else:
  1470. TheEvent = Event.by_slug(event_id, year)
  1471. if TheEvent is None:
  1472. raise HTTPNotFound(u"Cette réference n'existe pas")
  1473. if request.user is None or not (request.user.Staff or request.user in TheEvent.intervenants):
  1474. raise HTTPForbidden(u"Vous n'êtes pas identifié comme étant un participant à cette intervention.")
  1475. # Compute some field value from selected event
  1476. if TheEvent.start_time in TheYear.AvailableTimeSlots:
  1477. start_sel = TheYear.AvailableTimeSlots.index(TheEvent.start_time)
  1478. else:
  1479. start_sel = len(TimeSlots)
  1480. TimeSlots.append( (len(TimeSlots), TheEvent.start_time.strftime('%a %d %b %H:%M')))
  1481. duration = (TheEvent.end_time - TheEvent.start_time).total_seconds()/60
  1482. end = TheEvent.start_time + datetime.timedelta(minutes=duration)
  1483. # prepare the form with update
  1484. form = ConfUpdateForm(request.POST, TheEvent, start_sel=start_sel, duration=duration, end_time=end,
  1485. meta={'csrf_context': request.session} )
  1486. # Customize labels
  1487. form.name.label.text += IntervLabel
  1488. form.description.label.text += IntervLabel
  1489. # Each event can get severals members
  1490. formAdd = AddIntervenant(event_uid=TheEvent.uid)
  1491. # Build list of intervenant
  1492. # Get users from db
  1493. Users = DBSession.query(User)\
  1494. .filter(User.Staff==1)\
  1495. .order_by('nom').all()
  1496. # Put some users on form
  1497. formAdd.intervenant.choices = [(u.uid, "%s %s" % (u.nom, u.prenom))
  1498. for u in Users]
  1499. # Each event can get severals entities
  1500. formAddT = AddTiers(event_uid=TheEvent.uid)
  1501. # Build list of entities
  1502. # Get entities from db
  1503. TmpTiers = DBSession.query(Tiers)\
  1504. .order_by('name').limit(10)
  1505. # Put some entities on form
  1506. formAddT.tiers.choices = [(u.uid, "%s %s" % (u.nom, u.prenom))
  1507. for u in Users]
  1508. else:
  1509. TheEvent = Event()
  1510. # prepare the form for creation
  1511. form = ConfCreateForm(request.POST,
  1512. event_type=intervention,
  1513. for_year=str(year), meta={'csrf_context': request.session}
  1514. )
  1515. # Customize labels
  1516. form.name.label.text += IntervLabel
  1517. form.description.label.text += IntervLabel
  1518. duration=60
  1519. # No intervenant
  1520. formAdd = None
  1521. formAddT = None
  1522. SalleDispo = DBSession.query(Salles)\
  1523. .filter(Salles.year_uid==year)\
  1524. .order_by('name')
  1525. if intervention=="Conference":
  1526. form.duration.choices =[
  1527. (15,u'Lighting talk ( 5 min)'),
  1528. (30,u'Conférence (20 min)'),
  1529. (60,u'Conférence (50 min)'),
  1530. (90,u'Conférence (75 min)'),
  1531. ]
  1532. if not duration in [15, 30, 60, 90]:
  1533. form.duration.choices.append( (duration,u'Conférence (%d min)' % duration) )
  1534. if not form._fields.has_key("uid"):
  1535. form.duration.data=60
  1536. SalleDispo = SalleDispo.filter(Salles.place_type.in_(['Conference', 'MAO', 'Atelier']))
  1537. elif intervention=="Stand":
  1538. form.duration.choices =[
  1539. (8*60, u'Toute la journée'),
  1540. (4*60, u'une demi-journée')
  1541. ]
  1542. SalleDispo = SalleDispo.filter(Salles.place_type=='Stand')
  1543. elif intervention=="Atelier":
  1544. form.duration.choices = map( lambda d:(d, u'Atelier (%dh%.2d)' % (d/60, d%60) ), \
  1545. [60, 90, 120, 150, 180, 210, 240] )
  1546. if not duration in map(lambda (d,y): d, form.duration.choices):
  1547. form.duration.choices.append( (duration,u'Atelier (%dh%.2d)' % (duration/60, duration%60) ) )
  1548. SalleDispo = SalleDispo.filter(Salles.place_type.in_(['Atelier', 'MAO']))
  1549. elif intervention=="Table_ronde":
  1550. form.duration.choices = map( lambda d:(d, u'Table ronde (%dh%.2d)' % (d/60, d%60) ), \
  1551. [60, 90, 120, 150] )
  1552. if not duration in map(lambda (d,y): d, form.duration.choices):
  1553. form.duration.choices.append( (duration,u'Table ronde (%dh%.2d)' % (duration/60, duration%60) ) )
  1554. SalleDispo = SalleDispo.filter(Salles.place_type=='Table ronde')
  1555. elif intervention=="Concert":
  1556. form.duration.choices = map( lambda d:(d, u'Concert (%dh%.2d)' % (d/60, d%60) ), \
  1557. [60, 90, 120, 150, 180, 210, 240] )
  1558. if not duration in map(lambda (d,y): d, form.duration.choices):
  1559. form.duration.choices.append( (duration,u'Concert (%dh%.2d)' % (duration/60, duration%60) ) )
  1560. SalleDispo = SalleDispo.filter(Salles.place_type.in_(['Stand', 'MAO']))
  1561. else:
  1562. raise HTTPForbidden(u"Pas encore disponible.")
  1563. form.salle_uid.choices = [(s.salle_id, s.name) for s in SalleDispo]
  1564. form.start_sel.choices = TimeSlots
  1565. if request.method == 'POST' and form.validate():
  1566. form.populate_obj(TheEvent)
  1567. TheEvent.start_time = TheYear.AvailableTimeSlots[form.start_sel.data]
  1568. TheEvent.end_time = TheEvent.start_time + datetime.timedelta(minutes=form.duration.data)
  1569. # Ok, time to put in database
  1570. if not form._fields.has_key("uid"):
  1571. TheEvent.slug = unicode(slugify(TheEvent.name))
  1572. if intervention==u"Table_ronde":
  1573. TheEvent.event_type = "Table ronde"
  1574. DBSession.add(TheEvent)
  1575. # Append creator by default
  1576. if request.user.uid!=1:
  1577. uev = User_Event(year_uid=TheYear.year_uid, role=u"Animateur")
  1578. uev.user_uid = request.user.uid
  1579. TheEvent.interventions.append( uev )
  1580. DBSession.flush()
  1581. request.session.flash(('sucess',u'Votre intervention a été créee ! Vous pouvez la compléter à tout moment.'))
  1582. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1583. year=str(year), intervention=intervention, event_id=str(TheEvent.slug)))
  1584. else:
  1585. if slugify(TheEvent.name)!=TheEvent.slug:
  1586. # We should move some file as slug have been changed
  1587. # First we ensure there is no related event that already exist with that slug
  1588. CheckEvent = Event.by_slug( unicode(slugify(TheEvent.name)), year)
  1589. if CheckEvent:
  1590. request.session.flash(('warning',u'Choisissez un autre titre pour votre évènement, il est en conflit avec un autre.'))
  1591. return {'event':TheEvent, 'form':form, 'formAdd':formAdd, 'formAddT':formAddT, 'Salles':Salles }
  1592. else:
  1593. SRCPath = path.join('jm2l/upload', *(IMAGEPATH + ['event'] + [ str(year) ] + [ TheEvent.slug ]) )
  1594. TheEvent.slug=unicode(slugify(TheEvent.name))
  1595. DSTPath = path.join('jm2l/upload', *(IMAGEPATH + ['event'] + [ str(year) ] + [ TheEvent.slug ]) )
  1596. if not path.isdir(path.dirname(DSTPath)):
  1597. makedirs(path.dirname(DSTPath))
  1598. # Then we should move event attachments to the new slug (if any)
  1599. if path.exists(SRCPath):
  1600. shutil.move(SRCPath, DSTPath)
  1601. DBSession.merge(TheEvent)
  1602. request.session.flash(('sucess',u'Votre intervention a été mis à jour !'))
  1603. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1604. year=str(year), intervention=intervention, event_id=str(TheEvent.slug)))
  1605. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1606. 'event':TheEvent, 'form':form, 'formAdd':formAdd, 'formAddT':formAddT,
  1607. 'Salles':Salles }
  1608. return MainTab
  1609. @view_config(route_name='entities', renderer="jm2l:templates/list_tiers.mako")
  1610. def list_tiers(request):
  1611. Entities = dict()
  1612. EntityType = DBSession.query(TiersOpt.entity_type)\
  1613. .group_by(TiersOpt.entity_type).all()
  1614. for EType in EntityType:
  1615. Entities[EType.entity_type] = DBSession.query(Tiers).join(TiersOpt)\
  1616. .filter(TiersOpt.entity_type==EType.entity_type)\
  1617. .order_by(TiersOpt.entity_subtype, Tiers.name)
  1618. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1619. 'entities':Entities, 'logged_in':request.authenticated_userid }
  1620. return MainTab
  1621. @view_config(route_name='show_entity', renderer="jm2l:templates/view_tiers.mako")
  1622. def show_tiers(request):
  1623. tiers_type = request.matchdict.get('tiers_type')
  1624. entity_id = request.matchdict.get('entity_id')
  1625. if entity_id.isdigit():
  1626. TheTiers = Tiers.by_id(entity_id)
  1627. if TheTiers is None:
  1628. raise HTTPNotFound()
  1629. else:
  1630. TheTiers = Tiers.by_slug(entity_id)
  1631. if TheTiers is None:
  1632. raise HTTPNotFound()
  1633. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1634. 'entity':TheTiers, 'logged_in':request.authenticated_userid }
  1635. return MainTab
  1636. @view_config(route_name='delete_entity')
  1637. def delete_tiers(request):
  1638. if request.user is None:
  1639. # Don't answer to users that aren't logged
  1640. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1641. entity_id = request.matchdict.get('entity_id', None)
  1642. if entity_id:
  1643. if entity_id.isdigit():
  1644. TheTiers = Tiers.by_id(int(entity_id))
  1645. if TheTiers is None:
  1646. raise HTTPNotFound()
  1647. else:
  1648. TheTiers = Tiers.by_slug(entity_id)
  1649. if TheTiers is None:
  1650. raise HTTPNotFound()
  1651. if len(TheTiers.membership)!=0:
  1652. request.session.flash(('error', u"Vous devez supprimer tous les membres liés avant la suppression d'une entité."))
  1653. return HTTPFound(location=request.route_url('show_entity', entity_id=TheTiers.slug, tiers_type=TheTiers.get_entity_type.slug_entity_type))
  1654. if len(TheTiers.membership)!=0:
  1655. request.session.flash(('error', u"Vous devez supprimer tous les roles liés avant la suppression d'une entité."))
  1656. return HTTPFound(location=request.route_url('show_entity', entity_id=TheTiers.slug, tiers_type=TheTiers.get_entity_type.slug_entity_type))
  1657. DBSession.delete(TheTiers)
  1658. request.session.flash(('info', u"L'entité a bien été supprimée"))
  1659. return HTTPFound(location=request.route_url('entities'))
  1660. else:
  1661. raise HTTPNotFound()
  1662. @view_config(route_name='add_entity', renderer="jm2l:templates/edit_tiers.mako")
  1663. @view_config(route_name='edit_entity', renderer="jm2l:templates/edit_tiers.mako")
  1664. def edit_tiers(request):
  1665. entity_id = request.matchdict.get('entity_id', None)
  1666. TargetList = list()
  1667. if request.user is None:
  1668. # Don't answer to users that aren't logged
  1669. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1670. entity_types = DBSession.query(TiersOpt.entity_type).group_by(TiersOpt.entity_type).all()
  1671. for entity_type in entity_types:
  1672. entity_subtypes = DBSession.query(TiersOpt)\
  1673. .filter(TiersOpt.entity_type==entity_type.entity_type)\
  1674. .group_by(TiersOpt.entity_subtype).all()
  1675. ListType = [(i.uid, i.entity_subtype) for i in entity_subtypes]
  1676. TargetList.append( (entity_type.entity_type, ListType) )
  1677. if entity_id:
  1678. if entity_id.isdigit():
  1679. TheTiers = Tiers.by_id(entity_id)
  1680. if TheTiers is None:
  1681. raise HTTPNotFound()
  1682. else:
  1683. TheTiers = Tiers.by_slug(entity_id)
  1684. if TheTiers is None:
  1685. raise HTTPNotFound()
  1686. form = UpdateTiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  1687. UserOptions = DBSession.query(TiersOpt)\
  1688. .filter(TiersOpt.entity_type==TheTiers.tiers_type)\
  1689. .all()
  1690. form.tiers_type.choices = TargetList
  1691. else:
  1692. TheTiers = Tiers()
  1693. # prepare the form for creation
  1694. form = TiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  1695. form.tiers_type.choices = TargetList
  1696. UserOptions = list()
  1697. #test_form = TiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  1698. if request.method == 'POST' and form.validate():
  1699. ToDelete = list()
  1700. ToDeleteR = list()
  1701. # First, we remove entries no more present
  1702. for obj in form.membership.object_data:
  1703. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  1704. form.membership.entries )
  1705. if not MatchEntry:
  1706. ToDelete.append(obj)
  1707. # For roles too
  1708. for obj in form.roles.object_data:
  1709. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  1710. form.roles.entries )
  1711. if not MatchEntry:
  1712. ToDeleteR.append(obj)
  1713. # We should remove it as it's not in original data
  1714. for obj in ToDelete:
  1715. TheTiers.membership.remove(obj)
  1716. DBSession.delete(obj)
  1717. # For roles too
  1718. for obj in ToDeleteR:
  1719. TheTiers.roles.remove(obj)
  1720. DBSession.delete(obj)
  1721. # Then, it's time to consider new entries
  1722. for entry in form.membership.entries:
  1723. if entry.object_data is None:
  1724. TmpUser = User_Tiers()
  1725. entry.object_data = TmpUser
  1726. TheTiers.membership.append(TmpUser)
  1727. form.membership.object_data = TheTiers.membership
  1728. # For roles too
  1729. for entry in form.roles.entries:
  1730. if entry.object_data is None:
  1731. TmpRole = Role_Tiers()
  1732. entry.object_data = TmpRole
  1733. TheTiers.roles.append(TmpRole)
  1734. form.roles.object_data = TheTiers.roles
  1735. form.populate_obj(TheTiers)
  1736. # Handle Remove of accents
  1737. OriginalSlug = TheTiers.slug
  1738. if not form._fields.has_key('uid'):
  1739. TheTiers.slug = slugify(form.name.data)
  1740. TheTiers.creator_id = request.user.uid
  1741. DBSession.add(TheTiers)
  1742. DBSession.flush()
  1743. return HTTPFound(location=request.route_url('edit_entity', sep='/',
  1744. entity_id=str(TheTiers.slug), tiers_type=TheTiers.get_entity_type.entity_type))
  1745. else:
  1746. if OriginalSlug!=slugify(form.name.data):
  1747. # We should move some file as slug have been changed
  1748. # First we ensure there is no related event that already exist with that slug
  1749. CheckTiers = Tiers.by_slug( slugify(form.name.data) )
  1750. if CheckTiers:
  1751. request.session.flash(('warning',u'Attention, Choisissez un autre titre pour votre entitée, elle est en conflit avec une autre.'))
  1752. DBSession.rollback()
  1753. return HTTPFound(location=request.route_url('edit_entity', sep='/',
  1754. entity_id=str(OriginalSlug), tiers_type=TheTiers.get_entity_type.entity_type))
  1755. else:
  1756. TheTiers.slug = slugify(form.name.data)
  1757. SRCPath = path.join('jm2l/upload', *(IMAGEPATH + ['tiers'] + [ OriginalSlug ]) )
  1758. DSTPath = path.join('jm2l/upload', *(IMAGEPATH + ['tiers'] + [ TheTiers.slug ]) )
  1759. if not path.isdir(path.dirname(DSTPath)):
  1760. makedirs(path.dirname(DSTPath))
  1761. # Then we should move event attachments to the new slug (if any)
  1762. if path.exists(SRCPath):
  1763. shutil.move(SRCPath, DSTPath)
  1764. DBSession.merge(TheTiers)
  1765. return HTTPFound(location=request.route_url('show_entity', entity_id=TheTiers.slug,
  1766. tiers_type=TheTiers.get_entity_type.slug_entity_type))
  1767. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1768. 'form':form, 'DBUser':User, 'UserOptions':UserOptions,
  1769. 'logged_in':request.authenticated_userid }
  1770. return MainTab
  1771. @view_config(route_name='edit_entity_cat', renderer="jm2l:templates/edit_tiers_categ.mako")
  1772. def edit_tiers_category(request):
  1773. if request.user is None:
  1774. # Don't answer to users that aren't logged
  1775. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1776. DicResult = dict()
  1777. ListChanges = list()
  1778. if request.method == 'POST':
  1779. # Reformat data
  1780. RegExist = re.compile('collection\[(?P<slug>[\w-]+)\]\[(?P<num>\d+)\]\[(?P<id>\d+)\]')
  1781. RegTitle = re.compile('collection\[(?P<slug>[\w-]+)\]\[title]')
  1782. RegNew = re.compile('collection\[(?P<slug>[\w-]+)\]\[(?P<num>\d+)\]\[id\]')
  1783. for key, value in request.POST.iteritems():
  1784. regN= RegNew.match(key)
  1785. regT= RegTitle.match(key)
  1786. reg = RegExist.match(key)
  1787. if reg:
  1788. if not DicResult.has_key(reg.group('slug')):
  1789. DicResult[reg.group('slug')] = dict()
  1790. if DicResult[reg.group('slug')].has_key('items'):
  1791. DicResult[reg.group('slug')]['items'].append( ( int(reg.group('id')), value ) )
  1792. else:
  1793. DicResult[reg.group('slug')]['items'] = [ ( int(reg.group('id')), value ) ]
  1794. elif regN:
  1795. if not DicResult.has_key(regN.group('slug')):
  1796. DicResult[regN.group('slug')] = dict()
  1797. if DicResult[regN.group('slug')].has_key('items'):
  1798. DicResult[regN.group('slug')]['items'].append( ( 'id', value ) )
  1799. else:
  1800. DicResult[regN.group('slug')]['items'] = [ ( 'id', value ) ]
  1801. ListChanges.append(('add', 0, DicResult[regN.group('slug')]['title'], value))
  1802. elif regT:
  1803. if not DicResult.has_key(regT.group('slug')):
  1804. DicResult[regT.group('slug')] = dict()
  1805. DicResult[regT.group('slug')]['title'] = value
  1806. else:
  1807. raise
  1808. for opt in DBSession.query(TiersOpt).all():
  1809. if DicResult.has_key(opt.slug_entity_type):
  1810. found = filter( lambda (x,y): opt.uid==x,
  1811. DicResult[opt.slug_entity_type].get('items', []))
  1812. if not found:
  1813. ListChanges.append(('remove', opt.uid, opt.entity_type, opt.entity_subtype))
  1814. else:
  1815. for tst in found:
  1816. # Check changes on Cat Name
  1817. if DicResult[opt.slug_entity_type]['title']!=opt.entity_type or \
  1818. tst[1]!=opt.entity_subtype:
  1819. ListChanges.append(('changed', opt.uid,
  1820. DicResult[opt.slug_entity_type]['title'],
  1821. tst[1]))
  1822. else:
  1823. ListChanges.append(('remove', opt.uid, opt.entity_type, opt.entity_subtype))
  1824. # Do The change
  1825. for action, uid, entity, subentity in ListChanges:
  1826. if action=="changed":
  1827. opt = TiersOpt.by_id(uid)
  1828. opt.entity_type = entity
  1829. opt.entity_subtype = subentity
  1830. elif action=="remove":
  1831. opt = TiersOpt.by_id(uid)
  1832. DBSession.delete(opt)
  1833. elif action=="add":
  1834. opt = TiersOpt()
  1835. opt.entity_type = entity
  1836. opt.entity_subtype = subentity
  1837. DBSession.add(opt)
  1838. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1839. 'logged_in':request.authenticated_userid, 'TiersOpt':TiersOpt }
  1840. return MainTab
  1841. @view_config(route_name='show_user', renderer="jm2l:templates/view_user.mako")
  1842. def show_user(request):
  1843. user_slug = request.matchdict.get('user_slug', None)
  1844. if user_slug is None or len(user_slug)==0:
  1845. raise HTTPNotFound(u"Cet utilisateur n'a pas été reconnu")
  1846. # Query database
  1847. DispUser = User.by_slug(user_slug)
  1848. if DispUser is None:
  1849. raise HTTPNotFound()
  1850. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1851. 'DispUser':DispUser, 'logged_in':request.authenticated_userid }
  1852. return MainTab
  1853. #@view_config(route_name='link_user_entity')
  1854. def link_user_entity(request):
  1855. if request.user is None:
  1856. # Don't answer to users that aren't logged
  1857. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1858. uid = int(request.matchdict.get('uid', -1))
  1859. year = int(request.matchdict.get('year', -1))
  1860. user_id = int(request.matchdict.get('uid', -1))
  1861. TheTiers = Tiers.by_id(uid)
  1862. if TheTiers is None:
  1863. raise HTTPNotFound()
  1864. return HTTPFound(location=request.route_url('edit_entity', uid=uid) )
  1865. #@view_config(route_name='link_role_entity')
  1866. def link_role_entity(request):
  1867. if request.user is None:
  1868. # Don't answer to users that aren't logged
  1869. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1870. uid = int(request.matchdict.get('uid', -1))
  1871. year = int(request.matchdict.get('year', -1))
  1872. role_id = int(request.matchdict.get('role_id', -1))
  1873. TheTiers = Tiers.by_id(uid)
  1874. if TheTiers is None:
  1875. raise HTTPNotFound()
  1876. return HTTPFound(location=request.route_url('edit_entity', uid=uid) )
  1877. @forbidden_view_config()
  1878. def forbidden(reason, request):
  1879. if 'ident' in reason.detail:
  1880. request.session.flash(('info', reason.detail))
  1881. return HTTPFound(location='/sign/login?from='+request.environ['PATH_INFO'] )
  1882. else:
  1883. request.response.status = 403
  1884. return render_to_response('jm2l:templates/Errors/403.mako', { "reason":reason },
  1885. request=request)
  1886. @notfound_view_config()
  1887. def notfound(reason, request):
  1888. request.response.status = 404
  1889. return render_to_response('jm2l:templates/Errors/404.mako', { "reason":reason },
  1890. request=request)