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.
 
 
 
 
 

1034 lines
44 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. # Import Web Forms
  9. from .forms import *
  10. # Database access imports
  11. from .models import *
  12. from sqlalchemy.exc import DBAPIError
  13. from sqlalchemy import func, or_
  14. # Usefull tools
  15. from slugify import slugify
  16. from icalendar import Calendar
  17. from pytz import timezone
  18. from icalendar import Event as Evt
  19. # Then, standard libs
  20. import webhelpers.paginate as paginate
  21. import unicodedata
  22. import time
  23. import datetime
  24. import re
  25. CurrentYear = 2015
  26. ## =-=- Here, We keep some usefull function -=-=
  27. def remove_accents(input_str):
  28. """ This function is intended to remove all accent from input unicode string """
  29. nkfd_form = unicodedata.normalize('NFKD', input_str)
  30. only_ascii = nkfd_form.encode('ASCII', 'ignore')
  31. return only_ascii
  32. @view_config(route_name='tester', renderer="jm2l:templates/tester.mako")
  33. def Tester(request):
  34. JTiers = DBSession.query(Tiers).all()
  35. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  36. 'Tiers':JTiers, "logged_in":request.authenticated_userid }
  37. return MainTab
  38. ## =-=- Here, We handle ICal requests -=-=
  39. @view_config(route_name='progr_iCal', renderer="string")
  40. def ICal_Progamme_Request(request):
  41. year = int(request.matchdict.get('year', CurrentYear))
  42. # Initialization
  43. DicResult = dict()
  44. # Query database
  45. # Compute days used by all events matching the specified input year
  46. Events = DBSession.query(Event)\
  47. .filter(Event.for_year == year)\
  48. .filter(Event.event_type != 'Stand')\
  49. .order_by(Event.start_time)
  50. cal = Calendar()
  51. cal.add('prodid', '-//Programme %d//jm2l.linux-azur.org//' % year)
  52. cal.add('version', '2.0')
  53. tz = timezone('Europe/Paris')
  54. for ev in Events:
  55. if ev.event_type:
  56. event = Evt()
  57. event['uid'] = "%d/%d" % ( year, ev.uid )
  58. event.add('summary', ev.name )
  59. event.add('dtstart', ev.start_time.replace(tzinfo=tz) )
  60. event.add('dtend', ev.end_time.replace(tzinfo=tz) )
  61. event.add('created', ev.last_change.replace(tzinfo=tz) )
  62. event.add('description', "http://www.linux-azur.org/event/%s/%s" % (ev.for_year, ev.slug) )
  63. event.add('url', "http://www.linux-azur.org/event/%s/%s" % (ev.for_year, ev.slug) )
  64. event.add('priority', 5)
  65. cal.add_component(event)
  66. return cal.to_ical()
  67. ## =-=- Here, We handle Json requests -=-=
  68. @view_config(route_name='users_json', renderer="json")
  69. def JSON_User_Request(request):
  70. """ Build a JSON answer with active users and pagination handling """
  71. # Check arguments consitency
  72. pageSize = request.params.get('pageSize',"8")
  73. current_page = request.params.get('pageNum',"1")
  74. UserQuery = request.params.get('searchTerm', u"")
  75. # Don't answer to users that aren't logged
  76. if not request.user:
  77. return HTTPUnauthorized('You have to be logged to hope an answer.')
  78. # Check consistancy of parameters
  79. if pageSize.isdigit() and current_page.isdigit():
  80. current_page = int(current_page)
  81. pageSize = int(pageSize)
  82. else:
  83. return HTTPBadRequest('pageSize and pageNum accept only digits.')
  84. # Query database
  85. Users = DBSession.query(User.uid, User.nom, User.prenom)\
  86. .filter(User.slug.contains( remove_accents(UserQuery) ))
  87. page_url = paginate.PageURL_WebOb(request)
  88. records = paginate.Page(Users, current_page, url=page_url, items_per_page=pageSize)
  89. ListMatchUser = map( lambda u:{"id": u.uid, "text":"%s %s" % ( u.prenom, u.nom )}, records )
  90. return { "Results": ListMatchUser, "Total":records.item_count,
  91. "logged_in":request.authenticated_userid }
  92. @view_config(route_name='tiers_json', renderer="json")
  93. def JSON_Tiers_Request(request):
  94. """ Build a JSON answer with active users and pagination handling """
  95. # Check arguments consitency
  96. pageSize = request.params.get('pageSize',"8")
  97. current_page = request.params.get('pageNum',"1")
  98. TiersQuery = request.params.get('searchTerm', u"")
  99. # Don't answer to users that aren't logged
  100. if not request.user:
  101. return HTTPUnauthorized('You have to be logged to hope an answer.')
  102. # Check consistancy of parameters
  103. if pageSize.isdigit() and current_page.isdigit():
  104. current_page = int(current_page)
  105. pageSize = int(pageSize)
  106. else:
  107. return HTTPBadRequest('pageSize and pageNum accept only digits.')
  108. # Query database
  109. JTiers = DBSession.query(Tiers.uid, Tiers.name)\
  110. .filter(Tiers.slug.contains( remove_accents(TiersQuery) ))
  111. page_url = paginate.PageURL_WebOb(request)
  112. records = paginate.Page(JTiers, current_page, url=page_url, items_per_page=pageSize)
  113. ListMatchTiers = map( lambda t:{"id": t.uid, "text": t.name }, records )
  114. return { "Results": ListMatchTiers, "Total":records.item_count,
  115. "logged_in":request.authenticated_userid }
  116. @view_config(route_name='progr_json', renderer="json")
  117. def JSON_Progamme_Request(request):
  118. year = int(request.matchdict.get('year', CurrentYear))
  119. # Initialization
  120. DicResult = dict()
  121. # Query database
  122. # Compute days used by all events matching the specified input year
  123. Days = DBSession.query( func.strftime('%d', Event.start_time).label('day') )\
  124. .filter(Event.for_year == year)\
  125. .filter(Event.event_type != None)\
  126. .group_by(func.strftime('%d', Event.start_time)).all()
  127. for Day in Days:
  128. Events = DBSession.query(Event)\
  129. .filter(Event.for_year == year)\
  130. .filter(Event.event_type != 'Stand')\
  131. .filter("strftime('%d', start_time) = :dow").params(dow=Day.day)\
  132. .order_by(Event.start_time)
  133. ListEv = []
  134. for ev in Events:
  135. if ev.event_type:
  136. ListEv.append( {
  137. "uid":"%d/%d" % ( year, ev.uid ),
  138. "desc":ev.name,
  139. "startDate":ev.start_time.strftime('%Y-%m-%dT%H:%M:%S'),
  140. "endDate":ev.end_time.strftime('%Y-%m-%dT%H:%M:%S'),
  141. "placeName":ev.Salle and (ev.Salle.name or "unk") ,
  142. "status":ev.event_type
  143. } )
  144. DicResult[Day.day] = ListEv
  145. return { 'all':DicResult }
  146. @view_config(route_name='timeline_json', renderer="json")
  147. def JSON_TimeLine_Request(request):
  148. year = int(request.matchdict.get('year', CurrentYear))
  149. # Initialization
  150. DicResult = dict()
  151. # Query database
  152. # Compute days used by all events matching the specified input year
  153. Days = DBSession.query( func.strftime('%d', Event.start_time).label('day') )\
  154. .filter(Event.for_year == year)\
  155. .filter(Event.event_type != None)\
  156. .group_by(func.strftime('%d', Event.start_time)).all()
  157. ListEv = []
  158. for Day in Days:
  159. Events = DBSession.query(Event)\
  160. .filter(Event.for_year == year)\
  161. .filter(Event.event_type != 'Stand')\
  162. .filter("strftime('%d', start_time) = :dow").params(dow=Day.day)\
  163. .order_by(Event.start_time)
  164. ListEv = []
  165. for ev in Events:
  166. if ev.event_type:
  167. ListEv.append( {
  168. #"uid":"%d/%d" % ( year, ev.uid ),
  169. "headline":ev.name,
  170. "startDate":ev.start_time.strftime('%Y,%m,%d,%H,%M'),
  171. "endDate":ev.end_time.strftime('%Y,%m,%d,%H,%M'),
  172. "text":ev.Salle and (ev.Salle.name or "unk"),
  173. "tags":ev.Salle and (ev.Salle.name or "unk") ,
  174. #"status":ev.event_type,
  175. "asset": {
  176. "media":"", #http://jm2l.linux-azur.org/sites/jm2l.linux-azur.org/files/videos/2012/2012_Introduction_aux_logiciels_libres__Frederic_Couchet.ogv",
  177. "credit":"",
  178. "caption":"" }
  179. } )
  180. break
  181. DicResult = {
  182. "lang":"fr",
  183. "headline":"JM2L 2015",
  184. "type":"default",
  185. "startDate":"2015,11,28,10",
  186. "text":"<i><span class='c1'>9ème Édition</span></i>",
  187. "asset":
  188. {
  189. "media":"",
  190. "credit":"JM2L",
  191. "caption":""
  192. }
  193. }
  194. DicResult["date"] = ListEv
  195. return { 'timeline':DicResult }
  196. ## =-=- Here, We handle HTTP requests - Public Part -=-=
  197. @view_config(route_name='home', renderer="jm2l:templates/NewIndex.mako")
  198. def index_page(request):
  199. page = int(request.params.get('page', 1))
  200. paginator = Entry.get_paginator(request, page)
  201. profil = User.by_id(4)
  202. profil_form = ProfilForm(request.POST, profil, meta={'csrf_context': request.session})
  203. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'', 'paginator':paginator,
  204. "logged_in":request.authenticated_userid }
  205. return MainTab
  206. @view_config(route_name='programme', renderer="jm2l:templates/Public/Programme.mako")
  207. def programme(request):
  208. year = int(request.matchdict.get('year'))
  209. if 2006 > year:
  210. return HTTPBadRequest('The first JM2L event was in 2006.')
  211. # Query database about selected Year.
  212. Events = DBSession.query(Event)\
  213. .filter(Event.for_year == year)\
  214. .order_by(Event.start_time)
  215. Days = DBSession.query(func.strftime('%d-%m-%Y', Event.start_time))\
  216. .filter(Event.for_year == year)\
  217. .filter(Event.event_type != None)\
  218. .group_by(func.strftime('%d', Event.start_time)).all()
  219. ListDay = []
  220. for day in Days:
  221. RefDay = datetime.datetime.strptime(day[0],'%d-%m-%Y')
  222. ListDay.append( ( RefDay.strftime('%A %d %b %Y'),
  223. RefDay.strftime('%d') ) )
  224. MainTab = {'programme':'active','presse':'', 'plan':'', 'participer':'', 'DisplayYear':year, \
  225. 'Events':Events, 'Event':Event, 'Days':ListDay, "logged_in":request.authenticated_userid }
  226. return MainTab
  227. @view_config(route_name='presse', renderer="jm2l:templates/Public/Presse.mako")
  228. def static_presse(request):
  229. year = int(request.matchdict.get('year', None))
  230. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==year).first()
  231. MainTab = {'programme':'','presse':'active', 'plan':'', 'participer':'',
  232. "logged_in":request.authenticated_userid, 'content':content, 'DisplayYear':year}
  233. return MainTab
  234. @view_config(route_name='edit_presse', renderer="jm2l:templates/Staff/EditPresse.mako")
  235. def edit_presse(request):
  236. year = int(request.matchdict.get('year', None))
  237. content = DBSession.query(JM2L_Year).filter(JM2L_Year.year_uid==year).first()
  238. form = DossPresse(request.POST, content, meta={'csrf_context': request.session})
  239. if request.method == 'POST' and form.validate():
  240. form.populate_obj(content)
  241. MainTab = {'programme':'','presse':'active', 'plan':'', 'participer':'',
  242. "logged_in":request.authenticated_userid, 'form':form, 'DisplayYear':year}
  243. return MainTab
  244. @view_config(route_name='plan', renderer="jm2l:templates/Public/Plan.mako")
  245. def static_plan(request):
  246. MainTab = {'programme':'','presse':'', 'plan':'active', 'participer':'',
  247. "logged_in":request.authenticated_userid }
  248. return MainTab
  249. ## =-=- Here, We handle HTTP requests - Staff Logged Part -=-=
  250. @view_config(route_name='list_task', renderer='jm2l:templates/Staff/list.mako')
  251. def list_view(request):
  252. DicTask = {}
  253. taskgroup = DBSession.query( TasksArea ).all()
  254. for grp in taskgroup:
  255. tasks = DBSession.query( Tasks )\
  256. .filter( Tasks.area_uid==grp.uid )\
  257. .order_by(Tasks.closed, Tasks.due_date).all()
  258. DicTask[grp] = tasks
  259. return {'tasks': DicTask }
  260. @view_config(route_name='handle_task', renderer='jm2l:templates/Staff/tasks.mako')
  261. def tasks(request):
  262. task_id = request.matchdict.get('task_id')
  263. if task_id:
  264. Task = Tasks.by_id(int(task_id))
  265. if not Task:
  266. raise HTTPNotFound()
  267. form = EditStaffTasks(request.POST, Task, meta={'csrf_context': request.session})
  268. else:
  269. Task = Tasks()
  270. form = StaffTasks(request.POST, Task, meta={'csrf_context': request.session})
  271. # Put some areas on form
  272. Areas = DBSession.query(TasksArea.uid, TasksArea.name)\
  273. .order_by('name').all()
  274. form.area_uid.choices = Areas
  275. # Put some users on form
  276. Users = DBSession.query(User)\
  277. .filter(User.Staff==1)\
  278. .order_by('nom').all()
  279. form.closed_by.choices = [(u.uid, "%s %s" % (u.nom, u.prenom))
  280. for u in Users]
  281. if request.method == 'POST' and form.validate():
  282. form.populate_obj(Task)
  283. Task.closed = False
  284. if 'uid' in form._fields.keys():
  285. DBSession.merge(Task)
  286. else:
  287. DBSession.add(Task)
  288. return HTTPFound(location=request.route_url('list_task'))
  289. return {'form':form }
  290. @view_config(route_name='handle_pole', renderer='jm2l:templates/Staff/pole.mako')
  291. def tasks_area(request):
  292. pole_id = request.matchdict.get('pole_id')
  293. if pole_id:
  294. Pole = TasksArea.by_id(int(pole_id))
  295. if not Pole:
  296. raise HTTPNotFound()
  297. form = EditStaffArea(request.POST, Pole, meta={'csrf_context': request.session})
  298. else:
  299. Pole = TasksArea()
  300. form = StaffArea(request.POST, Pole, meta={'csrf_context': request.session})
  301. if request.method == 'POST' and form.validate():
  302. form.populate_obj(Pole)
  303. if 'uid' in form._fields.keys():
  304. DBSession.merge(Pole)
  305. else:
  306. DBSession.add(Pole)
  307. return HTTPFound(location=request.route_url('list_task'))
  308. return {'form':form }
  309. @view_config(route_name='action_task')
  310. def action_task(request):
  311. action = request.matchdict.get('action')
  312. task_id = request.matchdict.get('task_id')
  313. raise 'test'
  314. Task = Tasks.by_id(int(task_id))
  315. if action=='close':
  316. Task.closed = True
  317. if action=='open':
  318. Task.closed = False
  319. DBSession.merge(Task)
  320. request.session.flash('Task was successfully closed!')
  321. return HTTPFound(location=request.route_url('list_task'))
  322. ## =-=- Here, We handle HTTP requests - User Logged Part -=-=
  323. @view_config(route_name='exchange', renderer="jm2l:templates/Logistique/Logistique.mako")
  324. def exchange(request):
  325. modtype = request.matchdict.get('modtype', None)
  326. action = request.matchdict.get('action', None)
  327. uid = int(request.matchdict.get('id', -1))
  328. Exch = Exchange.by_id(uid)
  329. if not Exch:
  330. MainTab = {
  331. 'Exchanges':Exchange,
  332. 'Type':modtype[-1:],
  333. 'reload':True,
  334. 'logged_in':request.authenticated_userid
  335. }
  336. return MainTab
  337. if action in ['delete', 'accept', 'refuse', 'deal']:
  338. if action=='delete': # delete exchange
  339. DBSession.delete(Exch)
  340. elif action=='accept': # accept exchange
  341. Exch.exch_done=True
  342. DBSession.merge(Exch)
  343. elif action=='refuse': # refuse exchange
  344. Exch.exch_done=False
  345. if Exch.exch_state=="Ask":
  346. Exch.provider_id = None
  347. elif Exch.exch_state=="Proposal":
  348. Exch.asker_id = None
  349. DBSession.merge(Exch)
  350. elif action=='deal':
  351. # ask to deal the exchange
  352. if Exch.exch_state=="Ask":
  353. Exch.provider_id = request.user.uid
  354. elif Exch.exch_state=="Proposal":
  355. Exch.asker_id = request.user.uid
  356. # Return javascript to parent page
  357. response = render_to_response('jm2l:templates/modals_js.mako',
  358. {'modtype':modtype, 'action':action},
  359. request=request)
  360. response.content_type = 'text/javascript'
  361. return response
  362. else:
  363. MainTab = {
  364. 'Exchanges':Exchange,
  365. 'Type':modtype[-1:],
  366. 'reload':True,
  367. 'logged_in':request.authenticated_userid
  368. }
  369. return MainTab
  370. @view_config(route_name='jm2l', renderer="jm2l:templates/jm2l.mako")
  371. def jm2l_page(request):
  372. if request.user is None:
  373. # Don't answer to users that aren't logged
  374. return HTTPUnauthorized('You have to be logged to hope an answer.')
  375. page = int(request.params.get('page', 1))
  376. UserNum = request.params.get('user')
  377. if UserNum:
  378. profil = User.by_id(int(UserNum))
  379. if not profil:
  380. raise HTTPNotFound()
  381. else:
  382. profil = request.user
  383. # Build Form
  384. profil_form = ProfilForm(request.POST, profil, meta={'csrf_context': request.session})
  385. if request.method == 'POST' and profil_form.validate():
  386. ToDelete = list()
  387. # First, we remove entries no more present
  388. for obj in profil_form.tiersship.object_data:
  389. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  390. profil_form.tiersship.entries )
  391. if not MatchEntry:
  392. ToDelete.append(obj)
  393. # Then, it's time to consider new entries
  394. for entry in profil_form.tiersship.entries:
  395. if entry.object_data is None:
  396. TmpUser = User_Tiers()
  397. entry.object_data = TmpUser
  398. profil.tiersship.append(TmpUser)
  399. profil_form.tiersship.object_data = profil.tiersship
  400. profil_form.populate_obj(profil)
  401. # We should remove it as it's not in original data
  402. for obj in ToDelete:
  403. #profil.tiersship.remove(obj)
  404. DBSession.delete(obj)
  405. profil.last_change = datetime.datetime.utcnow()
  406. profil.slug = slugify(remove_accents('%s %s' % (profil.prenom, profil.nom)).lower().strip())
  407. DBSession.merge(profil)
  408. MainTab = {'participer':'active',
  409. 'Places':Place.get_list(False),
  410. 'DBTiers':Tiers,
  411. 'DBTiersOpt':TiersOpt,
  412. 'Exchanges':Exchange,
  413. 'profil_form':profil_form,
  414. 'uprofil':profil,
  415. 'logged_in':request.authenticated_userid
  416. }
  417. return MainTab
  418. @view_config(route_name='modal', renderer="jm2l:templates/modals.mako")
  419. def Modal(request):
  420. year = int(request.matchdict.get('year', None))
  421. modtype = request.matchdict.get('modtype', None)
  422. uid = int(request.matchdict.get('id', -1))
  423. session = request.session
  424. if modtype=='UserPicture':
  425. form = None
  426. if modtype=='Place':
  427. if uid>0:
  428. place = Place.by_id(uid)
  429. if not place:
  430. raise HTTPNotFound()
  431. form = PlaceUpdateForm(request.POST, place, meta={'csrf_context': request.session})
  432. else:
  433. place = Place()
  434. form = PlaceCreateForm(request.POST, meta={'csrf_context': request.session})
  435. if request.method == 'POST' and form.validate():
  436. form.populate_obj(place)
  437. place.created_by=request.user.uid
  438. if uid>0:
  439. DBSession.merge(place)
  440. else:
  441. DBSession.add(place)
  442. response = render_to_response('jm2l:templates/modals_js.mako',
  443. {'modtype':modtype},
  444. request=request)
  445. response.content_type = 'text/javascript'
  446. return response
  447. if modtype in ['AskC', 'AskH', 'AskM', 'PropC', 'PropH', 'PropM']:
  448. if uid>0:
  449. Exch = Exchange.by_id(uid)
  450. if not Exch:
  451. raise HTTPNotFound()
  452. if modtype in ['AskC','PropC']:
  453. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  454. start_place = Exch.Itin.start_place,
  455. arrival_place = Exch.Itin.arrival_place,
  456. Hour_start = Exch.start_time.strftime("%H:%M"),
  457. Day_start = Exch.start_time.strftime("%w"),
  458. exch_id = uid, meta={'csrf_context': request.session}
  459. )
  460. elif modtype in ['AskM','PropM']:
  461. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  462. description = Exch.description,
  463. exch_categ = Exch.exch_categ,
  464. Hour_start = Exch.start_time.strftime("%H:%M"),
  465. Day_start = Exch.start_time.strftime("%w"),
  466. Hour_end = Exch.end_time.strftime("%H:%M"),
  467. Day_end = Exch.end_time.strftime("%w"),
  468. exch_id = uid, meta={'csrf_context': request.session}
  469. )
  470. elif modtype in ['AskH','PropH']:
  471. form = globals()["Update%sForm" % modtype](request.POST, Exch,
  472. description = Exch.description,
  473. exch_categ = Exch.exch_categ,
  474. Day_start = Exch.start_time.strftime("%w"),
  475. exch_id = uid, meta={'csrf_context': request.session}
  476. )
  477. # Itinerary, first get itinerary
  478. if 0:
  479. form.itin.form.start_place.data = Exch.Itin.start_place
  480. form.itin.form.arrival_place.data = Exch.Itin.arrival_place
  481. form.dateform.form.Hour.data = Exch.start_time.strftime("%H:%M")
  482. form.dateform.form.Day.data = Exch.start_time.strftime("%w")
  483. form.exch_id.data = uid
  484. else:
  485. Exch = Exchange()
  486. form = globals()["%sForm" % modtype](request.POST, meta={'csrf_context': request.session})
  487. if modtype in ['AskC', 'PropC']:
  488. # Put some place on form
  489. Places = DBSession.query(Place.place_id, Place.display_name)\
  490. .order_by('name').all()
  491. form.start_place.choices = Places
  492. form.arrival_place.choices = Places
  493. if modtype in ['PropH']:
  494. form.exch_categ.choices = DBSession.query( Exchange_Cat.cat_id, Exchange_Cat.exch_subtype)\
  495. .filter( Exchange_Cat.exch_type=='H' ).all()
  496. form.place_id.choices = DBSession.query( Place.place_id, Place.display_name)\
  497. .filter( Place.created_by==request.user.uid ).all()
  498. if modtype in ['AskM', 'PropM']:
  499. form.exch_categ.choices = DBSession.query( Exchange_Cat.cat_id, Exchange_Cat.exch_subtype)\
  500. .filter( Exchange_Cat.exch_type=='M' ).all()
  501. if request.method == 'POST' and form.validate():
  502. # Form has been validated, it's time to create our Exchange
  503. Exch.for_year = year
  504. Exch.exch_state = {'Ask':'Ask', 'Prop':'Proposal'}[modtype[:-1]]
  505. Exch.exch_type = modtype[-1:]
  506. if modtype in ['AskC', 'PropC']:
  507. # Itinerary, first Let's see if itinerary exist
  508. Itinerary = DBSession.query(Itineraire)\
  509. .filter(Itineraire.start_place==form.start_place.data) \
  510. .filter(Itineraire.arrival_place==form.arrival_place.data) \
  511. .filter(Itineraire.tr_voiture==True) \
  512. .first()
  513. if not Itinerary: # Not exist yet !
  514. Itinerary = Itineraire(start_place=form.start_place.data, \
  515. arrival_place=form.arrival_place.data, \
  516. tr_voiture=True, \
  517. created_by=1
  518. )
  519. DBSession.add(Itinerary)
  520. DBSession.flush()
  521. Exch.itin_id = Itinerary.itin_id
  522. # Start Time
  523. StartEvent = DBSession.query(JM2L_Year.start_time).filter(JM2L_Year.year_uid==year).first()
  524. Week = StartEvent[0].strftime("%W")
  525. # populate
  526. form.populate_obj(Exch)
  527. if modtype in ['AskC', 'PropC']:
  528. Exch.itin_id = Itinerary.itin_id
  529. if form._fields.has_key("Hour_start"):
  530. TargetTime = datetime.datetime.strptime('%d %d %d %s' % (year, int(Week), \
  531. int(form.Day_start.data), form.Hour_start.data), "%Y %W %w %H:%M")
  532. Exch.start_time = TargetTime
  533. elif form._fields.has_key("Day_start"):
  534. TargetTime = datetime.datetime.strptime('%d %d %d' % (year, int(Week), \
  535. int(form.Day_start.data)), "%Y %W %w")
  536. Exch.start_time = TargetTime
  537. if form._fields.has_key("Hour_end"):
  538. TargetTime = datetime.datetime.strptime('%d %d %d %s' % (year, int(Week), \
  539. int(form.Day_end.data), form.Hour_end.data), "%Y %W %w %H:%M")
  540. Exch.end_time = TargetTime
  541. elif form._fields.has_key("Day_end"):
  542. TargetTime = datetime.datetime.strptime('%d %d %d' % (year, int(Week), \
  543. int(form.Day_end.data)), "%Y %W %w")
  544. Exch.end_time = TargetTime
  545. Exch.last_change = datetime.datetime.utcnow()
  546. if Exch.exch_state=='Ask':
  547. Exch.asker_id = request.user.uid
  548. elif Exch.exch_state=='Proposal':
  549. Exch.provider_id = request.user.uid
  550. #print vars(form.itin.form)
  551. if uid>0:
  552. DBSession.merge(Exch)
  553. else:
  554. DBSession.add(Exch)
  555. response = render_to_response('jm2l:templates/modals_js.mako',
  556. {'modtype':modtype},
  557. request=request)
  558. response.content_type = 'text/javascript'
  559. return response
  560. # Fallback to HTML Display with errors
  561. return {'modtype':modtype, 'form':form, 'update':uid>0,
  562. 'logged_in':request.authenticated_userid }
  563. if modtype in ['ShowC', 'ShowH', 'ShowM']:
  564. if uid>0:
  565. Exch = Exchange.by_id(uid)
  566. if not Exch:
  567. raise HTTPNotFound()
  568. else:
  569. raise HTTPNotFound()
  570. # Show Details around the Current Exchange
  571. return {'modtype':modtype, 'Exch':Exch, 'logged_in':request.authenticated_userid }
  572. MainTab = {'modtype':modtype, 'form':form, 'update':uid>0, 'uid':uid,
  573. 'DisplayYear':year, 'session':session,
  574. 'logged_in':request.authenticated_userid }
  575. return MainTab
  576. @view_config(route_name='participer', renderer="jm2l:templates/Participer.mako")
  577. def participer(request):
  578. session = request.session
  579. session['year'] = 2015
  580. TmpUsr = User()
  581. form = UserRegisterForm(request.POST, TmpUsr, meta={'csrf_context': request.session})
  582. MyLink=None
  583. if request.method == 'POST' and form.validate():
  584. form.populate_obj(TmpUsr)
  585. TmpUsr.nom = TmpUsr.nom.capitalize()
  586. TmpUsr.prenom = TmpUsr.prenom.capitalize()
  587. TmpUsr.slug = slugify(remove_accents('%s %s' % (form.prenom, form.nom)).lower().strip())
  588. TmpUsr.password = TmpUsr.my_hash
  589. if len(TmpUsr.slug):
  590. CheckExist = DBSession.query(User)\
  591. .filter(User.slug==TmpUsr.slug)\
  592. .first()
  593. else:
  594. CheckExist=None
  595. if CheckExist:
  596. MyLink = CheckExist.my_hash
  597. else:
  598. DBSession.add(TmpUsr)
  599. DBSession.flush()
  600. MyLink = TmpUsr.my_hash
  601. MainTab = {'programme':'','presse':'', 'plan':'',
  602. 'participer':'active', 'form':form, "link": MyLink,
  603. 'logged_in':request.authenticated_userid }
  604. return MainTab
  605. @view_config(route_name='year')
  606. def change_year(request):
  607. year = int(request.matchdict.get('year', -1))
  608. session = request.session
  609. if year>-1:
  610. session['year'] = year
  611. return HTTPFound(location='/%s/le-programme' % year)
  612. return HTTPFound(location=request.route_url('home'))
  613. @view_config(route_name='event', renderer="jm2l:templates/view_event.mako")
  614. def show_event(request):
  615. year = int(request.matchdict.get('year', -1))
  616. event_id = request.matchdict.get('event_id')
  617. if event_id.isdigit():
  618. TheEvent = Event.by_id(event_id)
  619. if TheEvent is None:
  620. raise HTTPNotFound()
  621. else:
  622. TheEvent = Event.by_slug(event_id, year)
  623. if TheEvent is None:
  624. raise HTTPNotFound()
  625. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  626. 'event':TheEvent, 'logged_in':request.authenticated_userid }
  627. return MainTab
  628. @view_config(route_name='link_event')
  629. def link_event(request):
  630. """ Create user if not exist, add it to current event """
  631. year = int(request.matchdict.get('year', -1))
  632. form = AddIntervenant(request.POST, meta={'csrf_context': request.session})
  633. intervention = request.matchdict.get('intervention', None)
  634. TargetEvent = Event.by_id(form.event_uid.data)
  635. Exist = DBSession.query(User)\
  636. .filter(User.nom==form.nom.data)\
  637. .filter(User.prenom==form.prenom.data)\
  638. .first()
  639. if Exist:
  640. TargetUser = Exist
  641. else:
  642. # Add it to user base
  643. TargetUser = User(nom=form.nom.data,
  644. prenom=form.prenom.data, password=form.nom.data)
  645. DBSession.add(TargetUser)
  646. DBSession.flush()
  647. uev = User_Event(year_uid=year, role="Animateur", user_uid=TargetUser.uid)
  648. TargetEvent.interventions.append( uev )
  649. return HTTPFound(location=request.route_url('edit_event', sep='/',
  650. year=str(year), intervention=intervention, uid=str(TargetEvent.uid)))
  651. @view_config(route_name='edit_event', renderer="jm2l:templates/edit_event.mako")
  652. def edit_event(request):
  653. year = int(request.matchdict.get('year', -1))
  654. event_id = request.matchdict.get('event_id')
  655. intervention = request.matchdict.get('intervention', None)
  656. IntervLabel = intervention.replace('_',' ').lower()
  657. if intervention=='Conference':
  658. IntervLabel = u'conférence'
  659. # Check intervention
  660. if not intervention in ['Stand', 'Table ronde', 'Atelier', 'Conference']:
  661. raise HTTPNotFound(u"Ce type d'évenement n'est pas reconnu")
  662. TheYear = DBSession.query(JM2L_Year)\
  663. .filter(JM2L_Year.year_uid==year)\
  664. .all()
  665. # Check year avaibility
  666. if not TheYear:
  667. raise HTTPNotFound(u"Cette année n'est pas pris en charge")
  668. # Generate Timeslots for current year
  669. TimeSlots = list(enumerate( [ x.strftime('%a %d %b %H:%M') for x in
  670. TheYear[0].AvailableTimeSlots ] ))
  671. if event_id:
  672. # We try to update an existing record
  673. if event_id.isdigit():
  674. TheEvent = Event.by_id(event_id)
  675. if TheEvent is None:
  676. raise HTTPNotFound(u"Cette réference n'existe pas")
  677. else:
  678. TheEvent = Event.by_slug(event_id, year)
  679. if TheEvent is None:
  680. raise HTTPNotFound(u"Cette réference n'existe pas")
  681. if not (request.user.uid==1 or request.user in TheEvent.intervenants):
  682. return HTTPForbidden(u"Vous n'êtes pas identifié comme étant un participant à cette intervention.")
  683. # Compute some field value from selected event
  684. if TheEvent.start_time in TheYear[0].AvailableTimeSlots:
  685. start_sel = TheYear[0].AvailableTimeSlots.index(TheEvent.start_time)
  686. else:
  687. start_sel = len(TimeSlots)
  688. TimeSlots.append( (len(TimeSlots), TheEvent.start_time.strftime('%a %d %b %H:%M')))
  689. duration = (TheEvent.end_time - TheEvent.start_time).total_seconds()/60
  690. end = TheEvent.start_time + datetime.timedelta(minutes=duration)
  691. # prepare the form with update
  692. form = ConfUpdateForm(request.POST, TheEvent, start_sel=start_sel, duration=duration, end_time=end,
  693. meta={'csrf_context': request.session} )
  694. # Customize labels
  695. form.name.label.text += IntervLabel
  696. form.description.label.text += IntervLabel
  697. # Each event can get severals members
  698. formAdd = AddIntervenant(event_uid=TheEvent.uid)
  699. else:
  700. TheEvent = Event()
  701. # prepare the form for creation
  702. form = ConfCreateForm(request.POST,
  703. event_type=intervention,
  704. for_year=str(year), meta={'csrf_context': request.session}
  705. )
  706. # Customize labels
  707. form.name.label.text += IntervLabel
  708. form.description.label.text += IntervLabel
  709. duration=60
  710. # No intervenant
  711. formAdd = None
  712. if intervention=="Conference":
  713. form.duration.choices =[
  714. (15,u'Lighting talk ( 5 min)'),
  715. (30,u'Conférence (20 min)'),
  716. (60,u'Conférence (50 min)'),
  717. (90,u'Conférence (75 min)'),
  718. ]
  719. if not duration in [15, 30, 60, 90]:
  720. form.duration.choices.append( (duration,u'Conférence (%d min)' % duration) )
  721. if not form._fields.has_key("uid"):
  722. form.duration.data=60
  723. elif intervention=="Stand":
  724. form.duration.choices =[
  725. (8*60, u'Toute la journée'),
  726. (4*60, u'une demi-journée')
  727. ]
  728. elif intervention=="Atelier":
  729. form.duration.choices = map( lambda d:(d, u'Atelier (%dh%.2d)' % (d/60, d%60) ), \
  730. [60, 90, 120, 150, 180, 210, 240] )
  731. if not duration in map(lambda (d,y): d, form.duration.choices):
  732. form.duration.choices.append( (duration,u'Atelier (%dh%.2d)' % (duration/60, duration%60) ) )
  733. elif intervention=="Table_Ronde":
  734. form.duration.choices = map( lambda d:(d, u'Table ronde (%dh%.2d)' % (d/60, d%60) ), \
  735. [60, 90, 120, 150] )
  736. if not duration in map(lambda (d,y): d, form.duration.choices):
  737. form.duration.choices.append( (duration,u'Table ronde (%dh%.2d)' % (duration/60, duration%60) ) )
  738. else:
  739. return HTTPForbidden(u"Pas encore disponible.")
  740. SalleDispo = DBSession.query(Salles)\
  741. .filter(Salles.year_uid==year)\
  742. .order_by('name')
  743. form.salle_uid.choices = [(s.salle_id, s.name) for s in SalleDispo]
  744. form.start_sel.choices = TimeSlots
  745. if request.method == 'POST' and form.validate():
  746. form.populate_obj(TheEvent)
  747. TheEvent.start_time = TheYear[0].AvailableTimeSlots[form.start_sel.data]
  748. TheEvent.end_time = TheEvent.start_time + datetime.timedelta(minutes=form.duration.data)
  749. # Ok, time to put in database
  750. if not form._fields.has_key("uid"):
  751. TheEvent.slug = slugify(TheEvent.name)
  752. DBSession.add(TheEvent)
  753. # Append creator by default
  754. if request.user.uid!=1:
  755. uev = User_Event(year_uid=TheYear.year_uid, role="Animateur")
  756. uev.user_uid = request.user.uid
  757. TheEvent.interventions.append( uev )
  758. DBSession.flush()
  759. return HTTPFound(location=request.route_url('edit_event', sep='/',
  760. year=str(year), intervention=intervention, event_id=str(TheEvent.slug)))
  761. else:
  762. DBSession.merge(TheEvent)
  763. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  764. 'event':TheEvent, 'form':form, 'formAdd':formAdd,
  765. 'logged_in':request.authenticated_userid }
  766. return MainTab
  767. @view_config(route_name='entities', renderer="jm2l:templates/list_tiers.mako")
  768. def list_tiers(request):
  769. Entities = dict()
  770. EntityType = DBSession.query(TiersOpt.entity_type)\
  771. .group_by(TiersOpt.entity_type).all()
  772. for EType in EntityType:
  773. Entities[EType.entity_type] = DBSession.query(Tiers).join(TiersOpt)\
  774. .filter(TiersOpt.entity_type==EType.entity_type)\
  775. .order_by(TiersOpt.entity_subtype, Tiers.name)
  776. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  777. 'entities':Entities, 'logged_in':request.authenticated_userid }
  778. return MainTab
  779. @view_config(route_name='show_entity', renderer="jm2l:templates/view_tiers.mako")
  780. def show_tiers(request):
  781. tiers_type = request.matchdict.get('tiers_type')
  782. entity_id = request.matchdict.get('entity_id')
  783. if entity_id.isdigit():
  784. TheTiers = Tiers.by_id(entity_id)
  785. if TheTiers is None:
  786. raise HTTPNotFound()
  787. else:
  788. TheTiers = Tiers.by_slug(entity_id)
  789. if TheTiers is None:
  790. raise HTTPNotFound()
  791. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  792. 'entity':TheTiers, 'logged_in':request.authenticated_userid }
  793. return MainTab
  794. @view_config(route_name='add_entity', renderer="jm2l:templates/edit_tiers.mako")
  795. @view_config(route_name='edit_entity', renderer="jm2l:templates/edit_tiers.mako",
  796. permission='edit')
  797. def edit_tiers(request):
  798. entity_id = request.matchdict.get('entity_id', None)
  799. TargetList = list()
  800. entity_types = DBSession.query(TiersOpt.entity_type).group_by(TiersOpt.entity_type).all()
  801. for entity_type in entity_types:
  802. entity_subtypes = DBSession.query(TiersOpt)\
  803. .filter(TiersOpt.entity_type==entity_type.entity_type)\
  804. .group_by(TiersOpt.entity_subtype).all()
  805. ListType = [(i.uid, i.entity_subtype) for i in entity_subtypes]
  806. TargetList.append( (entity_type.entity_type, ListType) )
  807. if entity_id:
  808. if entity_id.isdigit():
  809. TheTiers = Tiers.by_id(entity_id)
  810. if TheTiers is None:
  811. raise HTTPNotFound()
  812. else:
  813. TheTiers = Tiers.by_slug(entity_id)
  814. if TheTiers is None:
  815. raise HTTPNotFound()
  816. form = UpdateTiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  817. UserOptions = DBSession.query(TiersOpt)\
  818. .filter(TiersOpt.entity_type==TheTiers.tiers_type)\
  819. .all()
  820. form.tiers_type.choices = TargetList
  821. else:
  822. TheTiers = Tiers()
  823. # prepare the form for creation
  824. form = TiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  825. form.tiers_type.choices = TargetList
  826. UserOptions = list()
  827. #test_form = TiersForm(request.POST, TheTiers, meta={'csrf_context': request.session})
  828. if request.method == 'POST' and form.validate():
  829. ToDelete = list()
  830. # First, we remove entries no more present
  831. for obj in form.membership.object_data:
  832. MatchEntry = filter( lambda x: x.object_data and x.object_data._sa_instance_state == obj._sa_instance_state,
  833. form.membership.entries )
  834. if not MatchEntry:
  835. ToDelete.append(obj)
  836. # We should remove it as it's not in original data
  837. for obj in ToDelete:
  838. TheTiers.membership.remove(obj)
  839. DBSession.delete(obj)
  840. # Then, it's time to consider new entries
  841. for entry in form.membership.entries:
  842. if entry.object_data is None:
  843. TmpUser = User_Tiers()
  844. entry.object_data = TmpUser
  845. TheTiers.membership.append(TmpUser)
  846. form.membership.object_data = TheTiers.membership
  847. form.populate_obj(TheTiers)
  848. # Handle Remove of accents
  849. TheTiers.slug = slugify(form.name.data)
  850. if not form._fields.has_key('uid'):
  851. TheTiers.creator_id = request.user.uid
  852. DBSession.add(TheTiers)
  853. DBSession.flush()
  854. return HTTPFound(location=request.route_url('edit_entity', sep='/',
  855. entity_id=str(TheTiers.slug), tiers_type=TheTiers.get_entity_type.entity_type))
  856. DBSession.merge(TheTiers)
  857. return HTTPFound(location=request.route_url('entities'))
  858. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  859. 'form':form, 'DBUser':User, 'UserOptions':UserOptions,
  860. 'logged_in':request.authenticated_userid }
  861. return MainTab
  862. @view_config(route_name='edit_entity_cat', renderer="jm2l:templates/edit_tiers_categ.mako")
  863. def edit_tiers_category(request):
  864. DicResult = dict()
  865. ListChanges = list()
  866. if request.method == 'POST':
  867. # Reformat data
  868. RegExist = re.compile('collection\[(?P<slug>[\w-]+)\]\[(?P<num>\d+)\]\[(?P<id>\d+)\]')
  869. RegTitle = re.compile('collection\[(?P<slug>[\w-]+)\]\[title]')
  870. RegNew = re.compile('collection\[(?P<slug>[\w-]+)\]\[(?P<num>\d+)\]\[id\]')
  871. for key, value in request.POST.iteritems():
  872. regN= RegNew.match(key)
  873. regT= RegTitle.match(key)
  874. reg = RegExist.match(key)
  875. if reg:
  876. if not DicResult.has_key(reg.group('slug')):
  877. DicResult[reg.group('slug')] = dict()
  878. if DicResult[reg.group('slug')].has_key('items'):
  879. DicResult[reg.group('slug')]['items'].append( ( int(reg.group('id')), value ) )
  880. else:
  881. DicResult[reg.group('slug')]['items'] = [ ( int(reg.group('id')), value ) ]
  882. elif regN:
  883. if not DicResult.has_key(regN.group('slug')):
  884. DicResult[regN.group('slug')] = dict()
  885. if DicResult[regN.group('slug')].has_key('items'):
  886. DicResult[regN.group('slug')]['items'].append( ( 'id', value ) )
  887. else:
  888. DicResult[regN.group('slug')]['items'] = [ ( 'id', value ) ]
  889. ListChanges.append(('add', 0, DicResult[regN.group('slug')]['title'], value))
  890. elif regT:
  891. if not DicResult.has_key(regT.group('slug')):
  892. DicResult[regT.group('slug')] = dict()
  893. DicResult[regT.group('slug')]['title'] = value
  894. else:
  895. raise
  896. for opt in DBSession.query(TiersOpt).all():
  897. if DicResult.has_key(opt.slug_entity_type):
  898. found = filter( lambda (x,y): opt.uid==x,
  899. DicResult[opt.slug_entity_type].get('items', []))
  900. if not found:
  901. ListChanges.append(('remove', opt.uid, opt.entity_type, opt.entity_subtype))
  902. else:
  903. for tst in found:
  904. # Check changes on Cat Name
  905. if DicResult[opt.slug_entity_type]['title']!=opt.entity_type or \
  906. tst[1]!=opt.entity_subtype:
  907. ListChanges.append(('changed', opt.uid,
  908. DicResult[opt.slug_entity_type]['title'],
  909. tst[1]))
  910. else:
  911. ListChanges.append(('remove', opt.uid, opt.entity_type, opt.entity_subtype))
  912. # Do The change
  913. for action, uid, entity, subentity in ListChanges:
  914. if action=="changed":
  915. opt = TiersOpt.by_id(uid)
  916. opt.entity_type = entity
  917. opt.entity_subtype = subentity
  918. elif action=="remove":
  919. opt = TiersOpt.by_id(uid)
  920. DBSession.delete(opt)
  921. elif action=="add":
  922. opt = TiersOpt()
  923. opt.entity_type = entity
  924. opt.entity_subtype = subentity
  925. DBSession.add(opt)
  926. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  927. 'logged_in':request.authenticated_userid, 'TiersOpt':TiersOpt }
  928. return MainTab
  929. @view_config(route_name='show_user', renderer="jm2l:templates/view_user.mako")
  930. def show_user(request):
  931. user_slug = request.matchdict.get('user_slug', None)
  932. # Query database
  933. DispUser = User.by_slug(user_slug)
  934. MainTab = {'programme':'','presse':'', 'plan':'', 'participer':'',
  935. 'DispUser':DispUser, 'logged_in':request.authenticated_userid }
  936. return MainTab
  937. #@view_config(route_name='link_user_entity')
  938. def link_user_entity(request):
  939. uid = int(request.matchdict.get('uid', -1))
  940. year = int(request.matchdict.get('year', -1))
  941. user_id = int(request.matchdict.get('uid', -1))
  942. TheTiers = Tiers.by_id(uid)
  943. if TheTiers is None:
  944. raise HTTPNotFound()
  945. return HTTPFound(location=request.route_url('edit_entity', uid=uid) )
  946. #@view_config(route_name='link_role_entity')
  947. def link_role_entity(request):
  948. uid = int(request.matchdict.get('uid', -1))
  949. year = int(request.matchdict.get('year', -1))
  950. role_id = int(request.matchdict.get('role_id', -1))
  951. TheTiers = Tiers.by_id(uid)
  952. if TheTiers is None:
  953. raise HTTPNotFound()
  954. return HTTPFound(location=request.route_url('edit_entity', uid=uid) )
  955. @notfound_view_config()
  956. def notfound(reason, request):
  957. request.response.status = 404
  958. return render_to_response('jm2l:templates/Errors/404.mak', { "reason":reason },
  959. request=request)
  960. @forbidden_view_config()
  961. def forbidden(reason, request):
  962. return Response('forbidden')
  963. request.response.status = 404
  964. return render_to_response('jm2l:templates/Errors/404.mak', { "reason":reason },
  965. request=request)