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

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

Add bed statistics view components.

  • Property svn:keywords set to Id
File size: 14.6 KB
Line 
1## $Id: browser.py 13484 2015-11-19 11:34:48Z 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        flash_message = _(
302            '${a} empty beds removed, ${b} beds added, '
303            + '${c} occupied beds modified (${d})',
304            mapping = {'a':removed, 'b':added, 'c':modified, 'd':modified_beds})
305        self.flash(flash_message)
306        self.context.writeLogMessage(self, message)
307        self.redirect(self.url(self.context, '@@manage')+'#tab2')
308        return
309
310    @action(_('Switch reservation of selected beds'))
311    def switchReservations(self, **data):
312        form = self.request.form
313        if 'val_id' in form:
314            child_id = form['val_id']
315        else:
316            self.flash(_('No item selected.'), type='warning')
317            self.redirect(self.url(self.context, '@@manage')+'#tab2')
318            return
319        if not isinstance(child_id, list):
320            child_id = [child_id]
321        switched = [] # for log file
322        switched_translated = [] # for flash message
323        # Here we know that the cookie has been set
324        preferred_language = self.request.cookies.get('kofa.language')
325        for bed_id in child_id:
326            message = self.context[bed_id].switchReservation()
327            switched.append('%s (%s)' % (bed_id,message))
328            m_translated = translate(message, 'waeup.kofa',
329                target_language=preferred_language)
330            switched_translated.append('%s (%s)' % (bed_id,m_translated))
331        if len(switched):
332            message = ', '.join(switched)
333            m_translated = ', '.join(switched_translated)
334            if len(switched) > 50:
335                self.flash(_('Successfully switched ${a} beds.',
336                    mapping = {'a':len(switched)}))
337            else:
338                self.flash(_('Successfully switched beds: ${a}',
339                    mapping = {'a':m_translated}))
340            self.context.writeLogMessage(self, 'switched: %s' % message)
341            self.redirect(self.url(self.context, '@@manage')+'#tab2')
342        return
343
344    @action(_('Release selected beds'))
345    def releaseBeds(self, **data):
346        form = self.request.form
347        if 'val_id' in form:
348            child_id = form['val_id']
349        else:
350            self.flash(_('No item selected.'), type='warning')
351            self.redirect(self.url(self.context, '@@manage')+'#tab2')
352            return
353        if not isinstance(child_id, list):
354            child_id = [child_id]
355        released = []
356        for bed_id in child_id:
357            message = self.context[bed_id].releaseBed()
358            if message:
359                released.append('%s (%s)' % (bed_id,message))
360        if len(released):
361            message = ', '.join(released)
362            self.flash(_('Successfully released beds: ${a}',
363                mapping = {'a':message}))
364            self.context.writeLogMessage(self, 'released: %s' % message)
365            self.redirect(self.url(self.context, '@@manage')+'#tab2')
366        else:
367            self.flash(_('No allocated bed selected.'), type='warning')
368            self.redirect(self.url(self.context, '@@manage')+'#tab2')
369        return
370
371    @jsaction(_('Clear hostel'), style='danger')
372    def clearHostel(self, **data):
373        self.context.clearHostel()
374        self.flash(_('Hostel cleared.'))
375        self.context.writeLogMessage(self, 'cleared')
376        self.redirect(self.url(self.context, '@@manage')+'#tab2')
377        return
378
379class BedManageFormPage(KofaEditFormPage):
380    """ View to edit bed data
381    """
382    grok.context(IBed)
383    grok.name('index')
384    grok.require('waeup.manageHostels')
385    form_fields = grok.AutoFields(IBed).omit(
386        'bed_id', 'bed_number', 'bed_type')
387    label = _('Allocate student')
388    pnav = 5
389    doclink = DOCLINK + '/hostels.html#manage-bed'
390
391    @action(_('Save'))
392    def save(self, **data):
393        if data['owner'] == NOT_OCCUPIED:
394            self.flash(_('No valid student id.'), type='warning')
395            self.redirect(self.url(self.context))
396            return
397        msave(self, **data)
398        self.redirect(self.url(self.context.__parent__, '@@manage')+'#tab2')
399        return
400
401    def update(self):
402        if self.context.owner != NOT_OCCUPIED:
403            # Don't use this form for exchanging students.
404            # Beds must be released first before they can be allocated to
405            # other students.
406            self.redirect(self.url(self.context.__parent__, '@@manage')+'#tab2')
407        return
Note: See TracBrowser for help on using the repository browser.