source: main/waeup.sirp/branches/ulif-groktoolkit-1.4/src/waeup/sirp/hostels/browser.py @ 9169

Last change on this file since 9169 was 7694, checked in by Henrik Bettermann, 13 years ago

Remove unneeded import.

  • Property svn:keywords set to Id
File size: 10.6 KB
Line 
1## $Id: browser.py 7694 2012-02-23 17:35:54Z 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 waeup.sirp.browser import (
23    SIRPEditFormPage, SIRPAddFormPage, SIRPDisplayFormPage,
24    NullValidator)
25from waeup.sirp.browser.breadcrumbs import Breadcrumb
26from waeup.sirp.browser.resources import datepicker, datatable, tabs, warning
27from waeup.sirp.browser.layout import default_primary_nav_template
28from waeup.sirp.browser.pages import delSubobjects
29from waeup.sirp.browser.viewlets import (
30    ManageActionButton, PrimaryNavTab)
31from waeup.sirp.browser.layout import jsaction, action
32from waeup.sirp.interfaces import ISIRPObject
33from waeup.sirp.hostels.vocabularies import NOT_OCCUPIED
34from waeup.sirp.hostels.hostel import Hostel
35from waeup.sirp.hostels.interfaces import (
36    IHostelsContainer, IHostel, IBed, IBedAllocateStudent)
37
38from waeup.sirp.interfaces import MessageFactory as _
39
40def write_log_message(view, message):
41    ob_class = view.__implemented__.__name__.replace('waeup.sirp.','')
42    view.context.loggerInfo(ob_class, message)
43    return
44
45# Save function used for save methods in manager pages
46def msave(view, **data):
47    changed_fields = view.applyData(view.context, **data)
48    # Turn list of lists into single list
49    if changed_fields:
50        changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
51    fields_string = ' + '.join(changed_fields)
52    view.context._p_changed = True
53    view.flash('Form has been saved.')
54    if fields_string:
55        write_log_message(view, 'saved: % s' % fields_string)
56    return
57
58class HostelsTab(PrimaryNavTab):
59    """Hostels tab in primary navigation.
60    """
61
62    grok.context(ISIRPObject)
63    grok.order(5)
64    grok.require('waeup.viewHostels')
65    template = default_primary_nav_template
66    pnav = 5
67    tab_title = _(u'Hostels')
68
69    @property
70    def link_target(self):
71        return self.view.application_url('hostels')
72
73class HostelsBreadcrumb(Breadcrumb):
74    """A breadcrumb for the hostels container.
75    """
76    grok.context(IHostelsContainer)
77    title = u'Hostels'
78
79class HostelBreadcrumb(Breadcrumb):
80    """A breadcrumb for the hostel container.
81    """
82    grok.context(IHostel)
83
84    def title(self):
85        return self.context.hostel_name
86
87class BedBreadcrumb(Breadcrumb):
88    """A breadcrumb for the hostel container.
89    """
90    grok.context(IBed)
91
92    def title(self):
93        co = self.context.getBedCoordinates()
94        return 'Block %s, Room %s, Bed %s' % (co[1], co[2], co[3])
95
96class HostelsContainerPage(SIRPDisplayFormPage):
97    """The standard view for hostels containers.
98    """
99    grok.context(IHostelsContainer)
100    grok.name('index')
101    grok.require('waeup.viewHostels')
102    grok.template('containerpage')
103    label = 'Accommodation Section'
104    pnav = 5
105
106class HostelsContainerManageActionButton(ManageActionButton):
107    grok.order(1)
108    grok.context(IHostelsContainer)
109    grok.view(HostelsContainerPage)
110    grok.require('waeup.manageHostels')
111    text = 'Manage accommodation section'
112
113class HostelsContainerManagePage(SIRPDisplayFormPage):
114    """The manage page for hostel containers.
115    """
116    grok.context(IHostelsContainer)
117    grok.name('manage')
118    grok.require('waeup.manageHostels')
119    grok.template('containermanagepage')
120    pnav = 5
121    label = 'Manage accommodation section'
122
123    def update(self):
124        warning.need()
125        return super(HostelsContainerManagePage, self).update()
126
127    # It's quite dangerous to remove entire hostels with its content (beds).
128    # Thus, this remove method should be combined with an archiving function.
129    @jsaction('Remove selected')
130    def delHostels(self, **data):
131        form = self.request.form
132        if form.has_key('val_id'):
133            deleted = []
134            child_id = form['val_id']
135            if not isinstance(child_id, list):
136                child_id = [child_id]
137            for id in child_id:
138                deleted.append(id)
139            write_log_message(self, 'deleted: % s' % ', '.join(deleted))
140        delSubobjects(self, redirect='@@manage', tab='2')
141        return
142
143    @action('Add hostel', validator=NullValidator)
144    def addSubunit(self, **data):
145        self.redirect(self.url(self.context, 'addhostel'))
146        return
147
148class HostelAddFormPage(SIRPAddFormPage):
149    """Add-form to add a hostel.
150    """
151    grok.context(IHostelsContainer)
152    grok.require('waeup.manageHostels')
153    grok.name('addhostel')
154    #grok.template('hosteladdpage')
155    form_fields = grok.AutoFields(IHostel)
156    label = 'Add hostel'
157    pnav = 5
158
159    @action('Create hostel')
160    def addHostel(self, **data):
161        hostel = Hostel()
162        self.applyData(hostel, **data)
163        hostel.hostel_id = data[
164            'hostel_name'].lower().replace(' ','-').replace('_','-')
165        try:
166            self.context.addHostel(hostel)
167        except KeyError:
168            self.flash('The hostel already exists.')
169            return
170        self.flash('Hostel created.')
171        write_log_message(self, 'added: % s' % data['hostel_name'])
172        self.redirect(self.url(self.context[hostel.hostel_id], 'index'))
173        return
174
175class HostelDisplayFormPage(SIRPDisplayFormPage):
176    """ Page to display hostel data
177    """
178    grok.context(IHostel)
179    grok.name('index')
180    grok.require('waeup.viewHostels')
181    #grok.template('hostelpage')
182    pnav = 5
183
184    @property
185    def label(self):
186        return self.context.hostel_name
187
188class HostelManageActionButton(ManageActionButton):
189    grok.order(1)
190    grok.context(IHostel)
191    grok.view(HostelDisplayFormPage)
192    grok.require('waeup.manageHostels')
193    text = 'Manage'
194    target = 'manage'
195
196class HostelManageFormPage(SIRPEditFormPage):
197    """ View to edit hostel data
198    """
199    grok.context(IHostel)
200    grok.name('manage')
201    grok.require('waeup.manageHostels')
202    form_fields = grok.AutoFields(IHostel).omit('hostel_id')
203    grok.template('hostelmanagepage')
204    label = 'Manage hostel'
205    pnav = 5
206    taboneactions = ['Save']
207    tabtwoactions = ['Update all beds',
208        'Switch reservation of selected beds',
209        'Release selected beds']
210    not_occupied = NOT_OCCUPIED
211
212    @property
213    def students_url(self):
214        return self.url(grok.getSite(),'students')
215
216    def update(self):
217        datepicker.need() # Enable jQuery datepicker in date fields.
218        tabs.need()
219        datatable.need()
220        self.tab1 = self.tab2 = ''
221        qs = self.request.get('QUERY_STRING', '')
222        if not qs:
223            qs = 'tab1'
224        setattr(self, qs, 'active')
225        super(HostelManageFormPage, self).update()
226        return
227
228    @action('Save')
229    def save(self, **data):
230        msave(self, **data)
231        return
232
233    @action('Update all beds')
234    def updateBeds(self, **data):
235        removed, added, modified, modified_beds = self.context.updateBeds()
236        message = '%d empty beds removed, %d beds added, %d occupied beds modified (%s)' % (
237            removed, added, modified, modified_beds)
238        self.flash(message)
239        write_log_message(self, message)
240        self.redirect(self.url(self.context, '@@manage')+'?tab2')
241        return
242
243    @action('Switch reservation of selected beds')
244    def switchReservations(self, **data):
245        form = self.request.form
246        if form.has_key('val_id'):
247            child_id = form['val_id']
248        else:
249            self.flash('No item selected.')
250            self.redirect(self.url(self.context, '@@manage')+'?tab2')
251            return
252        if not isinstance(child_id, list):
253            child_id = [child_id]
254        switched = []
255        for bed_id in child_id:
256            try:
257                message = self.context[bed_id].switchReservation()
258                switched.append('%s (%s)' % (bed_id,message))
259            except:
260                self.flash('Could not switch %s: %s: %s' % (
261                        id, sys.exc_info()[0], sys.exc_info()[1]))
262                self.redirect(self.url(self.context, '@@manage')+'?tab2')
263                return
264        if len(switched):
265            message = ', '.join(switched)
266            self.flash('Successfully switched beds: %s' % message)
267            write_log_message(self, 'switched: %s' % message)
268            self.redirect(self.url(self.context, '@@manage')+'?tab2')
269        return
270
271    @action('Release selected beds')
272    def releaseBeds(self, **data):
273        form = self.request.form
274        if form.has_key('val_id'):
275            child_id = form['val_id']
276        else:
277            self.flash('No item selected.')
278            self.redirect(self.url(self.context, '@@manage')+'?tab2')
279            return
280        if not isinstance(child_id, list):
281            child_id = [child_id]
282        released = []
283        for bed_id in child_id:
284            message = self.context[bed_id].releaseBed()
285            if message:
286                released.append('%s (%s)' % (bed_id,message))
287        if len(released):
288            message = ', '.join(released)
289            self.flash('Successfully released beds: %s' % message)
290            write_log_message(self, 'released: %s' % message)
291            self.redirect(self.url(self.context, '@@manage')+'?tab2')
292        else:
293            self.flash('No allocated bed selected.')
294            self.redirect(self.url(self.context, '@@manage')+'?tab2')
295        return
296
297class BedManageFormPage(SIRPEditFormPage):
298    """ View to edit bed data
299    """
300    grok.context(IBedAllocateStudent)
301    grok.name('index')
302    grok.require('waeup.manageHostels')
303    form_fields = grok.AutoFields(IBedAllocateStudent).omit(
304        'bed_id').omit('bed_number').omit('bed_type')
305    label = 'Allocate student'
306    pnav = 5
307
308    @action('Save')
309    def save(self, **data):
310        msave(self, **data)
311        self.redirect(self.url(self.context.__parent__, '@@manage')+'?tab2')
312        return
313
314    def update(self):
315        if self.context.owner != NOT_OCCUPIED:
316            # Don't use this form for exchanging students.
317            # Beds must be released first before they can be allocated to
318            # other students.
319            self.redirect(self.url(self.context.__parent__, '@@manage')+'?tab2')
320        return
Note: See TracBrowser for help on using the repository browser.