source: main/waeup.kofa/trunk/src/waeup/kofa/hostels/browser.py @ 13505

Last change on this file since 13505 was 13494, checked in by Henrik Bettermann, 9 years ago

Reduce cookie length.

  • Property svn:keywords set to Id
File size: 14.9 KB
Line 
1## $Id: browser.py 13494 2015-11-24 15:13:31Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18"""UI components for hostels and related components.
19"""
20import grok
21import sys
22from zope.i18n import translate
23from zope.component import getUtility
24from zope.catalog.interfaces import ICatalog
25from waeup.kofa.browser.layout import (
26    KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage,
27    NullValidator, UtilityView)
28from waeup.kofa.browser.breadcrumbs import Breadcrumb
29from waeup.kofa.browser.layout import default_primary_nav_template
30from waeup.kofa.browser.pages import delSubobjects
31from waeup.kofa.browser.viewlets import (
32    ManageActionButton, PrimaryNavTab)
33from waeup.kofa.browser.layout import jsaction, action
34from waeup.kofa.interfaces import IKofaObject, IKofaUtils, DOCLINK
35from waeup.kofa.interfaces import MessageFactory as _
36from waeup.kofa.hostels.vocabularies import NOT_OCCUPIED
37from waeup.kofa.hostels.hostel import Hostel
38from waeup.kofa.hostels.interfaces import (
39    IHostelsContainer, IHostel, IBed)
40from waeup.kofa.widgets.datewidget import FriendlyDatetimeDisplayWidget
41
42# Save function used for save methods in manager pages
43def msave(view, **data):
44    changed_fields = view.applyData(view.context, **data)
45    # Turn list of lists into single list
46    if changed_fields:
47        changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
48    fields_string = ' + '.join(changed_fields)
49    view.context._p_changed = True
50    view.flash(_('Form has been saved.'))
51    if fields_string:
52        view.context.writeLogMessage(view, 'saved: %s' % fields_string)
53    return
54
55class HostelsTab(PrimaryNavTab):
56    """Hostels tab in primary navigation.
57    """
58
59    grok.context(IKofaObject)
60    grok.order(5)
61    grok.require('waeup.viewHostels')
62    grok.name('hostelstab')
63    template = default_primary_nav_template
64    pnav = 5
65    tab_title = _(u'Hostels')
66
67    @property
68    def link_target(self):
69        return self.view.application_url('hostels')
70
71class HostelsBreadcrumb(Breadcrumb):
72    """A breadcrumb for the hostels container.
73    """
74    grok.context(IHostelsContainer)
75    title = _(u'Hostels')
76
77class HostelBreadcrumb(Breadcrumb):
78    """A breadcrumb for the hostel container.
79    """
80    grok.context(IHostel)
81
82    def title(self):
83        return self.context.hostel_name
84
85class BedBreadcrumb(Breadcrumb):
86    """A breadcrumb for the hostel container.
87    """
88    grok.context(IBed)
89
90    def title(self):
91        co = self.context.coordinates
92        return _('Block ${a}, Room ${b}, Bed ${c}',
93            mapping = {'a':co[1], 'b':co[2], 'c':co[3]})
94
95class HostelsContainerPage(KofaDisplayFormPage):
96    """The standard view for hostels containers.
97    """
98    grok.context(IHostelsContainer)
99    grok.name('index')
100    grok.require('waeup.viewHostels')
101    grok.template('containerpage')
102    label = _('Accommodation Section')
103    pnav = 5
104    form_fields = grok.AutoFields(IHostelsContainer)
105    form_fields[
106        'startdate'].custom_widget = FriendlyDatetimeDisplayWidget('le')
107    form_fields[
108        'enddate'].custom_widget = FriendlyDatetimeDisplayWidget('le')
109
110class HostelsContainerManageActionButton(ManageActionButton):
111    grok.order(1)
112    grok.context(IHostelsContainer)
113    grok.view(HostelsContainerPage)
114    grok.require('waeup.manageHostels')
115    text = _('Manage accommodation section')
116
117class HostelsStatisticsActionButton(ManageActionButton):
118    grok.order(2)
119    grok.context(IHostelsContainer)
120    grok.view(HostelsContainerPage)
121    grok.require('waeup.manageHostels')
122    icon = 'actionicon_statistics.png'
123    text = _('Bed statistics')
124    target = 'statistics'
125
126class HostelsContainerManagePage(KofaEditFormPage):
127    """The manage page for hostel containers.
128    """
129    grok.context(IHostelsContainer)
130    grok.name('manage')
131    grok.require('waeup.manageHostels')
132    grok.template('containermanagepage')
133    pnav = 5
134    label = _('Manage accommodation section')
135    form_fields = grok.AutoFields(IHostelsContainer)
136    taboneactions = [_('Save')]
137    tabtwoactions = [_('Add hostel'),
138        _('Clear all hostels'),
139        _('Remove selected')]
140    doclink = DOCLINK + '/hostels.html#accommodation-section'
141
142    # It's quite dangerous to remove entire hostels with its content (beds).
143    # Thus, this remove method should be combined with an archiving function.
144    @jsaction(_('Remove selected'))
145    def delHostels(self, **data):
146        form = self.request.form
147        if 'val_id' in form:
148            deleted = []
149            child_id = form['val_id']
150            if not isinstance(child_id, list):
151                child_id = [child_id]
152            for id in child_id:
153                deleted.append(id)
154            self.context.writeLogMessage(
155                self, 'deleted: % s' % ', '.join(deleted))
156        delSubobjects(self, redirect='@@manage', tab='2')
157        return
158
159    @action(_('Add hostel'), validator=NullValidator)
160    def addSubunit(self, **data):
161        self.redirect(self.url(self.context, 'addhostel'))
162        return
163
164    @jsaction(_('Clear all hostels'), style='danger')
165    def clearHostels(self, **data):
166        self.context.clearAllHostels()
167        self.flash(_('All hostels cleared.'))
168        self.context.writeLogMessage(self, 'all hostels cleared')
169        self.redirect(self.url(self.context, '@@manage')+'#tab2')
170        return
171
172    @action(_('Save'), style='primary')
173    def save(self, **data):
174        if data['accommodation_session'] != self.context.accommodation_session:
175            catalog = getUtility(ICatalog, name='beds_catalog')
176            beds = catalog.searchResults(bed_type=(None,None))
177            if len(beds):
178                self.flash(_('You can\'t change the booking session '
179                             'before clearing all hostels.'),
180                           type='warning')
181                return
182        self.applyData(self.context, **data)
183        self.flash(_('Settings have been saved.'))
184        return
185
186class ReleaseExpiredAllocationsPage(UtilityView, grok.View):
187    """Release all expired allocated beds.
188    """
189    grok.context(IHostelsContainer)
190    grok.name('releaseexpired')
191    grok.require('waeup.manageHostels')
192
193    def update(self, n=7):
194        released = self.context.releaseExpiredAllocations(n)
195        if len(released):
196            message = ', '.join(released)
197            self.context.writeLogMessage(self, 'released: %s' % message)
198            flash_msg = _('Successfully released beds: ${a}', mapping = {'a':message})
199        else:
200            flash_msg = _('No bed released.')
201        self.flash(flash_msg, type='success')
202        self.redirect(self.url(self.context))
203        return
204
205    def render(self):
206        return
207
208class HostelsStatisticsPage(KofaDisplayFormPage):
209    """Some statistics about beds in hostels.
210    """
211    grok.context(IHostelsContainer)
212    grok.name('statistics')
213    grok.require('waeup.manageHostels')
214    grok.template('containerstatistics')
215    label = _('Bed Statistics')
216
217class HostelAddFormPage(KofaAddFormPage):
218    """Add-form to add a hostel.
219    """
220    grok.context(IHostelsContainer)
221    grok.require('waeup.manageHostels')
222    grok.name('addhostel')
223    #grok.template('hosteladdpage')
224    form_fields = grok.AutoFields(IHostel).omit('beds_reserved', 'hostel_id')
225    label = _('Add hostel')
226    pnav = 5
227    doclink = DOCLINK + '/hostels.html#accommodation-section'
228
229    @action(_('Create hostel'))
230    def addHostel(self, **data):
231        hostel = Hostel()
232        self.applyData(hostel, **data)
233        hostel.hostel_id = data['hostel_name'].lower().replace(
234            ' ','-').replace('_','-').replace('.','')
235        try:
236            self.context.addHostel(hostel)
237        except KeyError:
238            self.flash(_('The hostel already exists.'), type='warning')
239            return
240        self.flash(_('Hostel created.'))
241        self.context.writeLogMessage(self, 'added: % s' % data['hostel_name'])
242        self.redirect(self.url(self.context[hostel.hostel_id], 'index'))
243        return
244
245class HostelDisplayFormPage(KofaDisplayFormPage):
246    """ Page to display hostel data
247    """
248    grok.context(IHostel)
249    grok.name('index')
250    grok.require('waeup.viewHostels')
251    grok.template('hostelpage')
252    form_fields = grok.AutoFields(IHostel).omit('beds_reserved')
253    pnav = 5
254
255    @property
256    def label(self):
257        return self.context.hostel_name
258
259class HostelManageActionButton(ManageActionButton):
260    grok.order(1)
261    grok.context(IHostel)
262    grok.view(HostelDisplayFormPage)
263    grok.require('waeup.manageHostels')
264    text = _('Manage')
265    target = 'manage'
266
267class HostelManageFormPage(KofaEditFormPage):
268    """ View to edit hostel data
269    """
270    grok.context(IHostel)
271    grok.name('manage')
272    grok.require('waeup.manageHostels')
273    form_fields = grok.AutoFields(IHostel).omit('hostel_id', 'beds_reserved')
274    grok.template('hostelmanagepage')
275    label = _('Manage hostel')
276    pnav = 5
277    taboneactions = [_('Save')]
278    tabtwoactions = [_('Update all beds'),
279        _('Switch reservation of selected beds'),
280        _('Release selected beds'),
281        _('Clear hostel')]
282    not_occupied = NOT_OCCUPIED
283    doclink = DOCLINK + '/hostels.html#browser-pages'
284
285    @property
286    def students_url(self):
287        return self.url(grok.getSite(),'students')
288
289    @action(_('Save'), style='primary')
290    def save(self, **data):
291        msave(self, **data)
292        return
293
294    @action(_('Update all beds'), style='primary',
295            warning=_('Attention: The updater removes all reservation flags of existing beds.'
296                        ' You really want to update?'))
297    def updateBeds(self, **data):
298        removed, added, modified, modified_beds = self.context.updateBeds()
299        message = '%d empty beds removed, %d beds added, %d occupied beds modified (%s)' % (
300            removed, added, modified, modified_beds)
301        if modified > 50:
302            flash_message = _(
303                '${a} empty beds removed, ${b} beds added, '
304                + '${c} occupied beds modified',
305                mapping = {'a':removed, 'b':added, 'c':modified})
306        else:
307            flash_message = _(
308                '${a} empty beds removed, ${b} beds added, '
309                + '${c} occupied beds modified (${d})',
310                mapping = {'a':removed, 'b':added, 'c':modified, 'd':modified_beds})
311        self.flash(flash_message)
312        self.context.writeLogMessage(self, message)
313        self.redirect(self.url(self.context, '@@manage')+'#tab2')
314        return
315
316    @action(_('Switch reservation of selected beds'))
317    def switchReservations(self, **data):
318        form = self.request.form
319        if 'val_id' in form:
320            child_id = form['val_id']
321        else:
322            self.flash(_('No item selected.'), type='warning')
323            self.redirect(self.url(self.context, '@@manage')+'#tab2')
324            return
325        if not isinstance(child_id, list):
326            child_id = [child_id]
327        switched = [] # for log file
328        switched_translated = [] # for flash message
329        # Here we know that the cookie has been set
330        preferred_language = self.request.cookies.get('kofa.language')
331        for bed_id in child_id:
332            message = self.context[bed_id].switchReservation()
333            switched.append('%s (%s)' % (bed_id,message))
334            m_translated = translate(message, 'waeup.kofa',
335                target_language=preferred_language)
336            switched_translated.append('%s (%s)' % (bed_id,m_translated))
337        if len(switched):
338            message = ', '.join(switched)
339            m_translated = ', '.join(switched_translated)
340            if len(switched) > 50:
341                self.flash(_('Successfully switched ${a} beds.',
342                    mapping = {'a':len(switched)}))
343            else:
344                self.flash(_('Successfully switched beds: ${a}',
345                    mapping = {'a':m_translated}))
346            self.context.writeLogMessage(self, 'switched: %s' % message)
347            self.redirect(self.url(self.context, '@@manage')+'#tab2')
348        return
349
350    @action(_('Release selected beds'))
351    def releaseBeds(self, **data):
352        form = self.request.form
353        if 'val_id' in form:
354            child_id = form['val_id']
355        else:
356            self.flash(_('No item selected.'), type='warning')
357            self.redirect(self.url(self.context, '@@manage')+'#tab2')
358            return
359        if not isinstance(child_id, list):
360            child_id = [child_id]
361        released = []
362        for bed_id in child_id:
363            message = self.context[bed_id].releaseBed()
364            if message:
365                released.append('%s (%s)' % (bed_id,message))
366        if len(released):
367            message = ', '.join(released)
368            self.flash(_('Successfully released beds: ${a}',
369                mapping = {'a':message}))
370            self.context.writeLogMessage(self, 'released: %s' % message)
371            self.redirect(self.url(self.context, '@@manage')+'#tab2')
372        else:
373            self.flash(_('No allocated bed selected.'), type='warning')
374            self.redirect(self.url(self.context, '@@manage')+'#tab2')
375        return
376
377    @jsaction(_('Clear hostel'), style='danger')
378    def clearHostel(self, **data):
379        self.context.clearHostel()
380        self.flash(_('Hostel cleared.'))
381        self.context.writeLogMessage(self, 'cleared')
382        self.redirect(self.url(self.context, '@@manage')+'#tab2')
383        return
384
385class BedManageFormPage(KofaEditFormPage):
386    """ View to edit bed data
387    """
388    grok.context(IBed)
389    grok.name('index')
390    grok.require('waeup.manageHostels')
391    form_fields = grok.AutoFields(IBed).omit(
392        'bed_id', 'bed_number', 'bed_type')
393    label = _('Allocate student')
394    pnav = 5
395    doclink = DOCLINK + '/hostels.html#manage-bed'
396
397    @action(_('Save'))
398    def save(self, **data):
399        if data['owner'] == NOT_OCCUPIED:
400            self.flash(_('No valid student id.'), type='warning')
401            self.redirect(self.url(self.context))
402            return
403        msave(self, **data)
404        self.redirect(self.url(self.context.__parent__, '@@manage')+'#tab2')
405        return
406
407    def update(self):
408        if self.context.owner != NOT_OCCUPIED:
409            # Don't use this form for exchanging students.
410            # Beds must be released first before they can be allocated to
411            # other students.
412            self.redirect(self.url(self.context.__parent__, '@@manage')+'#tab2')
413        return
Note: See TracBrowser for help on using the repository browser.