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.
 
 
 
 
 

2064 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, 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. ## =-=- 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. orig_slug = Salle.slug
  690. if not Salle:
  691. raise HTTPNotFound()
  692. form = EditSallePhyForm(request.POST, Salle, meta={'csrf_context': request.session})
  693. else:
  694. Salle = SallePhy()
  695. orig_slug = None
  696. form = SallePhyForm(request.POST, Salle, meta={'csrf_context': request.session})
  697. if request.method == 'POST' and form.validate():
  698. form.populate_obj(Salle)
  699. dest_slug = slugify(Salle.name)
  700. # Do a check in order to move attached files if any
  701. if orig_slug and orig_slug!=dest_slug:
  702. try:
  703. mp = MediaPath().move_mediapath('salle', orig_slug, dest_slug)
  704. except RuntimeError, err:
  705. request.session.flash(('error', "Le nom de cette salle est déjà utilisé : " + err.message))
  706. return {'form': form}
  707. Salle.slug = slugify(Salle.name)
  708. if 'uid' in form._fields.keys():
  709. DBSession.merge(Salle)
  710. else:
  711. DBSession.add(Salle)
  712. return HTTPFound(location=request.route_url('list_salles'))
  713. return {'form':form }
  714. @view_config(route_name='action_salle')
  715. def action_salle(request):
  716. if request.user is None:
  717. # Don't answer to users that aren't logged
  718. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  719. if not request.user.Staff:
  720. # Don't answer to users that aren't logged
  721. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  722. action = request.matchdict.get('action')
  723. salle_id = request.matchdict.get('salle_id')
  724. Salle = Salles.by_id(int(salle_id))
  725. if not Salle:
  726. raise HTTPNotFound()
  727. if action=='delete':
  728. request.session.flash(('info', u'La Salle a été supprimée !'))
  729. DBSession.delete(Salle)
  730. return HTTPFound(location=request.route_url('list_salles'))
  731. ## =-=- Here, We handle HTTP requests - User Logged Part -=-=
  732. @view_config(route_name='exchange', renderer="jm2l:templates/Logistique/Logistique.mako")
  733. def exchange(request):
  734. modtype = request.matchdict.get('modtype', None)
  735. action = request.matchdict.get('action', None)
  736. uid = int(request.matchdict.get('id', -1))
  737. Exch = Exchange.by_id(uid)
  738. if not Exch:
  739. MainTab = {
  740. 'Exchanges':Exchange,
  741. 'Type':modtype[-1:],
  742. 'reload':True,
  743. 'logged_in':request.authenticated_userid
  744. }
  745. return MainTab
  746. if action in ['delete', 'accept', 'refuse', 'deal']:
  747. if action=='delete': # delete exchange
  748. DBSession.delete(Exch)
  749. elif action=='accept': # accept exchange
  750. Exch.exch_done=True
  751. DBSession.merge(Exch)
  752. elif action=='refuse': # refuse exchange
  753. Exch.exch_done=False
  754. if Exch.exch_state=="Ask":
  755. Exch.provider_id = None
  756. elif Exch.exch_state=="Proposal":
  757. Exch.asker_id = None
  758. DBSession.merge(Exch)
  759. elif action=='deal':
  760. # ask to deal the exchange
  761. if Exch.exch_state=="Ask":
  762. Exch.provider_id = request.user.uid
  763. elif Exch.exch_state=="Proposal":
  764. Exch.asker_id = request.user.uid
  765. # Return javascript to parent page
  766. response = render_to_response('jm2l:templates/modals_js.mako',
  767. {'modtype':modtype, 'action':action},
  768. request=request)
  769. response.content_type = 'text/javascript'
  770. return response
  771. else:
  772. MainTab = {
  773. 'Exchanges':Exchange,
  774. 'Type':modtype[-1:],
  775. 'reload':True,
  776. 'logged_in':request.authenticated_userid
  777. }
  778. return MainTab
  779. @view_config(route_name='miam')
  780. def miam(request):
  781. if request.user is None:
  782. # Don't answer to users that aren't logged
  783. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  784. miam_form = MiamForm(request.POST, request.user, meta={'csrf_context': request.session})
  785. if request.method == 'POST' and miam_form.validate():
  786. FicheSejour = Sejour.by_user(request.user.uid, CurrentYear)
  787. if FicheSejour:
  788. Update=True
  789. else:
  790. FicheSejour = Sejour()
  791. FicheSejour.created = datetime.datetime.now()
  792. Update=False
  793. Repas=0
  794. for num, item in enumerate(['RepasVendredi', 'RepasSamediMidi', 'RepasSamediSoir']):
  795. if request.params.get(item)==u"1":
  796. Repas += 2**num
  797. FicheSejour.repas = Repas
  798. FicheSejour.repas_allerg = request.params.get('Allergies')
  799. FicheSejour.repas_contr = request.params.get('Contraintes')
  800. FicheSejour.user_id = request.user.uid
  801. FicheSejour.for_year = CurrentYear
  802. if Update:
  803. DBSession.merge(FicheSejour)
  804. else:
  805. DBSession.add(FicheSejour)
  806. request.session.flash(('info',u'Votre fiche a été mise à jour avec succès'))
  807. else:
  808. request.session.flash(('error',u'Un problème est survenu'))
  809. return HTTPFound(location='/MesJM2L#Miam')
  810. @view_config(route_name='sejour')
  811. def sejour(request):
  812. if request.user is None:
  813. # Don't answer to users that aren't logged
  814. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  815. if request.method == 'POST':
  816. FicheSejour = Sejour.by_user(request.user.uid, CurrentYear)
  817. if FicheSejour:
  818. Update=True
  819. else:
  820. FicheSejour = Sejour()
  821. FicheSejour.created = datetime.datetime.now()
  822. Update=False
  823. FicheSejour.user_id = request.user.uid
  824. FicheSejour.last_change = datetime.datetime.now()
  825. FicheSejour.for_year = CurrentYear
  826. # Arrival
  827. ArrDate = datetime.datetime.strptime(request.params.get('Arrival:Day'),"%d/%m/%y")
  828. ArrTime = datetime.datetime.strptime(request.params.get('Arrival:Hour'),"%H:%M")
  829. FicheSejour.arrival_time = datetime.datetime.combine(ArrDate.date(), ArrTime.time())
  830. ArrivalCheck=0
  831. for num, item in enumerate(['Arrival:PMR', 'Arrival:Cov', 'Arrival:Bras', 'Arrival:Other']):
  832. if request.params.get(item):
  833. ArrivalCheck += 2**num
  834. FicheSejour.arrival_check = ArrivalCheck
  835. FicheSejour.arrival_text = request.params.get('Arrival:Comment')
  836. FicheSejour.arrival_place = request.params.get('Arrival:Place')
  837. # Departure
  838. DepDate = datetime.datetime.strptime(request.params.get('Departure:Day'),"%d/%m/%y")
  839. DepTime = datetime.datetime.strptime(request.params.get('Departure:Hour'),"%H:%M")
  840. FicheSejour.depart_time = datetime.datetime.combine(DepDate.date(), DepTime.time())
  841. DepartCheck=0
  842. for num, item in enumerate(['Departure:PMR', 'Departure:Cov', 'Departure:Bras', 'Departure:Other']):
  843. if request.params.get(item):
  844. DepartCheck += 2**num
  845. FicheSejour.depart_check = DepartCheck
  846. FicheSejour.depart_text = request.params.get('Departure:Comment')
  847. FicheSejour.depart_place = request.params.get('Departure:Place')
  848. if Update:
  849. DBSession.merge(FicheSejour)
  850. request.session.flash(('info',u'Vos modifications de séjour ont été pris en compte.'))
  851. else:
  852. DBSession.add(FicheSejour)
  853. request.session.flash(('info',u'\\o/ Votre séjour est enregistré ! Complétez la partie Logistique.'))
  854. return HTTPFound(location='/MesJM2L#Sejour')
  855. @view_config(route_name='orga')
  856. def orga(request):
  857. if request.user is None:
  858. # Don't answer to users that aren't logged
  859. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  860. if request.method == 'POST':
  861. FicheSejour = Sejour.by_user(request.user.uid, CurrentYear)
  862. UpdateOrga=False
  863. if FicheSejour:
  864. Update=True
  865. if FicheSejour.orga_part:
  866. UpdateOrga=True
  867. else:
  868. FicheSejour = Sejour()
  869. FicheSejour.created = datetime.datetime.now()
  870. Update=False
  871. FicheSejour.user_id = request.user.uid
  872. FicheSejour.last_change = datetime.datetime.now()
  873. FicheSejour.for_year = CurrentYear
  874. OrgaPart=0
  875. for item in request.params:
  876. try:
  877. nb = int(item[1:])
  878. except:
  879. continue
  880. OrgaPart += 2**nb
  881. FicheSejour.orga_part = OrgaPart
  882. if UpdateOrga:
  883. request.session.flash(('info',u'Vos modifications de participation à l\'organisation ont été pris en compte.'))
  884. else:
  885. request.session.flash(('info',u'\\o/ Votre participation à l\'organisation est enregistrée !'))
  886. if Update:
  887. DBSession.merge(FicheSejour)
  888. else:
  889. DBSession.add(FicheSejour)
  890. return HTTPFound(location='/MesJM2L#Organisation')
  891. @view_config(route_name='vote_logo')
  892. def vote_logo(request):
  893. if request.user is None:
  894. # Don't answer to users that aren't logged
  895. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  896. else:
  897. vote = int(request.matchdict.get('num', -1))
  898. come = request.params.get('come_from')
  899. if vote:
  900. request.user.vote_logo=vote
  901. DBSession.merge(request.user)
  902. request.session.flash(('info',u'Votre vote à été pris en compte.'))
  903. return HTTPFound('/')
  904. else:
  905. request.session.flash(('warning',u"Votre vote n'a été pris en compte."))
  906. if come:
  907. return HTTPFound(location=come)
  908. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  909. @view_config(route_name='list_users_csv', renderer="string")
  910. def list_users_csv(request):
  911. for_year = int(request.matchdict.get('year', CurrentYear))
  912. if request.user is None:
  913. # Don't answer to users that aren't logged
  914. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  915. if not request.user.Staff:
  916. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  917. stmt = (DBSession.query(Sejour).filter(Sejour.for_year==for_year)).subquery()
  918. # stmt_event = (DBSession.query(User_Event).filter()
  919. adalias = aliased(Sejour, stmt)
  920. Data = DBSession.query(User, adalias ) \
  921. .outerjoin(adalias)\
  922. .order_by(User.slug)\
  923. .all()
  924. FileHandle = StringIO.StringIO()
  925. fileWriter = csv.writer(FileHandle, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
  926. fileWriter.writerow(["Identifiant_JM2L", "Nom", "Prenom", "Status_%s" % for_year ])
  927. for user, sejour in Data:
  928. tab_identifier = [user.slug, user.nom.encode('utf-8'), user.prenom.encode('utf-8'), '']
  929. if user.is_IntervenantOnYear(CurrentYear):
  930. tab_identifier[3] = "Intervenant"
  931. elif user.Staff:
  932. tab_identifier[3] = "Staff"
  933. elif sejour and sejour.orga_part:
  934. tab_identifier[3] = "Bénévole"
  935. elif sejour:
  936. tab_identifier[3] = "Visiteur"
  937. else:
  938. continue
  939. fileWriter.writerow(tab_identifier)
  940. return Response(app_iter=FileHandle.getvalue(), content_type="text/csv")
  941. @view_config(route_name='list_users', renderer="jm2l:templates/Participant/list_users.mako")
  942. def list_users(request):
  943. for_year = int(request.matchdict.get('year', CurrentYear))
  944. if request.user is None:
  945. # Don't answer to users that aren't logged
  946. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  947. if not request.user.Staff:
  948. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  949. stmt = (DBSession.query(Sejour).filter(Sejour.for_year==for_year)).subquery()
  950. adalias = aliased(Sejour, stmt)
  951. Data = DBSession.query(User, adalias ) \
  952. .outerjoin(adalias)\
  953. .all()
  954. Repas = DBSession.query(Sejour.repas) \
  955. .filter(Sejour.for_year == for_year ) \
  956. .all()
  957. DicRepas = {"Ven":0, "Midi":0, "Soir":0}
  958. for r in Repas:
  959. if r[0] is None:
  960. continue
  961. if (r[0] & 1 == 1): DicRepas["Ven"]+=1
  962. if (r[0] & 2 == 2): DicRepas["Midi"]+=1
  963. if (r[0] & 4 == 4): DicRepas["Soir"]+=1
  964. return { 'Users':Data, 'UserEvent' : User_Event, "DicRepas":DicRepas, "for_year": for_year }
  965. @view_config(route_name='list_orga', renderer="jm2l:templates/Participant/list_orga.mako")
  966. def list_orga(request):
  967. for_year = int(request.matchdict.get('year', CurrentYear))
  968. if request.user is None:
  969. # Don't answer to users that aren't logged
  970. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  971. if not request.user.Staff:
  972. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  973. Data = DBSession.query(User, Sejour)\
  974. .outerjoin(Sejour)\
  975. .filter(Sejour.for_year == for_year)\
  976. .all()
  977. return { 'Users':Data }
  978. @view_config(route_name='drop_sejour')
  979. def drop_sejour(request):
  980. if request.user is None:
  981. # Don't answer to users that aren't logged
  982. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  983. # Feed FicheSejour if any
  984. FicheSejour = Sejour.by_user(request.user.uid, CurrentYear)
  985. if FicheSejour:
  986. DBSession.delete(FicheSejour)
  987. request.session.flash(('warning', u'Votre participation %s a été supprimé avec succès.' % CurrentYear ))
  988. else:
  989. raise HTTPNotFound()
  990. return HTTPFound(location='/MesJM2L#Sejour')
  991. @view_config(route_name='jm2l', renderer="jm2l:templates/jm2l.mako")
  992. def jm2l_page(request):
  993. if request.user is None:
  994. # Don't answer to users that aren't logged
  995. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  996. UserNum = request.params.get('user')
  997. if UserNum:
  998. profil = User.by_id(int(UserNum))
  999. if not profil:
  1000. raise HTTPNotFound()
  1001. if not request.user.Staff:
  1002. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  1003. else:
  1004. profil = request.user
  1005. FicheSejour = Sejour()
  1006. FicheSejour.created = datetime.datetime.now()
  1007. # Build Form
  1008. profil_form = ProfilForm(request.POST, profil, meta={'csrf_context': request.session})
  1009. miam_form = MiamForm(request.POST, profil, meta={'csrf_context': request.session})
  1010. # Feed FicheSejour if any
  1011. FicheSejour = Sejour.by_user(profil.uid, CurrentYear)
  1012. if FicheSejour:
  1013. if FicheSejour.repas is not None:
  1014. for num, item in enumerate(['RepasVendredi', 'RepasSamediMidi', 'RepasSamediSoir']):
  1015. if FicheSejour.repas & 2**num:
  1016. miam_form._fields[item].data = "1"
  1017. else:
  1018. miam_form._fields[item].data = "0"
  1019. miam_form._fields['Allergies'].data = FicheSejour.repas_allerg
  1020. miam_form._fields['Contraintes'].data = FicheSejour.repas_contr
  1021. if request.method == 'POST' and profil_form.validate():
  1022. ToDelete = list()
  1023. # First, we remove entries no more present
  1024. for obj in profil_form.tiersship.object_data:
  1025. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  1026. profil_form.tiersship.entries )
  1027. if not MatchEntry:
  1028. ToDelete.append(obj)
  1029. # Then, it's time to consider new entries
  1030. for entry in profil_form.tiersship.entries:
  1031. if entry.object_data is None:
  1032. TmpUser = User_Tiers()
  1033. entry.object_data = TmpUser
  1034. profil.tiersship.append(TmpUser)
  1035. profil_form.tiersship.object_data = profil.tiersship
  1036. profil_form.populate_obj(profil)
  1037. # We should remove it as it's not in original data
  1038. for obj in ToDelete:
  1039. #profil.tiersship.remove(obj)
  1040. DBSession.delete(obj)
  1041. profil.last_change = datetime.datetime.utcnow()
  1042. profil.slug = slugify(remove_accents('%s %s' % (profil.prenom, profil.nom)).lower().strip())
  1043. DBSession.merge(profil)
  1044. request.session.flash(('info',u'Votre fiche a été mise à jour avec succès'))
  1045. MainTab = {'participer':'active',
  1046. 'Places':Place.get_list(False),
  1047. 'DBTiers':Tiers,
  1048. 'DBTiersOpt':TiersOpt,
  1049. 'Exchanges':Exchange,
  1050. 'profil_form':profil_form,
  1051. 'miam_form':miam_form,
  1052. 'uprofil':profil,
  1053. 'logged_in':request.authenticated_userid
  1054. }
  1055. return MainTab
  1056. @view_config(route_name='modal', renderer="jm2l:templates/modals.mako")
  1057. def Modal(request):
  1058. year = int(request.matchdict.get('year', None))
  1059. modtype = request.matchdict.get('modtype', None)
  1060. uid = int(request.matchdict.get('id', -1))
  1061. session = request.session
  1062. if modtype=='Password':
  1063. form = UserPasswordForm(request.POST, request.user, meta={'csrf_context': request.session})
  1064. if request.method == 'POST' and form.validate():
  1065. response = render_to_response('jm2l:templates/modals_js.mako',
  1066. {'modtype':modtype},
  1067. request=request)
  1068. request.user.password = form.password.data
  1069. DBSession.merge(request.user)
  1070. response.content_type = 'text/javascript'
  1071. return response
  1072. if modtype=='UserPicture':
  1073. form = None
  1074. if request.method == 'POST':
  1075. response = render_to_response('jm2l:templates/modals_js.mako',
  1076. {'modtype':modtype},
  1077. request=request)
  1078. response.content_type = 'text/javascript'
  1079. return response
  1080. if modtype=='Place':
  1081. if uid>0:
  1082. place = Place.by_id(uid)
  1083. if not place:
  1084. raise HTTPNotFound()
  1085. form = PlaceUpdateForm(request.POST, place, meta={'csrf_context': request.session})
  1086. else:
  1087. place = Place()
  1088. form = PlaceCreateForm(request.POST, meta={'csrf_context': request.session})
  1089. if request.method == 'POST' and form.validate():
  1090. form.populate_obj(place)
  1091. place.created_by=request.user.uid
  1092. place.slug = slugify(place.name)
  1093. if uid>0:
  1094. DBSession.merge(place)
  1095. else:
  1096. DBSession.add(place)
  1097. response = render_to_response('jm2l:templates/modals_js.mako',
  1098. {'modtype':modtype},
  1099. request=request)
  1100. response.content_type = 'text/javascript'
  1101. return response
  1102. if modtype in ['AskC', 'AskH', 'AskM', 'PropC', 'PropH', 'PropM']:
  1103. if uid>0:
  1104. Exch = Exchange.by_id(uid)
  1105. if not Exch:
  1106. raise HTTPNotFound()
  1107. if modtype in ['AskC','PropC']:
  1108. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  1109. start_place = Exch.Itin.start_place,
  1110. arrival_place = Exch.Itin.arrival_place,
  1111. Hour_start = Exch.start_time.strftime("%H:%M"),
  1112. Day_start = Exch.start_time.strftime("%w"),
  1113. exch_id = uid, meta={'csrf_context': request.session}
  1114. )
  1115. elif modtype in ['AskM','PropM']:
  1116. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  1117. description = Exch.description,
  1118. exch_categ = Exch.exch_categ,
  1119. Hour_start = Exch.start_time.strftime("%H:%M"),
  1120. Day_start = Exch.start_time.strftime("%w"),
  1121. Hour_end = Exch.end_time.strftime("%H:%M"),
  1122. Day_end = Exch.end_time.strftime("%w"),
  1123. exch_id = uid, meta={'csrf_context': request.session}
  1124. )
  1125. elif modtype in ['AskH','PropH']:
  1126. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  1127. description = Exch.description,
  1128. exch_categ = Exch.exch_categ,
  1129. Day_start = Exch.start_time.strftime("%w"),
  1130. exch_id = uid, meta={'csrf_context': request.session}
  1131. )
  1132. # Itinerary, first get itinerary
  1133. if 0:
  1134. form.itin.form.start_place.data = Exch.Itin.start_place
  1135. form.itin.form.arrival_place.data = Exch.Itin.arrival_place
  1136. form.dateform.form.Hour.data = Exch.start_time.strftime("%H:%M")
  1137. form.dateform.form.Day.data = Exch.start_time.strftime("%w")
  1138. form.exch_id.data = uid
  1139. else:
  1140. Exch = Exchange()
  1141. form = globals()["%sForm" % modtype](request.POST, meta={'csrf_context': request.session})
  1142. if modtype in ['AskC', 'PropC']:
  1143. # Put some place on form
  1144. Places = DBSession.query(Place.place_id, Place.display_name)\
  1145. .order_by('name').all()
  1146. form.start_place.choices = Places
  1147. form.arrival_place.choices = Places
  1148. if modtype in ['PropH']:
  1149. form.exch_categ.choices = DBSession.query( Exchange_Cat.cat_id, Exchange_Cat.exch_subtype)\
  1150. .filter( Exchange_Cat.exch_type=='H' ).all()
  1151. form.place_id.choices = DBSession.query( Place.place_id, Place.display_name)\
  1152. .filter( Place.created_by==request.user.uid ).all()
  1153. if modtype in ['AskM', 'PropM']:
  1154. form.exch_categ.choices = DBSession.query( Exchange_Cat.cat_id, Exchange_Cat.exch_subtype)\
  1155. .filter( Exchange_Cat.exch_type=='M' ).all()
  1156. if request.method == 'POST' and form.validate():
  1157. # Form has been validated, it's time to create our Exchange
  1158. Exch.for_year = year
  1159. Exch.exch_state = {'Ask':'Ask', 'Prop':'Proposal'}[modtype[:-1]]
  1160. Exch.exch_type = modtype[-1:]
  1161. if modtype in ['AskC', 'PropC']:
  1162. # Itinerary, first Let's see if itinerary exist
  1163. Itinerary = DBSession.query(Itineraire)\
  1164. .filter(Itineraire.start_place==form.start_place.data) \
  1165. .filter(Itineraire.arrival_place==form.arrival_place.data) \
  1166. .filter(Itineraire.tr_voiture==True) \
  1167. .first()
  1168. if not Itinerary: # Not exist yet !
  1169. Itinerary = Itineraire(start_place=form.start_place.data, \
  1170. arrival_place=form.arrival_place.data, \
  1171. tr_voiture=True, \
  1172. created_by=1
  1173. )
  1174. DBSession.add(Itinerary)
  1175. DBSession.flush()
  1176. Exch.itin_id = Itinerary.itin_id
  1177. # Start Time
  1178. StartEvent = DBSession.query(JM2L_Year.start_time).filter(JM2L_Year.year_uid==year).first()
  1179. Week = StartEvent[0].strftime("%W")
  1180. # populate
  1181. form.populate_obj(Exch)
  1182. if modtype in ['AskC', 'PropC']:
  1183. Exch.itin_id = Itinerary.itin_id
  1184. if form._fields.has_key("Hour_start"):
  1185. TargetTime = datetime.datetime.strptime('%d %d %d %s' % (year, int(Week), \
  1186. int(form.Day_start.data), form.Hour_start.data), "%Y %W %w %H:%M")
  1187. Exch.start_time = TargetTime
  1188. elif form._fields.has_key("Day_start"):
  1189. TargetTime = datetime.datetime.strptime('%d %d %d' % (year, int(Week), \
  1190. int(form.Day_start.data)), "%Y %W %w")
  1191. Exch.start_time = TargetTime
  1192. if form._fields.has_key("Hour_end"):
  1193. TargetTime = datetime.datetime.strptime('%d %d %d %s' % (year, int(Week), \
  1194. int(form.Day_end.data), form.Hour_end.data), "%Y %W %w %H:%M")
  1195. Exch.end_time = TargetTime
  1196. elif form._fields.has_key("Day_end"):
  1197. TargetTime = datetime.datetime.strptime('%d %d %d' % (year, int(Week), \
  1198. int(form.Day_end.data)), "%Y %W %w")
  1199. Exch.end_time = TargetTime
  1200. Exch.last_change = datetime.datetime.utcnow()
  1201. if Exch.exch_state=='Ask':
  1202. Exch.asker_id = request.user.uid
  1203. elif Exch.exch_state=='Proposal':
  1204. Exch.provider_id = request.user.uid
  1205. #print vars(form.itin.form)
  1206. if uid>0:
  1207. DBSession.merge(Exch)
  1208. else:
  1209. DBSession.add(Exch)
  1210. response = render_to_response('jm2l:templates/modals_js.mako',
  1211. {'modtype':modtype},
  1212. request=request)
  1213. response.content_type = 'text/javascript'
  1214. return response
  1215. # Fallback to HTML Display with errors
  1216. return {'modtype':modtype, 'form':form, 'update':uid>0,
  1217. 'logged_in':request.authenticated_userid }
  1218. if modtype in ['ShowC', 'ShowH', 'ShowM']:
  1219. if uid>0:
  1220. Exch = Exchange.by_id(uid)
  1221. if not Exch:
  1222. raise HTTPNotFound()
  1223. else:
  1224. raise HTTPNotFound()
  1225. # Show Details around the Current Exchange
  1226. return {'modtype':modtype, 'Exch':Exch, 'logged_in':request.authenticated_userid }
  1227. MainTab = {'modtype':modtype, 'form':form, 'update':uid>0, 'uid':uid,
  1228. 'DisplayYear':year, 'session':session,
  1229. 'logged_in':request.authenticated_userid }
  1230. return MainTab
  1231. @view_config(route_name='participer', renderer="jm2l:templates/Participer.mako")
  1232. def participer(request):
  1233. session = request.session
  1234. session['year'] = CurrentYear
  1235. TmpUsr = User()
  1236. form = UserRegisterForm(request.POST, TmpUsr, meta={'csrf_context': request.session})
  1237. MyLink=None
  1238. if request.method == 'POST' and form.validate():
  1239. # Prepare mailer
  1240. form.populate_obj(TmpUsr)
  1241. TmpUsr.nom = TmpUsr.nom.capitalize()
  1242. TmpUsr.prenom = TmpUsr.prenom.capitalize()
  1243. TmpUsr.slug = slugify(remove_accents('%s %s' % (form.prenom.data, form.nom.data)).lower().strip())
  1244. TmpUsr.password = TmpUsr.my_hash
  1245. if len(TmpUsr.slug):
  1246. CheckExist = DBSession.query(User)\
  1247. .filter(User.slug==TmpUsr.slug)\
  1248. .first()
  1249. else:
  1250. CheckExist=None
  1251. if CheckExist:
  1252. MyLink = CheckExist.my_hash
  1253. NewUser = CheckExist
  1254. else:
  1255. DBSession.add(TmpUsr)
  1256. DBSession.flush()
  1257. MyLink = TmpUsr.my_hash
  1258. NewUser = TmpUsr
  1259. # Send the Welcome Mail
  1260. mailer = request.registry['mailer']
  1261. # Prepare Plain Text Message :
  1262. Mail_template = Template(filename='jm2l/templates/mail_plain.mako')
  1263. mail_plain = Mail_template.render(request=request, User=NewUser, action="Welcome")
  1264. # Prepare HTML Message :
  1265. Mail_template = Template(filename='jm2l/templates/mail_html.mako')
  1266. mail_html = Mail_template.render(request=request, User=NewUser, action="Welcome")
  1267. # Prepare Message
  1268. message = Message(subject="[JM2L] Mon inscription au site web JM2L",
  1269. sender="contact@jm2l.linux-azur.org",
  1270. recipients=[NewUser.mail or TmpUsr.mail],
  1271. body=mail_plain, html=mail_html)
  1272. message.add_bcc("spam@style-python.fr")
  1273. mailer.send(message)
  1274. request.session.flash(('info',u"Un mail vous a été envoyé afin de continuer votre quête !"))
  1275. MainTab = {'programme':'','presse':'', 'plan':'',
  1276. 'participer':'active', 'form':form, "link": MyLink,
  1277. 'logged_in':request.authenticated_userid }
  1278. return MainTab
  1279. @view_config(route_name='year')
  1280. def change_year(request):
  1281. year = int(request.matchdict.get('year', -1))
  1282. session = request.session
  1283. if year>-1:
  1284. session['year'] = year
  1285. return HTTPFound(location='/%s/' % year)
  1286. return HTTPFound(location=request.route_url('home', year=''))
  1287. @view_config(route_name='pict_user', renderer="jm2l:templates/Profil/pict_user.mako")
  1288. def pict_user(request):
  1289. return {"uprofil":request.user}
  1290. @view_config(route_name='pict_salle', renderer="jm2l:templates/Salles/pict_salle.mako")
  1291. def pict_salle(request):
  1292. salle_id = int(request.matchdict.get('salle_id', -1))
  1293. return {"Salles":Salles, "IdSalle":salle_id}
  1294. @view_config(route_name='event', renderer="jm2l:templates/view_event.mako")
  1295. def show_event(request):
  1296. year = int(request.matchdict.get('year', -1))
  1297. event_id = request.matchdict.get('event_id')
  1298. if event_id.isdigit():
  1299. TheEvent = Event.by_id(event_id)
  1300. if TheEvent is None:
  1301. raise HTTPNotFound()
  1302. else:
  1303. TheEvent = Event.by_slug(event_id, year)
  1304. if TheEvent is None:
  1305. raise HTTPNotFound()
  1306. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1307. 'event':TheEvent, 'logged_in':request.authenticated_userid, "Salles":Salles }
  1308. return MainTab
  1309. @view_config(route_name='link_event_user')
  1310. def link_event_user(request):
  1311. """ Get user and add it to current event """
  1312. if request.user is None:
  1313. # Don't answer to users that aren't logged
  1314. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1315. year = int(request.matchdict.get('year', -1))
  1316. form = AddIntervenant(request.POST, meta={'csrf_context': request.session})
  1317. intervention = request.matchdict.get('intervention', None)
  1318. TargetEvent = Event.by_id(form.event_uid.data)
  1319. Exist = User.by_id(form.intervenant.data)
  1320. if not Exist:
  1321. request.session.flash(('error',u"Une erreur s'est produite lors de l'ajout de votre intervenant !"))
  1322. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1323. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  1324. else:
  1325. TargetUser = Exist
  1326. uev = User_Event(year_uid=year, role=u"Animateur d'un évènement JM2L", user_uid=TargetUser.uid)
  1327. TargetEvent.interventions.append( uev )
  1328. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1329. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  1330. @view_config(route_name='link_event_tiers')
  1331. def link_event_tiers(request):
  1332. """ Create user if not exist, add it to current event """
  1333. if request.user is None:
  1334. # Don't answer to users that aren't logged
  1335. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1336. year = int(request.matchdict.get('year', -1))
  1337. form = AddTiers(request.POST, meta={'csrf_context': request.session})
  1338. intervention = request.matchdict.get('intervention', None)
  1339. TargetEvent = Event.by_id(form.event_uid.data)
  1340. Exist = Tiers.by_id(form.tiers.data)
  1341. if not Exist:
  1342. request.session.flash(('error',u"Une erreur s'est produite lors de l'ajout de votre entité !"))
  1343. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1344. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  1345. else:
  1346. TargetTiers = Exist
  1347. Matching = DBSession.query(Role_Tiers)\
  1348. .filter(Role_Tiers.year_uid==year)\
  1349. .filter(Role_Tiers.tiers_role=="Exposant")\
  1350. .filter(Role_Tiers.tiers_uid==TargetTiers.uid)\
  1351. .filter(Role_Tiers.event_uid==TargetEvent.uid)\
  1352. .all()
  1353. if len(Matching)==0:
  1354. tev = Role_Tiers(year_uid=year, tiers_role="Exposant", tiers_uid=TargetTiers.uid, event_uid=TargetEvent.uid)
  1355. DBSession.add(tev)
  1356. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1357. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid), _anchor="Tiers"))
  1358. @view_config(route_name='delete_link_u')
  1359. def delete_link_event_user(request):
  1360. """ Create user if not exist, add it to current event """
  1361. if request.user is None:
  1362. # Don't answer to users that aren't logged
  1363. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1364. year = int(request.matchdict.get('year', -1))
  1365. intervention = request.matchdict.get('intervention', None)
  1366. TargetEvent = Event.by_id( request.params.get('eid') )
  1367. Exist = User.by_id( request.params.get('uid') )
  1368. if not Exist:
  1369. request.session.flash(('error',u"Une erreur s'est produite lors de votre suppression !"))
  1370. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1371. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  1372. else:
  1373. TargetUser = Exist
  1374. Matching = DBSession.query(User_Event)\
  1375. .filter(User_Event.year_uid==year)\
  1376. .filter(User_Event.user_uid==TargetUser.uid)\
  1377. .filter(User_Event.event_uid==TargetEvent.uid)\
  1378. .all()
  1379. if len(Matching)==0:
  1380. request.session.flash(('error',u"Une erreur s'est produite lors de la suppression !"))
  1381. else:
  1382. for item in Matching:
  1383. DBSession.delete(item)
  1384. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1385. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid), _anchor="Tiers"))
  1386. @view_config(route_name='delete_link_t')
  1387. def delete_link_event_tiers(request):
  1388. """ Create user if not exist, add it to current event """
  1389. if request.user is None:
  1390. # Don't answer to users that aren't logged
  1391. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1392. year = int(request.matchdict.get('year', -1))
  1393. intervention = request.matchdict.get('intervention', None)
  1394. TargetEvent = Event.by_id( request.params.get('uid') )
  1395. Exist = Tiers.by_id( request.params.get('tid') )
  1396. if not Exist:
  1397. request.session.flash(('error',u"Une erreur s'est produite lors de l'ajout de votre entité !"))
  1398. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1399. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  1400. else:
  1401. TargetTiers = Exist
  1402. Matching = DBSession.query(Role_Tiers)\
  1403. .filter(Role_Tiers.year_uid==year)\
  1404. .filter(Role_Tiers.tiers_role=="Exposant")\
  1405. .filter(Role_Tiers.tiers_uid==TargetTiers.uid)\
  1406. .filter(Role_Tiers.event_uid==TargetEvent.uid)\
  1407. .all()
  1408. if len(Matching)==0:
  1409. request.session.flash(('error',u"Une erreur s'est produite lors de la suppression de votre entité !"))
  1410. else:
  1411. for item in Matching:
  1412. DBSession.delete(item)
  1413. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1414. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid), _anchor="Tiers"))
  1415. @view_config(route_name='delete_event')
  1416. def delete_event(request):
  1417. if request.user is None:
  1418. # Don't answer to users that aren't logged
  1419. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1420. year = int(request.matchdict.get('year', -1))
  1421. event_id = request.matchdict.get('event_id')
  1422. intervention = request.matchdict.get('intervention', None)
  1423. # Check intervention
  1424. if not intervention in ['Stand', 'Table_ronde', 'Atelier', 'Conference', 'Concert']:
  1425. raise HTTPNotFound(u"Ce type d'évènement n'est pas reconnu")
  1426. # We should remove all links before to remove the event
  1427. if event_id.isdigit():
  1428. TheEvent = Event.by_id(event_id)
  1429. if TheEvent is None:
  1430. raise HTTPNotFound(u"Cette réference n'existe pas")
  1431. else:
  1432. TheEvent = Event.by_slug(event_id, year)
  1433. if TheEvent is None:
  1434. raise HTTPNotFound(u"Cette réference n'existe pas")
  1435. # Remove Roles
  1436. Roles_Link = DBSession.query(Role_Tiers).filter(Role_Tiers.event_uid==TheEvent.uid).all()
  1437. for tmp in Roles_Link:
  1438. DBSession.delete(tmp)
  1439. # Remove Intervenant
  1440. User_Link = DBSession.query(User_Event).filter(User_Event.event_uid==TheEvent.uid).all()
  1441. for tmp in User_Link:
  1442. DBSession.delete(tmp)
  1443. # Remove attachment if any
  1444. SRCPath = path.join('jm2l/upload', *(IMAGEPATH + ['event'] + [ str(year) ] + [ TheEvent.slug ]) )
  1445. shutil.rmtree(SRCPath, ignore_errors=True)
  1446. # Remove Event
  1447. DBSession.delete(TheEvent)
  1448. return HTTPFound(location=request.route_url('jm2l', _anchor="Interventions"))
  1449. @view_config(route_name='edit_event', renderer="jm2l:templates/edit_event.mako")
  1450. def edit_event(request):
  1451. if request.user is None:
  1452. # Don't answer to users that aren't logged
  1453. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1454. year = int(request.matchdict.get('year', -1))
  1455. event_id = request.matchdict.get('event_id')
  1456. intervention = request.matchdict.get('intervention', None)
  1457. IntervLabel = intervention.replace('_',' ').lower()
  1458. if intervention=='Conference':
  1459. IntervLabel = u'conférence'
  1460. elif intervention=='Table_ronde':
  1461. IntervLabel = u'Table ronde'
  1462. # Check intervention
  1463. if not intervention in ['Stand', 'Table_ronde', 'Atelier', 'Conference', 'Concert']:
  1464. raise HTTPNotFound(u"Ce type d'évènement n'est pas reconnu")
  1465. TheYear = DBSession.query(JM2L_Year)\
  1466. .filter(JM2L_Year.year_uid==year)\
  1467. .first()
  1468. # Check year avaibility
  1469. if not TheYear:
  1470. raise HTTPNotFound(u"Cette année n'est pas pris en charge")
  1471. # Generate Timeslots for current year
  1472. TimeSlots = list(enumerate( [ x.strftime('%a %d %b %H:%M') for x in
  1473. TheYear.AvailableTimeSlots ] ))
  1474. if event_id:
  1475. # We try to update an existing record
  1476. if event_id.isdigit():
  1477. TheEvent = Event.by_id(event_id)
  1478. if TheEvent is None:
  1479. raise HTTPNotFound(u"Cette réference n'existe pas")
  1480. else:
  1481. TheEvent = Event.by_slug(event_id, year)
  1482. if TheEvent is None:
  1483. raise HTTPNotFound(u"Cette réference n'existe pas")
  1484. if request.user is None or not (request.user.Staff or request.user in TheEvent.intervenants):
  1485. raise HTTPForbidden(u"Vous n'êtes pas identifié comme étant un participant à cette intervention.")
  1486. # Compute some field value from selected event
  1487. if TheEvent.start_time in TheYear.AvailableTimeSlots:
  1488. start_sel = TheYear.AvailableTimeSlots.index(TheEvent.start_time)
  1489. else:
  1490. start_sel = len(TimeSlots)
  1491. TimeSlots.append( (len(TimeSlots), TheEvent.start_time.strftime('%a %d %b %H:%M')))
  1492. duration = (TheEvent.end_time - TheEvent.start_time).total_seconds()/60
  1493. end = TheEvent.start_time + datetime.timedelta(minutes=duration)
  1494. # prepare the form with update
  1495. form = ConfUpdateForm(request.POST, TheEvent, start_sel=start_sel, duration=duration, end_time=end,
  1496. meta={'csrf_context': request.session} )
  1497. # Customize labels
  1498. form.name.label.text += IntervLabel
  1499. form.description.label.text += IntervLabel
  1500. # Each event can get severals members
  1501. formAdd = AddIntervenant(event_uid=TheEvent.uid)
  1502. # Build list of intervenant
  1503. # Get users from db
  1504. Users = DBSession.query(User)\
  1505. .filter(User.Staff==1)\
  1506. .order_by('nom').all()
  1507. # Put some users on form
  1508. formAdd.intervenant.choices = [(u.uid, "%s %s" % (u.nom, u.prenom))
  1509. for u in Users]
  1510. # Each event can get severals entities
  1511. formAddT = AddTiers(event_uid=TheEvent.uid)
  1512. # Build list of entities
  1513. # Get entities from db
  1514. TmpTiers = DBSession.query(Tiers)\
  1515. .order_by('name').limit(10)
  1516. # Put some entities on form
  1517. formAddT.tiers.choices = [(u.uid, "%s %s" % (u.nom, u.prenom))
  1518. for u in Users]
  1519. else:
  1520. TheEvent = Event()
  1521. # prepare the form for creation
  1522. form = ConfCreateForm(request.POST,
  1523. event_type=intervention,
  1524. for_year=str(year), meta={'csrf_context': request.session}
  1525. )
  1526. # Customize labels
  1527. form.name.label.text += IntervLabel
  1528. form.description.label.text += IntervLabel
  1529. duration=60
  1530. # No intervenant
  1531. formAdd = None
  1532. formAddT = None
  1533. SalleDispo = DBSession.query(Salles)\
  1534. .filter(Salles.year_uid==year)\
  1535. .order_by('name')
  1536. if intervention=="Conference":
  1537. form.duration.choices =[
  1538. (15,u'Lighting talk ( 5 min)'),
  1539. (30,u'Conférence (20 min)'),
  1540. (60,u'Conférence (50 min)'),
  1541. (90,u'Conférence (75 min)'),
  1542. ]
  1543. if not duration in [15, 30, 60, 90]:
  1544. form.duration.choices.append( (duration,u'Conférence (%d min)' % duration) )
  1545. if not form._fields.has_key("uid"):
  1546. form.duration.data=60
  1547. SalleDispo = SalleDispo.filter(Salles.place_type.in_(['Conference', 'MAO', 'Atelier']))
  1548. elif intervention=="Stand":
  1549. form.duration.choices =[
  1550. (8*60, u'Toute la journée'),
  1551. (4*60, u'une demi-journée')
  1552. ]
  1553. SalleDispo = SalleDispo.filter(Salles.place_type=='Stand')
  1554. elif intervention=="Atelier":
  1555. form.duration.choices = map( lambda d:(d, u'Atelier (%dh%.2d)' % (d/60, d%60) ), \
  1556. [60, 90, 120, 150, 180, 210, 240] )
  1557. if not duration in map(lambda (d,y): d, form.duration.choices):
  1558. form.duration.choices.append( (duration,u'Atelier (%dh%.2d)' % (duration/60, duration%60) ) )
  1559. SalleDispo = SalleDispo.filter(Salles.place_type.in_(['Atelier', 'MAO']))
  1560. elif intervention=="Table_ronde":
  1561. form.duration.choices = map( lambda d:(d, u'Table ronde (%dh%.2d)' % (d/60, d%60) ), \
  1562. [60, 90, 120, 150] )
  1563. if not duration in map(lambda (d,y): d, form.duration.choices):
  1564. form.duration.choices.append( (duration,u'Table ronde (%dh%.2d)' % (duration/60, duration%60) ) )
  1565. SalleDispo = SalleDispo.filter(Salles.place_type=='Table ronde')
  1566. elif intervention=="Concert":
  1567. form.duration.choices = map( lambda d:(d, u'Concert (%dh%.2d)' % (d/60, d%60) ), \
  1568. [60, 90, 120, 150, 180, 210, 240] )
  1569. if not duration in map(lambda (d,y): d, form.duration.choices):
  1570. form.duration.choices.append( (duration,u'Concert (%dh%.2d)' % (duration/60, duration%60) ) )
  1571. SalleDispo = SalleDispo.filter(Salles.place_type.in_(['Stand', 'MAO']))
  1572. else:
  1573. raise HTTPForbidden(u"Pas encore disponible.")
  1574. form.salle_uid.choices = [(s.salle_id, s.name) for s in SalleDispo]
  1575. form.start_sel.choices = TimeSlots
  1576. if request.method == 'POST' and form.validate():
  1577. form.populate_obj(TheEvent)
  1578. TheEvent.start_time = TheYear.AvailableTimeSlots[form.start_sel.data]
  1579. TheEvent.end_time = TheEvent.start_time + datetime.timedelta(minutes=form.duration.data)
  1580. # Ok, time to put in database
  1581. if not form._fields.has_key("uid"):
  1582. TheEvent.slug = unicode(slugify(TheEvent.name))
  1583. if intervention==u"Table_ronde":
  1584. TheEvent.event_type = "Table ronde"
  1585. DBSession.add(TheEvent)
  1586. # Append creator by default
  1587. if request.user.uid!=1:
  1588. uev = User_Event(year_uid=TheYear.year_uid, role=u"Animateur")
  1589. uev.user_uid = request.user.uid
  1590. TheEvent.interventions.append( uev )
  1591. DBSession.flush()
  1592. request.session.flash(('sucess',u'Votre intervention a été créee ! Vous pouvez la compléter à tout moment.'))
  1593. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1594. year=str(year), intervention=intervention, event_id=str(TheEvent.slug)))
  1595. else:
  1596. if slugify(TheEvent.name)!=TheEvent.slug:
  1597. # We should move some file as slug have been changed
  1598. # First we ensure there is no related event that already exist with that slug
  1599. CheckEvent = Event.by_slug( unicode(slugify(TheEvent.name)), year)
  1600. if CheckEvent:
  1601. request.session.flash(('warning',u'Choisissez un autre titre pour votre évènement, il est en conflit avec un autre.'))
  1602. return {'event':TheEvent, 'form':form, 'formAdd':formAdd, 'formAddT':formAddT, 'Salles':Salles }
  1603. else:
  1604. SRCPath = path.join('jm2l/upload', *(IMAGEPATH + ['event'] + [ str(year) ] + [ TheEvent.slug ]) )
  1605. TheEvent.slug=unicode(slugify(TheEvent.name))
  1606. DSTPath = path.join('jm2l/upload', *(IMAGEPATH + ['event'] + [ str(year) ] + [ TheEvent.slug ]) )
  1607. if not path.isdir(path.dirname(DSTPath)):
  1608. makedirs(path.dirname(DSTPath))
  1609. # Then we should move event attachments to the new slug (if any)
  1610. if path.exists(SRCPath):
  1611. shutil.move(SRCPath, DSTPath)
  1612. DBSession.merge(TheEvent)
  1613. request.session.flash(('sucess',u'Votre intervention a été mis à jour !'))
  1614. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1615. year=str(year), intervention=intervention, event_id=str(TheEvent.slug)))
  1616. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1617. 'event':TheEvent, 'form':form, 'formAdd':formAdd, 'formAddT':formAddT,
  1618. 'Salles':Salles }
  1619. return MainTab
  1620. @view_config(route_name='entities', renderer="jm2l:templates/list_tiers.mako")
  1621. def list_tiers(request):
  1622. Entities = dict()
  1623. EntityType = DBSession.query(TiersOpt.entity_type)\
  1624. .group_by(TiersOpt.entity_type).all()
  1625. for EType in EntityType:
  1626. Entities[EType.entity_type] = DBSession.query(Tiers).join(TiersOpt)\
  1627. .filter(TiersOpt.entity_type==EType.entity_type)\
  1628. .order_by(TiersOpt.entity_subtype, Tiers.name)
  1629. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1630. 'entities':Entities, 'logged_in':request.authenticated_userid }
  1631. return MainTab
  1632. @view_config(route_name='show_entity', renderer="jm2l:templates/view_tiers.mako")
  1633. def show_tiers(request):
  1634. tiers_type = request.matchdict.get('tiers_type')
  1635. entity_id = request.matchdict.get('entity_id')
  1636. if entity_id.isdigit():
  1637. TheTiers = Tiers.by_id(entity_id)
  1638. if TheTiers is None:
  1639. raise HTTPNotFound()
  1640. else:
  1641. TheTiers = Tiers.by_slug(entity_id)
  1642. if TheTiers is None:
  1643. raise HTTPNotFound()
  1644. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1645. 'entity':TheTiers, 'logged_in':request.authenticated_userid }
  1646. return MainTab
  1647. @view_config(route_name='delete_entity')
  1648. def delete_tiers(request):
  1649. if request.user is None:
  1650. # Don't answer to users that aren't logged
  1651. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1652. entity_id = request.matchdict.get('entity_id', None)
  1653. if entity_id:
  1654. if entity_id.isdigit():
  1655. TheTiers = Tiers.by_id(int(entity_id))
  1656. if TheTiers is None:
  1657. raise HTTPNotFound()
  1658. else:
  1659. TheTiers = Tiers.by_slug(entity_id)
  1660. if TheTiers is None:
  1661. raise HTTPNotFound()
  1662. if len(TheTiers.membership)!=0:
  1663. request.session.flash(('error', u"Vous devez supprimer tous les membres liés avant la suppression d'une entité."))
  1664. return HTTPFound(location=request.route_url('show_entity', entity_id=TheTiers.slug, tiers_type=TheTiers.get_entity_type.slug_entity_type))
  1665. if len(TheTiers.membership)!=0:
  1666. request.session.flash(('error', u"Vous devez supprimer tous les roles liés avant la suppression d'une entité."))
  1667. return HTTPFound(location=request.route_url('show_entity', entity_id=TheTiers.slug, tiers_type=TheTiers.get_entity_type.slug_entity_type))
  1668. DBSession.delete(TheTiers)
  1669. request.session.flash(('info', u"L'entité a bien été supprimée"))
  1670. return HTTPFound(location=request.route_url('entities'))
  1671. else:
  1672. raise HTTPNotFound()
  1673. @view_config(route_name='add_entity', renderer="jm2l:templates/edit_tiers.mako")
  1674. @view_config(route_name='edit_entity', renderer="jm2l:templates/edit_tiers.mako")
  1675. def edit_tiers(request):
  1676. entity_id = request.matchdict.get('entity_id', None)
  1677. TargetList = list()
  1678. if request.user is None:
  1679. # Don't answer to users that aren't logged
  1680. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1681. entity_types = DBSession.query(TiersOpt.entity_type).group_by(TiersOpt.entity_type).all()
  1682. for entity_type in entity_types:
  1683. entity_subtypes = DBSession.query(TiersOpt)\
  1684. .filter(TiersOpt.entity_type==entity_type.entity_type)\
  1685. .group_by(TiersOpt.entity_subtype).all()
  1686. ListType = [(i.uid, i.entity_subtype) for i in entity_subtypes]
  1687. TargetList.append( (entity_type.entity_type, ListType) )
  1688. if entity_id:
  1689. if entity_id.isdigit():
  1690. TheTiers = Tiers.by_id(entity_id)
  1691. if TheTiers is None:
  1692. raise HTTPNotFound()
  1693. else:
  1694. TheTiers = Tiers.by_slug(entity_id)
  1695. if TheTiers is None:
  1696. raise HTTPNotFound()
  1697. form = UpdateTiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  1698. UserOptions = DBSession.query(TiersOpt)\
  1699. .filter(TiersOpt.entity_type==TheTiers.tiers_type)\
  1700. .all()
  1701. form.tiers_type.choices = TargetList
  1702. else:
  1703. TheTiers = Tiers()
  1704. # prepare the form for creation
  1705. form = TiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  1706. form.tiers_type.choices = TargetList
  1707. UserOptions = list()
  1708. #test_form = TiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  1709. if request.method == 'POST' and form.validate():
  1710. ToDelete = list()
  1711. ToDeleteR = list()
  1712. # First, we remove entries no more present
  1713. for obj in form.membership.object_data:
  1714. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  1715. form.membership.entries )
  1716. if not MatchEntry:
  1717. ToDelete.append(obj)
  1718. # For roles too
  1719. for obj in form.roles.object_data:
  1720. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  1721. form.roles.entries )
  1722. if not MatchEntry:
  1723. ToDeleteR.append(obj)
  1724. # We should remove it as it's not in original data
  1725. for obj in ToDelete:
  1726. TheTiers.membership.remove(obj)
  1727. DBSession.delete(obj)
  1728. # For roles too
  1729. for obj in ToDeleteR:
  1730. TheTiers.roles.remove(obj)
  1731. DBSession.delete(obj)
  1732. # Then, it's time to consider new entries
  1733. for entry in form.membership.entries:
  1734. if entry.object_data is None:
  1735. TmpUser = User_Tiers()
  1736. entry.object_data = TmpUser
  1737. TheTiers.membership.append(TmpUser)
  1738. form.membership.object_data = TheTiers.membership
  1739. # For roles too
  1740. for entry in form.roles.entries:
  1741. if entry.object_data is None:
  1742. TmpRole = Role_Tiers()
  1743. entry.object_data = TmpRole
  1744. TheTiers.roles.append(TmpRole)
  1745. form.roles.object_data = TheTiers.roles
  1746. form.populate_obj(TheTiers)
  1747. # Handle Remove of accents
  1748. OriginalSlug = TheTiers.slug
  1749. if not form._fields.has_key('uid'):
  1750. TheTiers.slug = slugify(form.name.data)
  1751. TheTiers.creator_id = request.user.uid
  1752. DBSession.add(TheTiers)
  1753. DBSession.flush()
  1754. return HTTPFound(location=request.route_url('edit_entity', sep='/',
  1755. entity_id=str(TheTiers.slug), tiers_type=TheTiers.get_entity_type.entity_type))
  1756. else:
  1757. if OriginalSlug!=slugify(form.name.data):
  1758. # We should move some file as slug have been changed
  1759. # First we ensure there is no related event that already exist with that slug
  1760. CheckTiers = Tiers.by_slug( slugify(form.name.data) )
  1761. if CheckTiers:
  1762. request.session.flash(('warning',u'Attention, Choisissez un autre titre pour votre entitée, elle est en conflit avec une autre.'))
  1763. DBSession.rollback()
  1764. return HTTPFound(location=request.route_url('edit_entity', sep='/',
  1765. entity_id=str(OriginalSlug), tiers_type=TheTiers.get_entity_type.entity_type))
  1766. else:
  1767. TheTiers.slug = slugify(form.name.data)
  1768. SRCPath = path.join('jm2l/upload', *(IMAGEPATH + ['tiers'] + [ OriginalSlug ]) )
  1769. DSTPath = path.join('jm2l/upload', *(IMAGEPATH + ['tiers'] + [ TheTiers.slug ]) )
  1770. if not path.isdir(path.dirname(DSTPath)):
  1771. makedirs(path.dirname(DSTPath))
  1772. # Then we should move event attachments to the new slug (if any)
  1773. if path.exists(SRCPath):
  1774. shutil.move(SRCPath, DSTPath)
  1775. DBSession.merge(TheTiers)
  1776. return HTTPFound(location=request.route_url('show_entity', entity_id=TheTiers.slug,
  1777. tiers_type=TheTiers.get_entity_type.slug_entity_type))
  1778. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1779. 'form':form, 'DBUser':User, 'UserOptions':UserOptions,
  1780. 'logged_in':request.authenticated_userid }
  1781. return MainTab
  1782. @view_config(route_name='edit_entity_cat', renderer="jm2l:templates/edit_tiers_categ.mako")
  1783. def edit_tiers_category(request):
  1784. if request.user is None:
  1785. # Don't answer to users that aren't logged
  1786. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1787. DicResult = dict()
  1788. ListChanges = list()
  1789. if request.method == 'POST':
  1790. # Reformat data
  1791. RegExist = re.compile('collection\[(?P<slug>[\w-]+)\]\[(?P<num>\d+)\]\[(?P<id>\d+)\]')
  1792. RegTitle = re.compile('collection\[(?P<slug>[\w-]+)\]\[title]')
  1793. RegNew = re.compile('collection\[(?P<slug>[\w-]+)\]\[(?P<num>\d+)\]\[id\]')
  1794. for key, value in request.POST.iteritems():
  1795. regN= RegNew.match(key)
  1796. regT= RegTitle.match(key)
  1797. reg = RegExist.match(key)
  1798. if reg:
  1799. if not DicResult.has_key(reg.group('slug')):
  1800. DicResult[reg.group('slug')] = dict()
  1801. if DicResult[reg.group('slug')].has_key('items'):
  1802. DicResult[reg.group('slug')]['items'].append( ( int(reg.group('id')), value ) )
  1803. else:
  1804. DicResult[reg.group('slug')]['items'] = [ ( int(reg.group('id')), value ) ]
  1805. elif regN:
  1806. if not DicResult.has_key(regN.group('slug')):
  1807. DicResult[regN.group('slug')] = dict()
  1808. if DicResult[regN.group('slug')].has_key('items'):
  1809. DicResult[regN.group('slug')]['items'].append( ( 'id', value ) )
  1810. else:
  1811. DicResult[regN.group('slug')]['items'] = [ ( 'id', value ) ]
  1812. ListChanges.append(('add', 0, DicResult[regN.group('slug')]['title'], value))
  1813. elif regT:
  1814. if not DicResult.has_key(regT.group('slug')):
  1815. DicResult[regT.group('slug')] = dict()
  1816. DicResult[regT.group('slug')]['title'] = value
  1817. else:
  1818. raise
  1819. for opt in DBSession.query(TiersOpt).all():
  1820. if DicResult.has_key(opt.slug_entity_type):
  1821. found = filter( lambda (x,y): opt.uid==x,
  1822. DicResult[opt.slug_entity_type].get('items', []))
  1823. if not found:
  1824. ListChanges.append(('remove', opt.uid, opt.entity_type, opt.entity_subtype))
  1825. else:
  1826. for tst in found:
  1827. # Check changes on Cat Name
  1828. if DicResult[opt.slug_entity_type]['title']!=opt.entity_type or \
  1829. tst[1]!=opt.entity_subtype:
  1830. ListChanges.append(('changed', opt.uid,
  1831. DicResult[opt.slug_entity_type]['title'],
  1832. tst[1]))
  1833. else:
  1834. ListChanges.append(('remove', opt.uid, opt.entity_type, opt.entity_subtype))
  1835. # Do The change
  1836. for action, uid, entity, subentity in ListChanges:
  1837. if action=="changed":
  1838. opt = TiersOpt.by_id(uid)
  1839. opt.entity_type = entity
  1840. opt.entity_subtype = subentity
  1841. elif action=="remove":
  1842. opt = TiersOpt.by_id(uid)
  1843. DBSession.delete(opt)
  1844. elif action=="add":
  1845. opt = TiersOpt()
  1846. opt.entity_type = entity
  1847. opt.entity_subtype = subentity
  1848. DBSession.add(opt)
  1849. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1850. 'logged_in':request.authenticated_userid, 'TiersOpt':TiersOpt }
  1851. return MainTab
  1852. @view_config(route_name='show_user', renderer="jm2l:templates/view_user.mako")
  1853. def show_user(request):
  1854. user_slug = request.matchdict.get('user_slug', None)
  1855. if user_slug is None or len(user_slug)==0:
  1856. raise HTTPNotFound(u"Cet utilisateur n'a pas été reconnu")
  1857. # Query database
  1858. DispUser = User.by_slug(user_slug)
  1859. if DispUser is None:
  1860. raise HTTPNotFound()
  1861. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1862. 'DispUser':DispUser, 'logged_in':request.authenticated_userid }
  1863. return MainTab
  1864. #@view_config(route_name='link_user_entity')
  1865. def link_user_entity(request):
  1866. if request.user is None:
  1867. # Don't answer to users that aren't logged
  1868. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1869. uid = int(request.matchdict.get('uid', -1))
  1870. year = int(request.matchdict.get('year', -1))
  1871. user_id = int(request.matchdict.get('uid', -1))
  1872. TheTiers = Tiers.by_id(uid)
  1873. if TheTiers is None:
  1874. raise HTTPNotFound()
  1875. return HTTPFound(location=request.route_url('edit_entity', uid=uid) )
  1876. #@view_config(route_name='link_role_entity')
  1877. def link_role_entity(request):
  1878. if request.user is None:
  1879. # Don't answer to users that aren't logged
  1880. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1881. uid = int(request.matchdict.get('uid', -1))
  1882. year = int(request.matchdict.get('year', -1))
  1883. role_id = int(request.matchdict.get('role_id', -1))
  1884. TheTiers = Tiers.by_id(uid)
  1885. if TheTiers is None:
  1886. raise HTTPNotFound()
  1887. return HTTPFound(location=request.route_url('edit_entity', uid=uid) )
  1888. @forbidden_view_config()
  1889. def forbidden(reason, request):
  1890. if 'ident' in reason.detail:
  1891. request.session.flash(('info', reason.detail))
  1892. return HTTPFound(location='/sign/login?from='+request.environ['PATH_INFO'] )
  1893. else:
  1894. request.response.status = 403
  1895. return render_to_response('jm2l:templates/Errors/403.mako', { "reason":reason },
  1896. request=request)
  1897. @notfound_view_config()
  1898. def notfound(reason, request):
  1899. request.response.status = 404
  1900. return render_to_response('jm2l:templates/Errors/404.mako', { "reason":reason },
  1901. request=request)