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.
 
 
 
 
 

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