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

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

Let admin be able to change accommodation session.

  • Property svn:keywords set to Id
File size: 15.6 KB
Line 
1## $Id: browser.py 13565 2016-01-04 10:33:46Z 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) and not self.request.principal.id == 'admin':
178                self.flash(_('You can\'t change the booking session '
179                             'before clearing all hostels.'),
180                           type='warning')
181                return
182        msave(self, **data)
183        return
184
185class ReleaseExpiredAllocationsPage(UtilityView, grok.View):
186    """Release all expired allocated beds.
187    """
188    grok.context(IHostelsContainer)
189    grok.name('releaseexpired')
190    grok.require('waeup.manageHostels')
191
192    def update(self, n=7):
193        if not grok.getSite()['configuration'].maintmode_enabled_by:
194            self.flash(
195                _('Portal must be in maintenance mode for releasing expired '
196                  'bed allocations.'),
197                type='danger')
198            self.redirect(self.url(self.context))
199            return
200        released = self.context.releaseExpiredAllocations(n)
201        if len(released):
202            message = ', '.join(released)
203            self.context.writeLogMessage(self, 'released: %s' % message)
204            if len(released) > 50:
205                flash_msg = _('Successfully released ${a} beds.',
206                    mapping = {'a':len(released)})
207            else:
208                flash_msg = _('Successfully released beds: ${a}',
209                    mapping = {'a':message})
210        else:
211            flash_msg = _('No bed released.')
212        self.flash(flash_msg, type='success')
213        self.redirect(self.url(self.context))
214        return
215
216    def render(self):
217        return
218
219class HostelsStatisticsPage(KofaDisplayFormPage):
220    """Some statistics about beds in hostels.
221    """
222    grok.context(IHostelsContainer)
223    grok.name('statistics')
224    grok.require('waeup.manageHostels')
225    grok.template('containerstatistics')
226    label = _('Bed Statistics')
227
228class HostelAddFormPage(KofaAddFormPage):
229    """Add-form to add a hostel.
230    """
231    grok.context(IHostelsContainer)
232    grok.require('waeup.manageHostels')
233    grok.name('addhostel')
234    #grok.template('hosteladdpage')
235    form_fields = grok.AutoFields(IHostel).omit('beds_reserved', 'hostel_id')
236    label = _('Add hostel')
237    pnav = 5
238    doclink = DOCLINK + '/hostels.html#accommodation-section'
239
240    @action(_('Create hostel'))
241    def addHostel(self, **data):
242        hostel = Hostel()
243        self.applyData(hostel, **data)
244        hostel.hostel_id = data['hostel_name'].lower().replace(
245            ' ','-').replace('_','-').replace('.','')
246        try:
247            self.context.addHostel(hostel)
248        except KeyError:
249            self.flash(_('The hostel already exists.'), type='warning')
250            return
251        self.flash(_('Hostel created.'))
252        self.context.writeLogMessage(self, 'added: % s' % data['hostel_name'])
253        self.redirect(self.url(self.context[hostel.hostel_id], 'index'))
254        return
255
256class HostelDisplayFormPage(KofaDisplayFormPage):
257    """ Page to display hostel data
258    """
259    grok.context(IHostel)
260    grok.name('index')
261    grok.require('waeup.viewHostels')
262    grok.template('hostelpage')
263    form_fields = grok.AutoFields(IHostel).omit('beds_reserved')
264    pnav = 5
265
266    @property
267    def label(self):
268        return self.context.hostel_name
269
270class HostelManageActionButton(ManageActionButton):
271    grok.order(1)
272    grok.context(IHostel)
273    grok.view(HostelDisplayFormPage)
274    grok.require('waeup.manageHostels')
275    text = _('Manage')
276    target = 'manage'
277
278class HostelManageFormPage(KofaEditFormPage):
279    """ View to edit hostel data
280    """
281    grok.context(IHostel)
282    grok.name('manage')
283    grok.require('waeup.manageHostels')
284    form_fields = grok.AutoFields(IHostel).omit('hostel_id', 'beds_reserved')
285    grok.template('hostelmanagepage')
286    label = _('Manage hostel')
287    pnav = 5
288    taboneactions = [_('Save')]
289    tabtwoactions = [_('Update all beds'),
290        _('Switch reservation of selected beds'),
291        _('Release selected beds'),
292        _('Clear hostel')]
293    not_occupied = NOT_OCCUPIED
294    doclink = DOCLINK + '/hostels.html#browser-pages'
295
296    @property
297    def students_url(self):
298        return self.url(grok.getSite(),'students')
299
300    @action(_('Save'), style='primary')
301    def save(self, **data):
302        msave(self, **data)
303        return
304
305    @action(_('Update all beds'), style='primary',
306            warning=_('Attention: The updater removes all reservation flags of existing beds.'
307                        ' You really want to update?'))
308    def updateBeds(self, **data):
309        if not grok.getSite()['configuration'].maintmode_enabled_by:
310            self.flash(
311                _('Portal must be in maintenance mode for bed updates.'),
312                type='danger')
313            self.redirect(self.url(self.context, '@@manage')+'#tab2')
314            return
315        removed, added, modified, modified_beds = self.context.updateBeds()
316        message = '%d empty beds removed, %d beds added, %d occupied beds modified (%s)' % (
317            removed, added, modified, modified_beds)
318        if modified > 50:
319            flash_message = _(
320                '${a} empty beds removed, ${b} beds added, '
321                + '${c} occupied beds modified',
322                mapping = {'a':removed, 'b':added, 'c':modified})
323        else:
324            flash_message = _(
325                '${a} empty beds removed, ${b} beds added, '
326                + '${c} occupied beds modified (${d})',
327                mapping = {'a':removed, 'b':added, 'c':modified, 'd':modified_beds})
328        self.flash(flash_message)
329        self.context.writeLogMessage(self, message)
330        self.redirect(self.url(self.context, '@@manage')+'#tab2')
331        return
332
333    @action(_('Switch reservation of selected beds'))
334    def switchReservations(self, **data):
335        form = self.request.form
336        if 'val_id' in form:
337            child_id = form['val_id']
338        else:
339            self.flash(_('No item selected.'), type='warning')
340            self.redirect(self.url(self.context, '@@manage')+'#tab2')
341            return
342        if not isinstance(child_id, list):
343            child_id = [child_id]
344        switched = [] # for log file
345        switched_translated = [] # for flash message
346        # Here we know that the cookie has been set
347        preferred_language = self.request.cookies.get('kofa.language')
348        for bed_id in child_id:
349            message = self.context[bed_id].switchReservation()
350            switched.append('%s (%s)' % (bed_id,message))
351            m_translated = translate(message, 'waeup.kofa',
352                target_language=preferred_language)
353            switched_translated.append('%s (%s)' % (bed_id,m_translated))
354        if len(switched):
355            message = ', '.join(switched)
356            m_translated = ', '.join(switched_translated)
357            if len(switched) > 50:
358                self.flash(_('Successfully switched ${a} beds.',
359                    mapping = {'a':len(switched)}))
360            else:
361                self.flash(_('Successfully switched beds: ${a}',
362                    mapping = {'a':m_translated}))
363            self.context.writeLogMessage(self, 'switched: %s' % message)
364            self.redirect(self.url(self.context, '@@manage')+'#tab2')
365        return
366
367    @action(_('Release selected beds'))
368    def releaseBeds(self, **data):
369        form = self.request.form
370        if 'val_id' in form:
371            child_id = form['val_id']
372        else:
373            self.flash(_('No item selected.'), type='warning')
374            self.redirect(self.url(self.context, '@@manage')+'#tab2')
375            return
376        if not isinstance(child_id, list):
377            child_id = [child_id]
378        released = []
379        for bed_id in child_id:
380            message = self.context[bed_id].releaseBed()
381            if message:
382                released.append('%s (%s)' % (bed_id,message))
383        if len(released):
384            message = ', '.join(released)
385            self.flash(_('Successfully released beds: ${a}',
386                mapping = {'a':message}))
387            self.context.writeLogMessage(self, 'released: %s' % message)
388            self.redirect(self.url(self.context, '@@manage')+'#tab2')
389        else:
390            self.flash(_('No allocated bed selected.'), type='warning')
391            self.redirect(self.url(self.context, '@@manage')+'#tab2')
392        return
393
394    @jsaction(_('Clear hostel'), style='danger')
395    def clearHostel(self, **data):
396        self.context.clearHostel()
397        self.flash(_('Hostel cleared.'))
398        self.context.writeLogMessage(self, 'cleared')
399        self.redirect(self.url(self.context, '@@manage')+'#tab2')
400        return
401
402class BedManageFormPage(KofaEditFormPage):
403    """ View to edit bed data
404    """
405    grok.context(IBed)
406    grok.name('index')
407    grok.require('waeup.manageHostels')
408    form_fields = grok.AutoFields(IBed).omit(
409        'bed_id', 'bed_number', 'bed_type')
410    label = _('Allocate student')
411    pnav = 5
412    doclink = DOCLINK + '/hostels.html#manage-bed'
413
414    @action(_('Save'))
415    def save(self, **data):
416        if data['owner'] == NOT_OCCUPIED:
417            self.flash(_('No valid student id.'), type='warning')
418            self.redirect(self.url(self.context))
419            return
420        msave(self, **data)
421        self.redirect(self.url(self.context.__parent__, '@@manage')+'#tab2')
422        return
423
424    def update(self):
425        if self.context.owner != NOT_OCCUPIED:
426            # Don't use this form for exchanging students.
427            # Beds must be released first before they can be allocated to
428            # other students.
429            self.redirect(self.url(self.context.__parent__, '@@manage')+'#tab2')
430        return
Note: See TracBrowser for help on using the repository browser.