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.
 
 
 
 
 

1460 lines
63 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.response import Response
  6. from pyramid.view import notfound_view_config, forbidden_view_config
  7. from pyramid.view import view_config
  8. from pyramid_mailer import get_mailer
  9. from mako.template import Template
  10. # Import Web Forms
  11. from .forms import *
  12. # Database access imports
  13. from .models import *
  14. from sqlalchemy.exc import DBAPIError
  15. from sqlalchemy import func, or_
  16. # Usefull tools
  17. from slugify import slugify
  18. from icalendar import Calendar
  19. from pytz import timezone
  20. from icalendar import Event as Evt
  21. from pyramid_mailer import get_mailer
  22. from pyramid_mailer.message import Attachment, Message
  23. # Then, standard libs
  24. import webhelpers.paginate as paginate
  25. import unicodedata
  26. import time
  27. import datetime
  28. import re
  29. CurrentYear = 2015
  30. ## =-=- Here, We keep some usefull function -=-=
  31. def remove_accents(input_str):
  32. """ This function is intended to remove all accent from input unicode string """
  33. nkfd_form = unicodedata.normalize('NFKD', input_str)
  34. only_ascii = nkfd_form.encode('ASCII', 'ignore')
  35. return only_ascii
  36. def embeed_video(mime_type, link):
  37. Container = "<video controls='controls' preload='metadata' style='width:60%'>"
  38. Container += "<source type='%s' " % mime_type
  39. Container += "src='%s' />" % link
  40. Container += "</video>"
  41. return Container
  42. ## =-=- Here, We handle ICal requests -=-=
  43. @view_config(route_name='progr_iCal', renderer="string")
  44. def ICal_Progamme_Request(request):
  45. year = int(request.matchdict.get('year', CurrentYear))
  46. # Initialization
  47. DicResult = dict()
  48. # Query database
  49. # Compute days used by all events matching the specified input year
  50. Events = DBSession.query(Event)\
  51. .filter(Event.for_year == year)\
  52. .filter(Event.event_type != 'Stand')\
  53. .order_by(Event.start_time)
  54. cal = Calendar()
  55. cal.add('prodid', '-//Programme %d//jm2l.linux-azur.org//' % year)
  56. cal.add('version', '2.0')
  57. tz = timezone('Europe/Paris')
  58. for ev in Events:
  59. if ev.event_type:
  60. event = Evt()
  61. event['uid'] = "%d/%d" % ( year, ev.uid )
  62. event.add('summary', ev.name )
  63. event.add('dtstart', ev.start_time.replace(tzinfo=tz) )
  64. event.add('dtend', ev.end_time.replace(tzinfo=tz) )
  65. event.add('created', ev.last_change.replace(tzinfo=tz) )
  66. event.add('description', "http://www.linux-azur.org/event/%s/%s" % (ev.for_year, ev.slug) )
  67. event.add('url', "http://www.linux-azur.org/event/%s/%s" % (ev.for_year, ev.slug) )
  68. event.add('priority', 5)
  69. cal.add_component(event)
  70. request.response.content_type = "text/calendar"
  71. return cal.to_ical()
  72. ## =-=- Here, We handle Json requests -=-=
  73. @view_config(route_name='users_json', renderer="json")
  74. def JSON_User_Request(request):
  75. """ Build a JSON answer with active users and pagination handling """
  76. # Check arguments consitency
  77. pageSize = request.params.get('pageSize',"8")
  78. current_page = request.params.get('pageNum',"1")
  79. UserQuery = request.params.get('searchTerm', u"")
  80. # Don't answer to users that aren't logged
  81. if not request.user:
  82. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  83. # Check consistancy of parameters
  84. if pageSize.isdigit() and current_page.isdigit():
  85. current_page = int(current_page)
  86. pageSize = int(pageSize)
  87. else:
  88. return HTTPBadRequest('pageSize and pageNum accept only digits.')
  89. # Query database
  90. Users = DBSession.query(User.uid, User.nom, User.prenom)\
  91. .filter(User.slug.contains( remove_accents(UserQuery) ))
  92. page_url = paginate.PageURL_WebOb(request)
  93. records = paginate.Page(Users, current_page, url=page_url, items_per_page=pageSize)
  94. ListMatchUser = map( lambda u:{"id": u.uid, "text":"%s %s" % ( u.prenom, u.nom )}, records )
  95. return { "Results": ListMatchUser, "Total":records.item_count,
  96. "logged_in":request.authenticated_userid }
  97. @view_config(route_name='tiers_json', renderer="json")
  98. def JSON_Tiers_Request(request):
  99. """ Build a JSON answer with active users and pagination handling """
  100. # Check arguments consitency
  101. pageSize = request.params.get('pageSize',"8")
  102. current_page = request.params.get('pageNum',"1")
  103. TiersQuery = request.params.get('searchTerm', u"")
  104. # Don't answer to users that aren't logged
  105. if not request.user:
  106. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  107. # Check consistancy of parameters
  108. if pageSize.isdigit() and current_page.isdigit():
  109. current_page = int(current_page)
  110. pageSize = int(pageSize)
  111. else:
  112. return HTTPBadRequest('pageSize and pageNum accept only digits.')
  113. # Query database
  114. JTiers = DBSession.query(Tiers.uid, Tiers.name)\
  115. .filter(Tiers.slug.contains( remove_accents(TiersQuery) ))
  116. page_url = paginate.PageURL_WebOb(request)
  117. records = paginate.Page(JTiers, current_page, url=page_url, items_per_page=pageSize)
  118. ListMatchTiers = map( lambda t:{"id": t.uid, "text": t.name }, records )
  119. return { "Results": ListMatchTiers, "Total":records.item_count,
  120. "logged_in":request.authenticated_userid }
  121. @view_config(route_name='progr_json', renderer="json")
  122. def JSON_Progamme_Request(request):
  123. year = int(request.matchdict.get('year', CurrentYear))
  124. # Initialization
  125. DicResult = dict()
  126. # Query database
  127. # Compute days used by all events matching the specified input year
  128. Days = DBSession.query( func.strftime('%d', Event.start_time).label('day') )\
  129. .filter(Event.for_year == year)\
  130. .filter(Event.event_type != None)\
  131. .group_by(func.strftime('%d', Event.start_time)).all()
  132. for Day in Days:
  133. Events = DBSession.query(Event)\
  134. .filter(Event.for_year == year)\
  135. .filter(Event.event_type != 'Stand')\
  136. .filter("strftime('%d', start_time) = :dow").params(dow=Day.day)\
  137. .order_by(Event.start_time)
  138. ListEv = []
  139. for ev in Events:
  140. if ev.event_type:
  141. ListEv.append( {
  142. "uid":"%d/%d" % ( year, ev.uid ),
  143. "desc":ev.name,
  144. "startDate":ev.start_time.strftime('%Y-%m-%dT%H:%M:%S'),
  145. "endDate":ev.end_time.strftime('%Y-%m-%dT%H:%M:%S'),
  146. "placeName":ev.Salle and (ev.Salle.name or "unk") ,
  147. "status":ev.event_type
  148. } )
  149. DicResult[Day.day] = ListEv
  150. return { 'all':DicResult }
  151. @view_config(route_name='timeline_json', renderer="json")
  152. def JSON_TimeLine_Request(request):
  153. year = int(request.matchdict.get('year', CurrentYear))
  154. # Initialization
  155. DicResult = dict()
  156. # Query database
  157. # Compute days used by all events matching the specified input year
  158. Days = DBSession.query( func.strftime('%d', Event.start_time).label('day') )\
  159. .filter(Event.for_year == year)\
  160. .filter(Event.event_type != None)\
  161. .group_by(func.strftime('%d', Event.start_time)).all()
  162. ListEv = []
  163. for Day in Days:
  164. Events = DBSession.query(Event)\
  165. .filter(Event.for_year == year)\
  166. .filter(Event.event_type != 'Stand')\
  167. .filter("strftime('%d', start_time) = :dow").params(dow=Day.day)\
  168. .order_by(Event.start_time)
  169. #ListEv = []
  170. for ev in Events:
  171. if ev.event_type:
  172. CurMedia = ev.video.first() or ""
  173. if CurMedia:
  174. Container = "<video controls='controls' preload='metadata' style='width:60%'>"
  175. Container += "<source type='%s' " % CurMedia.mime_type
  176. Container += "src='%s' />" % CurMedia.get_path
  177. Container += "</video>"
  178. else:
  179. Container = ""
  180. ListEv.append( {
  181. #"uid":"%d/%d" % ( year, ev.uid ),
  182. "headline":ev.name,
  183. "startDate":ev.start_time.strftime('%Y,%m,%d,%H,%M'),
  184. "endDate":ev.end_time.strftime('%Y,%m,%d,%H,%M'),
  185. "text":ev.Salle and (ev.Salle.name or "unk"),
  186. #"text":ev.description[:100],
  187. "tags":ev.Salle and (ev.Salle.salle_id or "unk") ,
  188. #"status":ev.event_type,
  189. "asset": {
  190. "media": Container,
  191. "credit": ",".join(["%s %s" % (i.prenom, i.nom) for i in ev.intervenants]),
  192. "caption":"" }
  193. } )
  194. if year==2015:
  195. DicResult = {
  196. "lang":"fr",
  197. "headline":"JM2L 2015",
  198. "type":"default",
  199. "startDate":"2015,11,28,10",
  200. "text":"<i><span class='c1'>9ème Édition</span></i>",
  201. "asset":
  202. {
  203. "media":"https://www.youtube.com/watch?v=DnfjrxVoLao",
  204. "credit":"JM2L",
  205. "caption":""
  206. }
  207. }
  208. elif year==2011:
  209. DicResult = {
  210. "lang":"fr",
  211. "headline":"JM2L 2011",
  212. "type":"default",
  213. "startDate":"2011,11,25,10",
  214. "text":"<i><span class='c1'>6ème Édition</span></i>",
  215. "asset":
  216. {
  217. "media":"https://www.youtube.com/embed/rcaNeXuAEhs",
  218. "credit":"JM2L",
  219. "caption":"Reportage FR3"
  220. },
  221. }
  222. elif year==2010:
  223. DicResult = {
  224. "lang":"fr",
  225. "headline":"JM2L 2010",
  226. "type":"default",
  227. "text":"<i><span class='c1'>5ème Édition</span></i>",
  228. "asset":
  229. {
  230. "media":embeed_video("video/ogg","http://jm2l.linux-azur.org/resources/2010/Video/reportages/JM2L2010-PleinSudTV.ogv"),
  231. "credit":"JM2L",
  232. "caption":"reportage Plein-sud TV"
  233. }
  234. }
  235. else:
  236. DicResult = {
  237. "lang":"fr",
  238. "headline":"JM2L %d" % year,
  239. "type":"default",
  240. "asset":
  241. {
  242. "media":"",
  243. "credit":"JM2L",
  244. "caption":""
  245. }
  246. }
  247. DicResult["date"] = ListEv
  248. return { 'timeline':DicResult }
  249. ## =-=- Here, We handle HTTP requests - Public Part -=-=
  250. @view_config(route_name='home', renderer="jm2l:templates/NewIndex.mako")
  251. def index_page(request):
  252. year = request.matchdict.get('year')
  253. if year:
  254. year=int(year[:-1])
  255. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==year).first()
  256. if content:
  257. content = content.description
  258. else:
  259. content = ""
  260. if 2004<year<=CurrentYear:
  261. if year==2006:
  262. return {'year': year, 'content':content, 'edition':u"1<sup>ère</sup>" }
  263. elif year==2015:
  264. return {'year': year, 'content':content, 'edition':u"9<sup>ème</sup>" }
  265. else:
  266. edition = year - 2005
  267. return {'year': year, 'content':content, 'edition':u"%d<sup>ème</sup>" % edition }
  268. else:
  269. raise HTTPNotFound()
  270. else:
  271. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==CurrentYear).first().description
  272. return {'year': CurrentYear, 'content':content, 'edition':u"9<sup>ème</sup>"}
  273. @view_config(route_name='edit_index', renderer="jm2l:templates/Staff/EditIndex.mako")
  274. def edit_index(request):
  275. year = int(request.matchdict.get('year', None))
  276. if not request.user.Staff:
  277. # Don't answer to users that aren't logged
  278. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  279. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==year).first()
  280. form = IndexForm(request.POST, content, meta={'csrf_context': request.session})
  281. if request.method == 'POST' and form.validate():
  282. form.populate_obj(content)
  283. return HTTPFound(location=request.route_url('home', year="%d/" % year))
  284. MainTab = {'home':'active', "logged_in":request.authenticated_userid,
  285. 'form':form, 'DisplayYear':year}
  286. return MainTab
  287. @view_config(route_name='programme', renderer="jm2l:templates/Public/Programme.mako")
  288. def programme(request):
  289. year = int(request.matchdict.get('year'))
  290. if 2006 > year:
  291. return HTTPBadRequest('The first JM2L event was in 2006.')
  292. # Query database about selected Year.
  293. Events = DBSession.query(Event)\
  294. .filter(Event.for_year == year)\
  295. .order_by(Event.start_time)
  296. Days = DBSession.query(func.strftime('%d-%m-%Y', Event.start_time))\
  297. .filter(Event.for_year == year)\
  298. .filter(Event.event_type != None)\
  299. .group_by(func.strftime('%d', Event.start_time)).all()
  300. ListDay = []
  301. for day in Days:
  302. RefDay = datetime.datetime.strptime(day[0],'%d-%m-%Y')
  303. ListDay.append( ( RefDay.strftime('%A %d %b %Y'),
  304. RefDay.strftime('%d') ) )
  305. MainTab = {'programme':'active','DisplayYear':year, \
  306. 'Events':Events, 'Event':Event, 'Days':ListDay, "logged_in":request.authenticated_userid }
  307. return MainTab
  308. @view_config(route_name='presse', renderer="jm2l:templates/Public/Presse.mako")
  309. def static_presse(request):
  310. year = int(request.matchdict.get('year', None))
  311. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==year).first()
  312. MainTab = {'presse':'active', "logged_in":request.authenticated_userid, 'content':content, 'DisplayYear':year}
  313. return MainTab
  314. @view_config(route_name='edit_presse', renderer="jm2l:templates/Staff/EditPresse.mako")
  315. def edit_presse(request):
  316. year = int(request.matchdict.get('year', None))
  317. if request.user is None:
  318. # Don't answer to users that aren't logged
  319. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  320. if not request.user.Staff:
  321. # Don't answer to users that aren't logged
  322. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  323. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==year).first()
  324. form = DossPresse(request.POST, content, meta={'csrf_context': request.session})
  325. if request.method == 'POST' and form.validate():
  326. form.populate_obj(content)
  327. MainTab = {'presse':'active', "logged_in":request.authenticated_userid, 'form':form, 'DisplayYear':year}
  328. return MainTab
  329. @view_config(route_name='plan', renderer="jm2l:templates/Public/Plan.mako")
  330. def static_plan(request):
  331. session = request.session
  332. session['year'] = 2015
  333. MainTab = {'plan':'active', "logged_in":request.authenticated_userid }
  334. return MainTab
  335. ## =-=- Here, We handle HTTP requests - Staff Logged Part -=-=
  336. @view_config(route_name='list_task', renderer='jm2l:templates/Staff/list.mako')
  337. def list_view(request):
  338. if request.user is None:
  339. # Don't answer to users that aren't logged
  340. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  341. if not request.user.Staff:
  342. # Don't answer to users that aren't logged
  343. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  344. DicTask = {}
  345. taskgroup = DBSession.query( TasksArea ).all()
  346. for grp in taskgroup:
  347. tasks = DBSession.query( Tasks )\
  348. .filter( Tasks.area_uid==grp.uid )\
  349. .order_by(Tasks.closed, Tasks.due_date).all()
  350. DicTask[grp] = tasks
  351. return {'tasks': DicTask }
  352. @view_config(route_name='handle_task', renderer='jm2l:templates/Staff/tasks.mako')
  353. def tasks(request):
  354. if request.user is None:
  355. # Don't answer to users that aren't logged
  356. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  357. if not request.user.Staff:
  358. # Don't answer to users that aren't logged
  359. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  360. task_id = request.matchdict.get('task_id')
  361. # Convert the pole_id GET parameter to int or 0
  362. try:
  363. pole_id = int(request.params.get('pole_id'))
  364. except (ValueError, TypeError):
  365. pole_id = 0
  366. # Get areas from db
  367. Areas = DBSession.query(TasksArea.uid, TasksArea.name)\
  368. .order_by('name').all()
  369. # Get users from db
  370. Users = DBSession.query(User)\
  371. .filter(User.Staff==1)\
  372. .order_by('nom').all()
  373. if task_id:
  374. Task = Tasks.by_id(int(task_id))
  375. if not Task:
  376. raise HTTPNotFound()
  377. form = EditStaffTasks(request.POST, Task, meta={'csrf_context': request.session})
  378. else:
  379. Task = Tasks()
  380. # Check if the supplied pole_id is in the Areas' range
  381. Task.area_uid = pole_id if 1 < pole_id <= len(Areas) else 1
  382. form = StaffTasks(request.POST, Task, meta={'csrf_context': request.session})
  383. # Put some areas on form
  384. form.area_uid.choices = Areas
  385. # Put some users on form
  386. form.closed_by.choices = [(u.uid, "%s %s" % (u.nom, u.prenom))
  387. for u in Users]
  388. form.due_date.type = "date"
  389. if request.method == 'POST' and form.validate():
  390. form.populate_obj(Task)
  391. Task.closed = False
  392. if 'uid' in form._fields.keys():
  393. DBSession.merge(Task)
  394. else:
  395. DBSession.add(Task)
  396. DBSession.flush()
  397. return HTTPFound(location=request.route_url('list_task')+"#"+slugify(Task.area.name))
  398. return {'form':form, 'area':slugify(Areas[Task.area_uid-1].name)}
  399. @view_config(route_name='handle_pole', renderer='jm2l:templates/Staff/pole.mako')
  400. def tasks_area(request):
  401. if request.user is None:
  402. # Don't answer to users that aren't logged
  403. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  404. if not request.user.Staff:
  405. # Don't answer to users that aren't logged
  406. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  407. pole_id = request.matchdict.get('pole_id')
  408. if pole_id:
  409. Pole = TasksArea.by_id(int(pole_id))
  410. if not Pole:
  411. raise HTTPNotFound()
  412. form = EditStaffArea(request.POST, Pole, meta={'csrf_context': request.session})
  413. else:
  414. Pole = TasksArea()
  415. form = StaffArea(request.POST, Pole, meta={'csrf_context': request.session})
  416. if request.method == 'POST' and form.validate():
  417. form.populate_obj(Pole)
  418. if 'uid' in form._fields.keys():
  419. DBSession.merge(Pole)
  420. else:
  421. DBSession.add(Pole)
  422. return HTTPFound(location=request.route_url('list_task')+"#"+slugify(Pole.name))
  423. return {'form':form }
  424. @view_config(route_name='action_task')
  425. def action_task(request):
  426. if request.user is None:
  427. # Don't answer to users that aren't logged
  428. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  429. if not request.user.Staff:
  430. # Don't answer to users that aren't logged
  431. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  432. action = request.matchdict.get('action')
  433. task_id = request.matchdict.get('task_id')
  434. Task = Tasks.by_id(int(task_id))
  435. if action=='close':
  436. Task.closed = True
  437. request.session.flash(('info', u'La tâche a été fermé, Félicitations !'))
  438. DBSession.merge(Task)
  439. if action=='open':
  440. Task.closed = False
  441. request.session.flash(('info', u'La tâche a été ré-ouverte !'))
  442. DBSession.merge(Task)
  443. if action=='delete':
  444. request.session.flash(('info', u'La tâche a été supprimée !'))
  445. DBSession.delete(Task)
  446. return HTTPFound(location=request.route_url('list_task')+"#"+slugify(Task.area.name))
  447. @view_config(route_name='action_task_area')
  448. def action_task_area(request):
  449. if request.user is None:
  450. # Don't answer to users that aren't logged
  451. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  452. if not request.user.Staff:
  453. # Don't answer to users that aren't logged
  454. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  455. action = request.matchdict.get('action')
  456. pole_id = request.matchdict.get('pole_id')
  457. Pole = TasksArea.by_id(int(pole_id))
  458. if not Pole:
  459. raise HTTPNotFound()
  460. if action=='delete':
  461. request.session.flash(('info', u'Le pôle a été supprimé !'))
  462. DBSession.delete(Pole)
  463. return HTTPFound(location=request.route_url('list_task'))
  464. @view_config(route_name='list_salles', renderer='jm2l:templates/Salles/list.mako')
  465. def list_salles(request):
  466. if request.user is None:
  467. # Don't answer to users that aren't logged
  468. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  469. if not request.user.Staff:
  470. # Don't answer to users that aren't logged
  471. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  472. DicSalle = {}
  473. years = DBSession.query( JM2L_Year ).all()
  474. for year in years:
  475. salles = DBSession.query( Salles )\
  476. .filter( Salles.year_uid==year.year_uid )\
  477. .order_by(Salles.name).all()
  478. DicSalle[year] = salles
  479. return {'DicSalle': DicSalle }
  480. @view_config(route_name='handle_salle', renderer='jm2l:templates/Salles/salle.mako')
  481. def handle_salle(request):
  482. if request.user is None:
  483. # Don't answer to users that aren't logged
  484. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  485. if not request.user.Staff:
  486. # Don't answer to users that aren't logged
  487. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  488. salle_id = request.matchdict.get('salle_id')
  489. if salle_id:
  490. Salle = Salles.by_id(int(salle_id))
  491. if not Salle:
  492. raise HTTPNotFound()
  493. form = EditSalleForm(request.POST, Salle, meta={'csrf_context': request.session})
  494. else:
  495. Salle = Salles()
  496. form = SalleForm(request.POST, Salle, meta={'csrf_context': request.session})
  497. form.year_uid.choices = map(tuple, DBSession.query(JM2L_Year.year_uid, JM2L_Year.year_uid).all())
  498. form.phy_salle_id.choices = map(tuple, DBSession.query(SallePhy.uid, SallePhy.name).all())
  499. if request.method == 'POST' and form.validate():
  500. form.populate_obj(Salle)
  501. if 'uid' in form._fields.keys():
  502. DBSession.merge(Salle)
  503. else:
  504. DBSession.add(Salle)
  505. return HTTPFound(location=request.route_url('list_salles'))
  506. return {'form':form }
  507. @view_config(route_name='handle_salle_phy', renderer='jm2l:templates/Salles/salle_phy.mako')
  508. def handle_salle_phy(request):
  509. if request.user is None:
  510. # Don't answer to users that aren't logged
  511. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  512. if not request.user.Staff:
  513. # Don't answer to users that aren't logged
  514. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  515. salle_id = request.matchdict.get('salle_id')
  516. if salle_id:
  517. Salle = SallePhy.by_id(int(salle_id))
  518. if not Salle:
  519. raise HTTPNotFound()
  520. form = EditSallePhyForm(request.POST, Salle, meta={'csrf_context': request.session})
  521. else:
  522. Salle = SallePhy()
  523. form = SallePhyForm(request.POST, Salle, meta={'csrf_context': request.session})
  524. if request.method == 'POST' and form.validate():
  525. form.populate_obj(Salle)
  526. Salle.slug = slugify(Salle.name)
  527. if 'uid' in form._fields.keys():
  528. DBSession.merge(Salle)
  529. else:
  530. DBSession.add(Salle)
  531. return HTTPFound(location=request.route_url('list_salles'))
  532. return {'form':form }
  533. @view_config(route_name='action_salle')
  534. def action_salle(request):
  535. if request.user is None:
  536. # Don't answer to users that aren't logged
  537. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  538. if not request.user.Staff:
  539. # Don't answer to users that aren't logged
  540. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  541. action = request.matchdict.get('action')
  542. salle_id = request.matchdict.get('salle_id')
  543. Salle = Salles.by_id(int(salle_id))
  544. if not Salle:
  545. raise HTTPNotFound()
  546. if action=='delete':
  547. request.session.flash(('info', u'La Salle a été supprimée !'))
  548. DBSession.delete(Salle)
  549. return HTTPFound(location=request.route_url('list_salles'))
  550. ## =-=- Here, We handle HTTP requests - User Logged Part -=-=
  551. @view_config(route_name='exchange', renderer="jm2l:templates/Logistique/Logistique.mako")
  552. def exchange(request):
  553. modtype = request.matchdict.get('modtype', None)
  554. action = request.matchdict.get('action', None)
  555. uid = int(request.matchdict.get('id', -1))
  556. Exch = Exchange.by_id(uid)
  557. if not Exch:
  558. MainTab = {
  559. 'Exchanges':Exchange,
  560. 'Type':modtype[-1:],
  561. 'reload':True,
  562. 'logged_in':request.authenticated_userid
  563. }
  564. return MainTab
  565. if action in ['delete', 'accept', 'refuse', 'deal']:
  566. if action=='delete': # delete exchange
  567. DBSession.delete(Exch)
  568. elif action=='accept': # accept exchange
  569. Exch.exch_done=True
  570. DBSession.merge(Exch)
  571. elif action=='refuse': # refuse exchange
  572. Exch.exch_done=False
  573. if Exch.exch_state=="Ask":
  574. Exch.provider_id = None
  575. elif Exch.exch_state=="Proposal":
  576. Exch.asker_id = None
  577. DBSession.merge(Exch)
  578. elif action=='deal':
  579. # ask to deal the exchange
  580. if Exch.exch_state=="Ask":
  581. Exch.provider_id = request.user.uid
  582. elif Exch.exch_state=="Proposal":
  583. Exch.asker_id = request.user.uid
  584. # Return javascript to parent page
  585. response = render_to_response('jm2l:templates/modals_js.mako',
  586. {'modtype':modtype, 'action':action},
  587. request=request)
  588. response.content_type = 'text/javascript'
  589. return response
  590. else:
  591. MainTab = {
  592. 'Exchanges':Exchange,
  593. 'Type':modtype[-1:],
  594. 'reload':True,
  595. 'logged_in':request.authenticated_userid
  596. }
  597. return MainTab
  598. @view_config(route_name='sejour')
  599. def sejour(request):
  600. if request.user is None:
  601. # Don't answer to users that aren't logged
  602. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  603. if request.method == 'POST':
  604. print request.POST
  605. return HTTPFound(location='/MesJM2L#Sejour')
  606. @view_config(route_name='vote_logo')
  607. def vote_logo(request):
  608. if request.user is None:
  609. # Don't answer to users that aren't logged
  610. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  611. else:
  612. vote = int(request.matchdict.get('num', -1))
  613. come = request.params.get('come_from')
  614. if vote:
  615. request.user.vote_logo=vote
  616. DBSession.merge(request.user)
  617. request.session.flash(('info',u'Votre vote à été pris en compte.'))
  618. return HTTPFound('/')
  619. else:
  620. request.session.flash(('warning',u"Votre vote n'a été pris en compte."))
  621. if come:
  622. return HTTPFound(location=come)
  623. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  624. @view_config(route_name='jm2l', renderer="jm2l:templates/jm2l.mako")
  625. def jm2l_page(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. page = int(request.params.get('page', 1))
  630. UserNum = request.params.get('user')
  631. if UserNum:
  632. profil = User.by_id(int(UserNum))
  633. if not profil:
  634. raise HTTPNotFound()
  635. if not request.user.Staff:
  636. raise HTTPForbidden(u'Vous n\'avez pas l\'autorité suffisante pour effectuer cette action.')
  637. else:
  638. profil = request.user
  639. # Build Form
  640. profil_form = ProfilForm(request.POST, profil, meta={'csrf_context': request.session})
  641. miam_form = MiamForm(request.POST, profil, meta={'csrf_context': request.session})
  642. if request.method == 'POST' and profil_form.validate():
  643. ToDelete = list()
  644. # First, we remove entries no more present
  645. for obj in profil_form.tiersship.object_data:
  646. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  647. profil_form.tiersship.entries )
  648. if not MatchEntry:
  649. ToDelete.append(obj)
  650. # Then, it's time to consider new entries
  651. for entry in profil_form.tiersship.entries:
  652. if entry.object_data is None:
  653. TmpUser = User_Tiers()
  654. entry.object_data = TmpUser
  655. profil.tiersship.append(TmpUser)
  656. profil_form.tiersship.object_data = profil.tiersship
  657. profil_form.populate_obj(profil)
  658. # We should remove it as it's not in original data
  659. for obj in ToDelete:
  660. #profil.tiersship.remove(obj)
  661. DBSession.delete(obj)
  662. profil.last_change = datetime.datetime.utcnow()
  663. profil.slug = slugify(remove_accents('%s %s' % (profil.prenom, profil.nom)).lower().strip())
  664. DBSession.merge(profil)
  665. request.session.flash(('info',u'Votre fiche a été mise à jour avec succès'))
  666. MainTab = {'participer':'active',
  667. 'Places':Place.get_list(False),
  668. 'DBTiers':Tiers,
  669. 'DBTiersOpt':TiersOpt,
  670. 'Exchanges':Exchange,
  671. 'profil_form':profil_form,
  672. 'miam_form':miam_form,
  673. 'uprofil':profil,
  674. 'logged_in':request.authenticated_userid
  675. }
  676. return MainTab
  677. @view_config(route_name='modal', renderer="jm2l:templates/modals.mako")
  678. def Modal(request):
  679. year = int(request.matchdict.get('year', None))
  680. modtype = request.matchdict.get('modtype', None)
  681. uid = int(request.matchdict.get('id', -1))
  682. session = request.session
  683. if modtype=='Password':
  684. form = UserPasswordForm(request.POST, request.user, meta={'csrf_context': request.session})
  685. if request.method == 'POST' and form.validate():
  686. response = render_to_response('jm2l:templates/modals_js.mako',
  687. {'modtype':modtype},
  688. request=request)
  689. request.user.password = form.password.data
  690. DBSession.merge(request.user)
  691. response.content_type = 'text/javascript'
  692. return response
  693. if modtype=='UserPicture':
  694. form = None
  695. if request.method == 'POST':
  696. response = render_to_response('jm2l:templates/modals_js.mako',
  697. {'modtype':modtype},
  698. request=request)
  699. response.content_type = 'text/javascript'
  700. return response
  701. if modtype=='Place':
  702. if uid>0:
  703. place = Place.by_id(uid)
  704. if not place:
  705. raise HTTPNotFound()
  706. form = PlaceUpdateForm(request.POST, place, meta={'csrf_context': request.session})
  707. else:
  708. place = Place()
  709. form = PlaceCreateForm(request.POST, meta={'csrf_context': request.session})
  710. if request.method == 'POST' and form.validate():
  711. form.populate_obj(place)
  712. place.created_by=request.user.uid
  713. if uid>0:
  714. DBSession.merge(place)
  715. else:
  716. DBSession.add(place)
  717. response = render_to_response('jm2l:templates/modals_js.mako',
  718. {'modtype':modtype},
  719. request=request)
  720. response.content_type = 'text/javascript'
  721. return response
  722. if modtype in ['AskC', 'AskH', 'AskM', 'PropC', 'PropH', 'PropM']:
  723. if uid>0:
  724. Exch = Exchange.by_id(uid)
  725. if not Exch:
  726. raise HTTPNotFound()
  727. if modtype in ['AskC','PropC']:
  728. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  729. start_place = Exch.Itin.start_place,
  730. arrival_place = Exch.Itin.arrival_place,
  731. Hour_start = Exch.start_time.strftime("%H:%M"),
  732. Day_start = Exch.start_time.strftime("%w"),
  733. exch_id = uid, meta={'csrf_context': request.session}
  734. )
  735. elif modtype in ['AskM','PropM']:
  736. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  737. description = Exch.description,
  738. exch_categ = Exch.exch_categ,
  739. Hour_start = Exch.start_time.strftime("%H:%M"),
  740. Day_start = Exch.start_time.strftime("%w"),
  741. Hour_end = Exch.end_time.strftime("%H:%M"),
  742. Day_end = Exch.end_time.strftime("%w"),
  743. exch_id = uid, meta={'csrf_context': request.session}
  744. )
  745. elif modtype in ['AskH','PropH']:
  746. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  747. description = Exch.description,
  748. exch_categ = Exch.exch_categ,
  749. Day_start = Exch.start_time.strftime("%w"),
  750. exch_id = uid, meta={'csrf_context': request.session}
  751. )
  752. # Itinerary, first get itinerary
  753. if 0:
  754. form.itin.form.start_place.data = Exch.Itin.start_place
  755. form.itin.form.arrival_place.data = Exch.Itin.arrival_place
  756. form.dateform.form.Hour.data = Exch.start_time.strftime("%H:%M")
  757. form.dateform.form.Day.data = Exch.start_time.strftime("%w")
  758. form.exch_id.data = uid
  759. else:
  760. Exch = Exchange()
  761. form = globals()["%sForm" % modtype](request.POST, meta={'csrf_context': request.session})
  762. if modtype in ['AskC', 'PropC']:
  763. # Put some place on form
  764. Places = DBSession.query(Place.place_id, Place.display_name)\
  765. .order_by('name').all()
  766. form.start_place.choices = Places
  767. form.arrival_place.choices = Places
  768. if modtype in ['PropH']:
  769. form.exch_categ.choices = DBSession.query( Exchange_Cat.cat_id, Exchange_Cat.exch_subtype)\
  770. .filter( Exchange_Cat.exch_type=='H' ).all()
  771. form.place_id.choices = DBSession.query( Place.place_id, Place.display_name)\
  772. .filter( Place.created_by==request.user.uid ).all()
  773. if modtype in ['AskM', 'PropM']:
  774. form.exch_categ.choices = DBSession.query( Exchange_Cat.cat_id, Exchange_Cat.exch_subtype)\
  775. .filter( Exchange_Cat.exch_type=='M' ).all()
  776. if request.method == 'POST' and form.validate():
  777. # Form has been validated, it's time to create our Exchange
  778. Exch.for_year = year
  779. Exch.exch_state = {'Ask':'Ask', 'Prop':'Proposal'}[modtype[:-1]]
  780. Exch.exch_type = modtype[-1:]
  781. if modtype in ['AskC', 'PropC']:
  782. # Itinerary, first Let's see if itinerary exist
  783. Itinerary = DBSession.query(Itineraire)\
  784. .filter(Itineraire.start_place==form.start_place.data) \
  785. .filter(Itineraire.arrival_place==form.arrival_place.data) \
  786. .filter(Itineraire.tr_voiture==True) \
  787. .first()
  788. if not Itinerary: # Not exist yet !
  789. Itinerary = Itineraire(start_place=form.start_place.data, \
  790. arrival_place=form.arrival_place.data, \
  791. tr_voiture=True, \
  792. created_by=1
  793. )
  794. DBSession.add(Itinerary)
  795. DBSession.flush()
  796. Exch.itin_id = Itinerary.itin_id
  797. # Start Time
  798. StartEvent = DBSession.query(JM2L_Year.start_time).filter(JM2L_Year.year_uid==year).first()
  799. Week = StartEvent[0].strftime("%W")
  800. # populate
  801. form.populate_obj(Exch)
  802. if modtype in ['AskC', 'PropC']:
  803. Exch.itin_id = Itinerary.itin_id
  804. if form._fields.has_key("Hour_start"):
  805. TargetTime = datetime.datetime.strptime('%d %d %d %s' % (year, int(Week), \
  806. int(form.Day_start.data), form.Hour_start.data), "%Y %W %w %H:%M")
  807. Exch.start_time = TargetTime
  808. elif form._fields.has_key("Day_start"):
  809. TargetTime = datetime.datetime.strptime('%d %d %d' % (year, int(Week), \
  810. int(form.Day_start.data)), "%Y %W %w")
  811. Exch.start_time = TargetTime
  812. if form._fields.has_key("Hour_end"):
  813. TargetTime = datetime.datetime.strptime('%d %d %d %s' % (year, int(Week), \
  814. int(form.Day_end.data), form.Hour_end.data), "%Y %W %w %H:%M")
  815. Exch.end_time = TargetTime
  816. elif form._fields.has_key("Day_end"):
  817. TargetTime = datetime.datetime.strptime('%d %d %d' % (year, int(Week), \
  818. int(form.Day_end.data)), "%Y %W %w")
  819. Exch.end_time = TargetTime
  820. Exch.last_change = datetime.datetime.utcnow()
  821. if Exch.exch_state=='Ask':
  822. Exch.asker_id = request.user.uid
  823. elif Exch.exch_state=='Proposal':
  824. Exch.provider_id = request.user.uid
  825. #print vars(form.itin.form)
  826. if uid>0:
  827. DBSession.merge(Exch)
  828. else:
  829. DBSession.add(Exch)
  830. response = render_to_response('jm2l:templates/modals_js.mako',
  831. {'modtype':modtype},
  832. request=request)
  833. response.content_type = 'text/javascript'
  834. return response
  835. # Fallback to HTML Display with errors
  836. return {'modtype':modtype, 'form':form, 'update':uid>0,
  837. 'logged_in':request.authenticated_userid }
  838. if modtype in ['ShowC', 'ShowH', 'ShowM']:
  839. if uid>0:
  840. Exch = Exchange.by_id(uid)
  841. if not Exch:
  842. raise HTTPNotFound()
  843. else:
  844. raise HTTPNotFound()
  845. # Show Details around the Current Exchange
  846. return {'modtype':modtype, 'Exch':Exch, 'logged_in':request.authenticated_userid }
  847. MainTab = {'modtype':modtype, 'form':form, 'update':uid>0, 'uid':uid,
  848. 'DisplayYear':year, 'session':session,
  849. 'logged_in':request.authenticated_userid }
  850. return MainTab
  851. @view_config(route_name='participer', renderer="jm2l:templates/Participer.mako")
  852. def participer(request):
  853. session = request.session
  854. session['year'] = 2015
  855. TmpUsr = User()
  856. form = UserRegisterForm(request.POST, TmpUsr, meta={'csrf_context': request.session})
  857. MyLink=None
  858. if request.method == 'POST' and form.validate():
  859. # Prepare mailer
  860. form.populate_obj(TmpUsr)
  861. TmpUsr.nom = TmpUsr.nom.capitalize()
  862. TmpUsr.prenom = TmpUsr.prenom.capitalize()
  863. TmpUsr.slug = slugify(remove_accents('%s %s' % (form.prenom.data, form.nom.data)).lower().strip())
  864. TmpUsr.password = TmpUsr.my_hash
  865. if len(TmpUsr.slug):
  866. CheckExist = DBSession.query(User)\
  867. .filter(User.slug==TmpUsr.slug)\
  868. .first()
  869. else:
  870. CheckExist=None
  871. if CheckExist:
  872. MyLink = CheckExist.my_hash
  873. NewUser = CheckExist
  874. else:
  875. DBSession.add(TmpUsr)
  876. DBSession.flush()
  877. MyLink = TmpUsr.my_hash
  878. NewUser = TmpUsr
  879. # Send the Welcome Mail
  880. mailer = request.registry['mailer']
  881. # Prepare Plain Text Message :
  882. Mail_template = Template(filename='jm2l/templates/mail_plain.mako')
  883. mail_plain = Mail_template.render(request=request, User=NewUser, action="Welcome")
  884. # Prepare HTML Message :
  885. Mail_template = Template(filename='jm2l/templates/mail_html.mako')
  886. mail_html = Mail_template.render(request=request, User=NewUser, action="Welcome")
  887. # Prepare Message
  888. message = Message(subject="[JM2L] Mon inscription au site web JM2L",
  889. sender="contact@jm2l.linux-azur.org",
  890. recipients=[NewUser.mail],
  891. body=mail_plain, html=mail_html)
  892. message.add_bcc("spam@style-python.fr")
  893. mailer.send(message)
  894. request.session.flash(('info',u"Un mail vous a été envoyé afin de continuer votre quête !"))
  895. MainTab = {'programme':'','presse':'', 'plan':'',
  896. 'participer':'active', 'form':form, "link": MyLink,
  897. 'logged_in':request.authenticated_userid }
  898. return MainTab
  899. @view_config(route_name='year')
  900. def change_year(request):
  901. year = int(request.matchdict.get('year', -1))
  902. session = request.session
  903. if year>-1:
  904. session['year'] = year
  905. return HTTPFound(location='/%s/' % year)
  906. return HTTPFound(location=request.route_url('home', year=''))
  907. @view_config(route_name='pict_user', renderer="jm2l:templates/Profil/pict_user.mako")
  908. def pict_user(request):
  909. return {"uprofil":request.user}
  910. @view_config(route_name='pict_salle', renderer="jm2l:templates/Salles/pict_salle.mako")
  911. def pict_salle(request):
  912. salle_id = int(request.matchdict.get('salle_id', -1))
  913. return {"Salles":Salles, "IdSalle":salle_id}
  914. @view_config(route_name='event', renderer="jm2l:templates/view_event.mako")
  915. def show_event(request):
  916. year = int(request.matchdict.get('year', -1))
  917. event_id = request.matchdict.get('event_id')
  918. if event_id.isdigit():
  919. TheEvent = Event.by_id(event_id)
  920. if TheEvent is None:
  921. raise HTTPNotFound()
  922. else:
  923. TheEvent = Event.by_slug(event_id, year)
  924. if TheEvent is None:
  925. raise HTTPNotFound()
  926. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  927. 'event':TheEvent, 'logged_in':request.authenticated_userid, "Salles":Salles }
  928. return MainTab
  929. @view_config(route_name='link_event_user')
  930. def link_event_user(request):
  931. """ Get user and add it to current event """
  932. year = int(request.matchdict.get('year', -1))
  933. form = AddIntervenant(request.POST, meta={'csrf_context': request.session})
  934. intervention = request.matchdict.get('intervention', None)
  935. TargetEvent = Event.by_id(form.event_uid.data)
  936. Exist = User.by_id(form.intervenant.data)
  937. if not Exist:
  938. request.session.flash(('error',u"Une erreur s'est produite lors de l'ajout de votre intervenant !"))
  939. return HTTPFound(location=request.route_url('edit_event', sep='/',
  940. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  941. else:
  942. TargetUser = Exist
  943. uev = User_Event(year_uid=year, role=u"Animateur d'un évenement JM2L", user_uid=TargetUser.uid)
  944. TargetEvent.interventions.append( uev )
  945. return HTTPFound(location=request.route_url('edit_event', sep='/',
  946. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  947. @view_config(route_name='link_event_tiers')
  948. def link_event_tiers(request):
  949. """ Create user if not exist, add it to current event """
  950. year = int(request.matchdict.get('year', -1))
  951. form = AddTiers(request.POST, meta={'csrf_context': request.session})
  952. intervention = request.matchdict.get('intervention', None)
  953. TargetEvent = Event.by_id(form.event_uid.data)
  954. Exist = Tiers.by_id(form.tiers.data)
  955. if not Exist:
  956. request.session.flash(('error',u"Une erreur s'est produite lors de l'ajout de votre entité !"))
  957. return HTTPFound(location=request.route_url('edit_event', sep='/',
  958. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  959. else:
  960. TargetTiers = Exist
  961. if len(DBSession.query(Role_Tiers)\
  962. .filter(Role_Tiers.year_uid==year)\
  963. .filter(Role_Tiers.tiers_role=="Exposant")\
  964. .filter(Role_Tiers.tiers_uid==TargetTiers.uid)\
  965. .all())==0:
  966. tev = Role_Tiers(year_uid=year, tiers_role="Exposant", tiers_uid=TargetTiers.uid)
  967. DBSession.add(tev)
  968. return HTTPFound(location=request.route_url('edit_event', sep='/',
  969. year=str(year), intervention=intervention, event_id=str(TargetEvent.uid)))
  970. @view_config(route_name='edit_event', renderer="jm2l:templates/edit_event.mako")
  971. def edit_event(request):
  972. year = int(request.matchdict.get('year', -1))
  973. event_id = request.matchdict.get('event_id')
  974. intervention = request.matchdict.get('intervention', None)
  975. IntervLabel = intervention.replace('_',' ').lower()
  976. if intervention=='Conference':
  977. IntervLabel = u'conférence'
  978. # Check intervention
  979. if not intervention in ['Stand', 'Table ronde', 'Atelier', 'Conference', 'Concert']:
  980. raise HTTPNotFound(u"Ce type d'évenement n'est pas reconnu")
  981. TheYear = DBSession.query(JM2L_Year)\
  982. .filter(JM2L_Year.year_uid==year)\
  983. .first()
  984. # Check year avaibility
  985. if not TheYear:
  986. raise HTTPNotFound(u"Cette année n'est pas pris en charge")
  987. # Generate Timeslots for current year
  988. TimeSlots = list(enumerate( [ x.strftime('%a %d %b %H:%M') for x in
  989. TheYear.AvailableTimeSlots ] ))
  990. if event_id:
  991. # We try to update an existing record
  992. if event_id.isdigit():
  993. TheEvent = Event.by_id(event_id)
  994. if TheEvent is None:
  995. raise HTTPNotFound(u"Cette réference n'existe pas")
  996. else:
  997. TheEvent = Event.by_slug(event_id, year)
  998. if TheEvent is None:
  999. raise HTTPNotFound(u"Cette réference n'existe pas")
  1000. if request.user is None or not (request.user.Staff or request.user in TheEvent.intervenants):
  1001. raise HTTPForbidden(u"Vous n'êtes pas identifié comme étant un participant à cette intervention.")
  1002. # Compute some field value from selected event
  1003. if TheEvent.start_time in TheYear.AvailableTimeSlots:
  1004. start_sel = TheYear.AvailableTimeSlots.index(TheEvent.start_time)
  1005. else:
  1006. start_sel = len(TimeSlots)
  1007. TimeSlots.append( (len(TimeSlots), TheEvent.start_time.strftime('%a %d %b %H:%M')))
  1008. duration = (TheEvent.end_time - TheEvent.start_time).total_seconds()/60
  1009. end = TheEvent.start_time + datetime.timedelta(minutes=duration)
  1010. # prepare the form with update
  1011. form = ConfUpdateForm(request.POST, TheEvent, start_sel=start_sel, duration=duration, end_time=end,
  1012. meta={'csrf_context': request.session} )
  1013. # Customize labels
  1014. form.name.label.text += IntervLabel
  1015. form.description.label.text += IntervLabel
  1016. # Each event can get severals members
  1017. formAdd = AddIntervenant(event_uid=TheEvent.uid)
  1018. # Build list of intervenant
  1019. # Get users from db
  1020. Users = DBSession.query(User)\
  1021. .filter(User.Staff==1)\
  1022. .order_by('nom').all()
  1023. # Put some users on form
  1024. formAdd.intervenant.choices = [(u.uid, "%s %s" % (u.nom, u.prenom))
  1025. for u in Users]
  1026. # Each event can get severals entities
  1027. formAddT = AddTiers(event_uid=TheEvent.uid)
  1028. # Build list of entities
  1029. # Get entities from db
  1030. TmpTiers = DBSession.query(Tiers)\
  1031. .order_by('name').limit(10)
  1032. # Put some entities on form
  1033. formAddT.tiers.choices = [(u.uid, "%s %s" % (u.nom, u.prenom))
  1034. for u in Users]
  1035. else:
  1036. TheEvent = Event()
  1037. # prepare the form for creation
  1038. form = ConfCreateForm(request.POST,
  1039. event_type=intervention,
  1040. for_year=str(year), meta={'csrf_context': request.session}
  1041. )
  1042. # Customize labels
  1043. form.name.label.text += IntervLabel
  1044. form.description.label.text += IntervLabel
  1045. duration=60
  1046. # No intervenant
  1047. formAdd = None
  1048. formAddT = None
  1049. SalleDispo = DBSession.query(Salles)\
  1050. .filter(Salles.year_uid==year)\
  1051. .order_by('name')
  1052. if intervention=="Conference":
  1053. form.duration.choices =[
  1054. (15,u'Lighting talk ( 5 min)'),
  1055. (30,u'Conférence (20 min)'),
  1056. (60,u'Conférence (50 min)'),
  1057. (90,u'Conférence (75 min)'),
  1058. ]
  1059. if not duration in [15, 30, 60, 90]:
  1060. form.duration.choices.append( (duration,u'Conférence (%d min)' % duration) )
  1061. if not form._fields.has_key("uid"):
  1062. form.duration.data=60
  1063. SalleDispo = SalleDispo.filter(Salles.place_type=='Conference')
  1064. elif intervention=="Stand":
  1065. form.duration.choices =[
  1066. (8*60, u'Toute la journée'),
  1067. (4*60, u'une demi-journée')
  1068. ]
  1069. SalleDispo = SalleDispo.filter(Salles.place_type=='Stand')
  1070. elif intervention=="Atelier":
  1071. form.duration.choices = map( lambda d:(d, u'Atelier (%dh%.2d)' % (d/60, d%60) ), \
  1072. [60, 90, 120, 150, 180, 210, 240] )
  1073. if not duration in map(lambda (d,y): d, form.duration.choices):
  1074. form.duration.choices.append( (duration,u'Atelier (%dh%.2d)' % (duration/60, duration%60) ) )
  1075. SalleDispo = SalleDispo.filter(Salles.place_type=='Ateliers')
  1076. elif intervention=="Table ronde":
  1077. form.duration.choices = map( lambda d:(d, u'Table ronde (%dh%.2d)' % (d/60, d%60) ), \
  1078. [60, 90, 120, 150] )
  1079. if not duration in map(lambda (d,y): d, form.duration.choices):
  1080. form.duration.choices.append( (duration,u'Table ronde (%dh%.2d)' % (duration/60, duration%60) ) )
  1081. SalleDispo = SalleDispo.filter(Salles.place_type=='Conference')
  1082. else:
  1083. raise HTTPForbidden(u"Pas encore disponible.")
  1084. form.salle_uid.choices = [(s.salle_id, s.name) for s in SalleDispo]
  1085. form.start_sel.choices = TimeSlots
  1086. if request.method == 'POST' and form.validate():
  1087. form.populate_obj(TheEvent)
  1088. TheEvent.start_time = TheYear.AvailableTimeSlots[form.start_sel.data]
  1089. TheEvent.end_time = TheEvent.start_time + datetime.timedelta(minutes=form.duration.data)
  1090. # Ok, time to put in database
  1091. if not form._fields.has_key("uid"):
  1092. TheEvent.slug = slugify(TheEvent.name)
  1093. DBSession.add(TheEvent)
  1094. # Append creator by default
  1095. if request.user.uid!=1:
  1096. uev = User_Event(year_uid=TheYear.year_uid, role="Animateur")
  1097. uev.user_uid = request.user.uid
  1098. TheEvent.interventions.append( uev )
  1099. DBSession.flush()
  1100. request.session.flash(('sucess',u'Votre intervention a été créee !'))
  1101. return HTTPFound(location=request.route_url('edit_event', sep='/',
  1102. year=str(year), intervention=intervention, event_id=str(TheEvent.slug)))
  1103. else:
  1104. DBSession.merge(TheEvent)
  1105. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1106. 'event':TheEvent, 'form':form, 'formAdd':formAdd, 'formAddT':formAddT,
  1107. 'Salles':Salles,
  1108. 'logged_in':request.authenticated_userid }
  1109. return MainTab
  1110. @view_config(route_name='entities', renderer="jm2l:templates/list_tiers.mako")
  1111. def list_tiers(request):
  1112. Entities = dict()
  1113. EntityType = DBSession.query(TiersOpt.entity_type)\
  1114. .group_by(TiersOpt.entity_type).all()
  1115. for EType in EntityType:
  1116. Entities[EType.entity_type] = DBSession.query(Tiers).join(TiersOpt)\
  1117. .filter(TiersOpt.entity_type==EType.entity_type)\
  1118. .order_by(TiersOpt.entity_subtype, Tiers.name)
  1119. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1120. 'entities':Entities, 'logged_in':request.authenticated_userid }
  1121. return MainTab
  1122. @view_config(route_name='show_entity', renderer="jm2l:templates/view_tiers.mako")
  1123. def show_tiers(request):
  1124. tiers_type = request.matchdict.get('tiers_type')
  1125. entity_id = request.matchdict.get('entity_id')
  1126. if entity_id.isdigit():
  1127. TheTiers = Tiers.by_id(entity_id)
  1128. if TheTiers is None:
  1129. raise HTTPNotFound()
  1130. else:
  1131. TheTiers = Tiers.by_slug(entity_id)
  1132. if TheTiers is None:
  1133. raise HTTPNotFound()
  1134. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1135. 'entity':TheTiers, 'logged_in':request.authenticated_userid }
  1136. return MainTab
  1137. @view_config(route_name='delete_entity')
  1138. def delete_tiers(request):
  1139. entity_id = request.matchdict.get('entity_id', None)
  1140. if entity_id:
  1141. if entity_id.isdigit():
  1142. TheTiers = Tiers.by_id(int(entity_id))
  1143. if TheTiers is None:
  1144. raise HTTPNotFound()
  1145. else:
  1146. TheTiers = Tiers.by_slug(entity_id)
  1147. if TheTiers is None:
  1148. raise HTTPNotFound()
  1149. if len(TheTiers.membership)!=0:
  1150. request.session.flash(('error', u"Vous devez supprimer tous les membres liés avant la suppression d'une entité."))
  1151. return HTTPFound(location=request.route_url('show_entity', entity_id=TheTiers.slug, tiers_type=TheTiers.get_entity_type.slug_entity_type))
  1152. if len(TheTiers.membership)!=0:
  1153. request.session.flash(('error', u"Vous devez supprimer tous les roles liés avant la suppression d'une entité."))
  1154. return HTTPFound(location=request.route_url('show_entity', entity_id=TheTiers.slug, tiers_type=TheTiers.get_entity_type.slug_entity_type))
  1155. DBSession.delete(TheTiers)
  1156. request.session.flash(('info', u"L'entité a bien été supprimée"))
  1157. return HTTPFound(location=request.route_url('entities'))
  1158. else:
  1159. raise HTTPNotFound()
  1160. @view_config(route_name='add_entity', renderer="jm2l:templates/edit_tiers.mako")
  1161. @view_config(route_name='edit_entity', renderer="jm2l:templates/edit_tiers.mako")
  1162. def edit_tiers(request):
  1163. entity_id = request.matchdict.get('entity_id', None)
  1164. TargetList = list()
  1165. if request.user is None:
  1166. # Don't answer to users that aren't logged
  1167. raise HTTPForbidden(u'Vous devez vous identifier pour obtenir une réponse.')
  1168. entity_types = DBSession.query(TiersOpt.entity_type).group_by(TiersOpt.entity_type).all()
  1169. for entity_type in entity_types:
  1170. entity_subtypes = DBSession.query(TiersOpt)\
  1171. .filter(TiersOpt.entity_type==entity_type.entity_type)\
  1172. .group_by(TiersOpt.entity_subtype).all()
  1173. ListType = [(i.uid, i.entity_subtype) for i in entity_subtypes]
  1174. TargetList.append( (entity_type.entity_type, ListType) )
  1175. if entity_id:
  1176. if entity_id.isdigit():
  1177. TheTiers = Tiers.by_id(entity_id)
  1178. if TheTiers is None:
  1179. raise HTTPNotFound()
  1180. else:
  1181. TheTiers = Tiers.by_slug(entity_id)
  1182. if TheTiers is None:
  1183. raise HTTPNotFound()
  1184. form = UpdateTiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  1185. UserOptions = DBSession.query(TiersOpt)\
  1186. .filter(TiersOpt.entity_type==TheTiers.tiers_type)\
  1187. .all()
  1188. form.tiers_type.choices = TargetList
  1189. else:
  1190. TheTiers = Tiers()
  1191. # prepare the form for creation
  1192. form = TiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  1193. form.tiers_type.choices = TargetList
  1194. UserOptions = list()
  1195. #test_form = TiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  1196. if request.method == 'POST' and form.validate():
  1197. ToDelete = list()
  1198. ToDeleteR = list()
  1199. # First, we remove entries no more present
  1200. for obj in form.membership.object_data:
  1201. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  1202. form.membership.entries )
  1203. if not MatchEntry:
  1204. ToDelete.append(obj)
  1205. # For roles too
  1206. for obj in form.roles.object_data:
  1207. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  1208. form.roles.entries )
  1209. if not MatchEntry:
  1210. ToDeleteR.append(obj)
  1211. # We should remove it as it's not in original data
  1212. for obj in ToDelete:
  1213. TheTiers.membership.remove(obj)
  1214. DBSession.delete(obj)
  1215. # For roles too
  1216. for obj in ToDeleteR:
  1217. TheTiers.roles.remove(obj)
  1218. DBSession.delete(obj)
  1219. # Then, it's time to consider new entries
  1220. for entry in form.membership.entries:
  1221. if entry.object_data is None:
  1222. TmpUser = User_Tiers()
  1223. entry.object_data = TmpUser
  1224. TheTiers.membership.append(TmpUser)
  1225. form.membership.object_data = TheTiers.membership
  1226. # For roles too
  1227. for entry in form.roles.entries:
  1228. if entry.object_data is None:
  1229. TmpRole = Role_Tiers()
  1230. entry.object_data = TmpRole
  1231. TheTiers.roles.append(TmpRole)
  1232. form.roles.object_data = TheTiers.roles
  1233. form.populate_obj(TheTiers)
  1234. # Handle Remove of accents
  1235. TheTiers.slug = slugify(form.name.data)
  1236. if not form._fields.has_key('uid'):
  1237. TheTiers.creator_id = request.user.uid
  1238. DBSession.add(TheTiers)
  1239. DBSession.flush()
  1240. return HTTPFound(location=request.route_url('edit_entity', sep='/',
  1241. entity_id=str(TheTiers.slug), tiers_type=TheTiers.get_entity_type.entity_type))
  1242. DBSession.merge(TheTiers)
  1243. return HTTPFound(location=request.route_url('show_entity', entity_id=TheTiers.slug,
  1244. tiers_type=TheTiers.get_entity_type.slug_entity_type))
  1245. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1246. 'form':form, 'DBUser':User, 'UserOptions':UserOptions,
  1247. 'logged_in':request.authenticated_userid }
  1248. return MainTab
  1249. @view_config(route_name='edit_entity_cat', renderer="jm2l:templates/edit_tiers_categ.mako")
  1250. def edit_tiers_category(request):
  1251. DicResult = dict()
  1252. ListChanges = list()
  1253. if request.method == 'POST':
  1254. # Reformat data
  1255. RegExist = re.compile('collection\[(?P<slug>[\w-]+)\]\[(?P<num>\d+)\]\[(?P<id>\d+)\]')
  1256. RegTitle = re.compile('collection\[(?P<slug>[\w-]+)\]\[title]')
  1257. RegNew = re.compile('collection\[(?P<slug>[\w-]+)\]\[(?P<num>\d+)\]\[id\]')
  1258. for key, value in request.POST.iteritems():
  1259. regN= RegNew.match(key)
  1260. regT= RegTitle.match(key)
  1261. reg = RegExist.match(key)
  1262. if reg:
  1263. if not DicResult.has_key(reg.group('slug')):
  1264. DicResult[reg.group('slug')] = dict()
  1265. if DicResult[reg.group('slug')].has_key('items'):
  1266. DicResult[reg.group('slug')]['items'].append( ( int(reg.group('id')), value ) )
  1267. else:
  1268. DicResult[reg.group('slug')]['items'] = [ ( int(reg.group('id')), value ) ]
  1269. elif regN:
  1270. if not DicResult.has_key(regN.group('slug')):
  1271. DicResult[regN.group('slug')] = dict()
  1272. if DicResult[regN.group('slug')].has_key('items'):
  1273. DicResult[regN.group('slug')]['items'].append( ( 'id', value ) )
  1274. else:
  1275. DicResult[regN.group('slug')]['items'] = [ ( 'id', value ) ]
  1276. ListChanges.append(('add', 0, DicResult[regN.group('slug')]['title'], value))
  1277. elif regT:
  1278. if not DicResult.has_key(regT.group('slug')):
  1279. DicResult[regT.group('slug')] = dict()
  1280. DicResult[regT.group('slug')]['title'] = value
  1281. else:
  1282. raise
  1283. for opt in DBSession.query(TiersOpt).all():
  1284. if DicResult.has_key(opt.slug_entity_type):
  1285. found = filter( lambda (x,y): opt.uid==x,
  1286. DicResult[opt.slug_entity_type].get('items', []))
  1287. if not found:
  1288. ListChanges.append(('remove', opt.uid, opt.entity_type, opt.entity_subtype))
  1289. else:
  1290. for tst in found:
  1291. # Check changes on Cat Name
  1292. if DicResult[opt.slug_entity_type]['title']!=opt.entity_type or \
  1293. tst[1]!=opt.entity_subtype:
  1294. ListChanges.append(('changed', opt.uid,
  1295. DicResult[opt.slug_entity_type]['title'],
  1296. tst[1]))
  1297. else:
  1298. ListChanges.append(('remove', opt.uid, opt.entity_type, opt.entity_subtype))
  1299. # Do The change
  1300. for action, uid, entity, subentity in ListChanges:
  1301. if action=="changed":
  1302. opt = TiersOpt.by_id(uid)
  1303. opt.entity_type = entity
  1304. opt.entity_subtype = subentity
  1305. elif action=="remove":
  1306. opt = TiersOpt.by_id(uid)
  1307. DBSession.delete(opt)
  1308. elif action=="add":
  1309. opt = TiersOpt()
  1310. opt.entity_type = entity
  1311. opt.entity_subtype = subentity
  1312. DBSession.add(opt)
  1313. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1314. 'logged_in':request.authenticated_userid, 'TiersOpt':TiersOpt }
  1315. return MainTab
  1316. @view_config(route_name='show_user', renderer="jm2l:templates/view_user.mako")
  1317. def show_user(request):
  1318. user_slug = request.matchdict.get('user_slug', None)
  1319. if user_slug is None or len(user_slug)==0:
  1320. raise HTTPNotFound(u"Cet utilisateur n'a pas été reconnu")
  1321. # Query database
  1322. DispUser = User.by_slug(user_slug)
  1323. if DispUser is None:
  1324. raise HTTPNotFound()
  1325. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  1326. 'DispUser':DispUser, 'logged_in':request.authenticated_userid }
  1327. return MainTab
  1328. #@view_config(route_name='link_user_entity')
  1329. def link_user_entity(request):
  1330. uid = int(request.matchdict.get('uid', -1))
  1331. year = int(request.matchdict.get('year', -1))
  1332. user_id = int(request.matchdict.get('uid', -1))
  1333. TheTiers = Tiers.by_id(uid)
  1334. if TheTiers is None:
  1335. raise HTTPNotFound()
  1336. return HTTPFound(location=request.route_url('edit_entity', uid=uid) )
  1337. #@view_config(route_name='link_role_entity')
  1338. def link_role_entity(request):
  1339. uid = int(request.matchdict.get('uid', -1))
  1340. year = int(request.matchdict.get('year', -1))
  1341. role_id = int(request.matchdict.get('role_id', -1))
  1342. TheTiers = Tiers.by_id(uid)
  1343. if TheTiers is None:
  1344. raise HTTPNotFound()
  1345. return HTTPFound(location=request.route_url('edit_entity', uid=uid) )
  1346. @forbidden_view_config()
  1347. def forbidden(reason, request):
  1348. if 'ident' in reason.detail:
  1349. request.session.flash(('info', reason.detail))
  1350. return HTTPFound(location='/sign/login' )
  1351. else:
  1352. request.response.status = 403
  1353. return render_to_response('jm2l:templates/Errors/403.mako', { "reason":reason },
  1354. request=request)
  1355. @notfound_view_config()
  1356. def notfound(reason, request):
  1357. request.response.status = 404
  1358. return render_to_response('jm2l:templates/Errors/404.mako', { "reason":reason },
  1359. request=request)