class PaymentsController(BaseController): def __init__(self): super(PaymentsController, self).__init__() self.lmf = LdapModelFactory() def __before__(self, action, **param): super(PaymentsController, self).__before__() def _sidebar(self): super(PaymentsController, self)._sidebar() c.actions.append({'name' : _('All payments'), 'args' : {'controller' : 'payments', 'action' : 'listPayments'}}) c.actions.append({'name' : _('Outstanding payment'), 'args' : {'controller' : 'payments', 'action' : 'index'}}) def index(self): if self.isAdmin() or self.lmf.isUserInGroup(self.identity, 'office'): return self.showOutstanding() return redirect(url(controller='payments', action='listPayments', member_id=self.identity)) @BaseController.needFinanceAdmin def validatePayment(self): """ Validate a payment specified by an id """ try: ParamChecker.checkUsername('member_id', param=True) ParamChecker.checkInt('idPayment', param=True) except: redirect(url(controller='payments', action='index')) try: np = Session.query(Payment).filter(Payment.id == request.params['idPayment']).one() if np.verified: np.verified = False else: np.verified = True Session.commit() session['flash'] = _('Payment validation successfully toggled') session['flash_class'] = 'success' except: session['flash'] = _('Saving payment failed') session['flash_class'] = 'error' session.save() redirect(url(controller='payments', action='listPayments', member_id=request.params['member_id'])) def _getLastPayment(self, uid): member = self.lmf.getUser(uid) lastDate = parser.parse(member.arrivalDate) try: p = Session.query(Payment).filter(and_(Payment.uid == uid, or_(Payment.status == 0, Payment.status == 2))).order_by(Payment.date.desc()).first() lastDate = p.date + relativedelta(months = + 1) except Exception as e: pass return lastDate def bulkAdd(self): try: ParamChecker.checkUsername('member_id', param=True) except: redirect(url(controller='payments', action='index')) c.member_id = request.params['member_id'] c.heading = _('Add bulk payments') return render('/payments/bulkAdd.mako') def doBulkAdd(self): try: ParamChecker.checkUsername('member_id', param=True) ParamChecker.checkInt('months', param=True, max_len=2) except: redirect(url(controller='payments', action='index')) lastDate = self._getLastPayment(request.params['member_id']) months = int(request.params['months']) verified = False if self.isFinanceAdmin(): try: ParamChecker.checkInt('verified', param=True, max_len=1) verified = True except: pass try: for i in range(months): p = Payment() p.uid = request.params['member_id'] p.date = lastDate + relativedelta(months = i) p.status = 0 p.verified = verified Session.add(p) Session.commit() session['flash'] = _('Payments added') session['flash_class'] = 'success' except Exception as e: session['flash'] = _('Operation failed') session['flash_class'] = 'error' session.save() redirect(url(controller='payments', action='listPayments', member_id=request.params['member_id'])) @BaseController.needAdmin def showOutstanding(self): """ Show which users still need to pay their membership fees and if a reminder has already been sent """ showAll = False if request.params.get('showAll', '') == '1': showAll = True activeMembers = self.lmf.getActiveMemberList() # Prepare add payment form c.heading = _('Outstanding payments') c.members = [] c.member_ids = [] for uid in activeMembers: last_payment = None try: last_payment = Session.query(Payment).filter(and_(Payment.uid == uid, Payment.verified == 1)).order_by(Payment.date.desc()).limit(1)[0] except: ''' Don't care if there is no payment ''' pass m = self.lmf.getUser(uid) m.paymentGood = False if last_payment: d = last_payment.date today = datetime.now().date() if d.year > today.year or (d.year == today.year and d.month >= today.month): m.paymentGood = True if not m.paymentGood or showAll: c.members.append(m) c.member_ids.append(uid) return render('/payments/showOutstanding.mako') def listPayments(self): """ Show a specific user's payments """ if not 'member_id' in request.params: if not self.isAdmin() and not self.isFinanceAdmin(): redirect(url(controller='error', action='forbidden')) else: redirect(url(controller='payments', action='showOutstanding', showAll='1')) elif not self.isAdmin() and not self.isFinanceAdmin() and not request.params['member_id'] == self.identity: redirect(url(controller='error', action='forbidden')) year = None if year is None: try: ParamChecker.checkInt('year', param=True, max_len=4) if int(request.params['year']) > 1970 and int(request.params['year']) < 2222: year = int(request.params['year']) except: pass if year is None: try: ParamChecker.checkUsername('member_id', param=True) year = self._getLastPayment(request.params['member_id']).year except: pass if year is None: year = datetime.now().year c.heading = _('Payments for the year %s, user %s') % (str(year), request.params['member_id']) c.member_id = request.params['member_id'] ## consider pagination # http://pylonsbook.com/en/1.1/starting-the-simplesite-tutorial.html#using-pagination try: #c.member.leavingDate = date(int(member.leavingDate[:4]),int(member.leavingDate[5:6]),int(member.leavingDate[7:8])) ## ideally, fetch monthly from member and the rest from payment (one to many relation) ## http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html y_start = date(year, 1, 1) y_end = date(year, 12, 31) payment_sql = Session.query(Payment).filter(Payment.uid == request.params['member_id']).filter(Payment.date.between(y_start, y_end)).order_by(Payment.date.desc()).all() payments = {} c.unverifiedPledges = 0 for p in payment_sql: if p.verified == 0: c.unverifiedPledges += 1 payments[p.date.month] = p c.year = year c.payments = payments except AttributeError, e: return 'This member has made no payments o.O ?!: %s' % e except NoResultFound: return "this member has no payments on records" # replace by "this member has made no payments" message
class GroupsController(BaseController): def __init__(self): super(GroupsController, self).__init__() self.lmf = LdapModelFactory() def __before__(self, action, **param): super(GroupsController, self).__before__() def _sidebar(self): super(GroupsController, self)._sidebar() c.actions.append({'name' : _('Show all groups'), 'args' : {'controller' : 'groups', 'action' : 'listGroups'}}) c.actions.append({'name' : _('Add Group'), 'args' : {'controller' : 'groups', 'action' : 'editGroup'}}) c.actions.append({'name' : _('Members'), 'args' : {'controller' : 'members', 'action' : 'index'}}) def index(self): if self.lmf.isUserInGroup(self.identity, 'office') or self.lmf.isUserInGroup(self.identity, 'sysops'): return self.listGroups() return redirect(url(controller='profile', action='index')) @BaseController.needGroup('superadmins') def listGroups(self): c.heading = _('Managed groups') c.groups = self.lmf.getManagedGroupList() return render('/groups/listGroups.mako') @BaseController.needGroup('superadmins') def editGroup(self): # vary form depending on mode (do that over ajax) if request.params.get('gid', '') == '': c.group = Group() action = 'Adding' c.gid = '' else: try: ParamChecker.checkUsername('gid', param=True) except: redirect(url(controller='groups', action='index')) action = 'Editing' c.gid = request.params['gid'] try: c.group = self.lmf.getGroup(request.params['gid']) users = '' for u in c.group.users: if not users == '': users += '\n' users += u c.group.users = users except LookupError: # @TODO implement better handler print 'No such group!' redirect(url(controller='groups', action='index')) c.heading = '{0} group'.format(action) return render('/groups/editGroup.mako') def checkEdit(f): def new_f(self): if not 'gid' in request.params: redirect(url(controller='groups', action='index')) else: formok = True errors = [] items = {} try: ParamChecker.checkUsername('gid', param=True) except: formok = False errors.append(_('Invalid group ID')) items['users'] = [] if 'users' in request.params: try: #ParamChecker.checkString('users', param=True, min_len=-1, max_len=9999, regex=r'([\w]{1,20}\n?)*') for k in request.params['users'].split('\n'): m = k.replace('\r', '').replace(' ', '') if m == '': continue else: ParamChecker.checkUsername(m, param=False) items['users'].append(m) except InvalidParameterFormat as ipf: formok = False errors.append(_('Invalid user name(s)')) if not formok: session['errors'] = errors session['reqparams'] = {} # @TODO request.params may contain multiple values per key... test & fix for k in request.params.iterkeys(): session['reqparams'][k] = request.params[k] session.save() redirect(url(controller='groups', action='editGroup', gid=request.params['gid'])) else: items['gid'] = request.params['gid'] return f(self, items) return new_f @BaseController.needGroup('superadmins') @checkEdit @restrict('POST') def doEditGroup(self, items): if not self.lmf.addGroup(items['gid']): session['flash'] = _('Failed to add group!') session['flash_class'] = 'error' session.save() else: try: lgrp_members = self.lmf.getGroupMembers(items['gid']) except LookupError: lgrp_members = [] # Adding new members for m in items['users']: if not m in lgrp_members: #print 'adding -> ' + str(m) self.lmf.changeUserGroup(m, items['gid'], True) # Removing members for m in lgrp_members: if not m in items['users']: #print 'removing -> ' + str(m) self.lmf.changeUserGroup(m, items['gid'], False) # @TODO add group if not exist session['flash'] = _('Group saved successfully') session['flash_class'] = 'success' session.save() redirect(url(controller='groups', action='index')) @BaseController.needGroup('superadmins') def unmanageGroup(self): try: ParamChecker.checkUsername('gid', param=True) except: redirect(url(controller='groups', action='index')) result = self.lmf.unmanageGroup(request.params['gid']) if result: session['flash'] = _('Group no longer managed') session['flash_class'] = 'success' else: session['flash'] = _('Failed to remove group from management!') session['flash_class'] = 'error' session.save() redirect(url(controller='groups', action='index')) @BaseController.needGroup('superadmins') def deleteGroup(self): try: ParamChecker.checkUsername('gid', param=True) except: redirect(url(controller='groups', action='index')) result = self.lmf.deleteGroup(request.params['gid']) if result: session['flash'] = _('Group successfully deleted') session['flash_class'] = 'success' else: session['flash'] = _('Failed to delete group!') session['flash_class'] = 'error' session.save() redirect(url(controller='groups', action='index'))