Le repo des sources pour le site web des JM2L
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

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