コード例 #1
0
ファイル: transactions.py プロジェクト: vokomokum/vkmkm-erp
    def __call__(self):
        session = DBSession()
        transaction = Transaction()
        params = self.request.params
        year = int(params['year'])
        month = int(params['month'])

        if params['ttype_id'] == '--':
            return self.redir_to_list(year, month, msg='Please select a type.')
        ttype = session.query(TransactionType).get(params['ttype_id'])
        transaction.ttype = ttype
        transaction.amount = float(params['amount'])
        if ttype.mem_sup == 'memb' and 'mem_id' in params:
            transaction.member = session.query(Member).get(params['mem_id'])
        if ttype.mem_sup == 'whol' and 'wh_id' in params:
            transaction.wholesaler = session.query(Wholesaler).get(
                params['wh_id'])
        if ttype.mem_sup == 'vers' and 'vers_id' in params:
            transaction.vers_supplier = session.query(VersSupplier).get(
                params['vers_id'])
        transaction.comment = params['comment']
        if 'ord_no' in params and not params['ord_no'] in ('', '--'):
            transaction.ord_no = int(params['ord_no'])
        if 'late' in params:
            transaction.late = bool(params['late'])

        day = int(params['day'])
        adate = datetime.date(year, month, day)
        transaction.date = adate
        transaction.validate()
        session.add(transaction)
        session.flush()
        return self.redir_to_list(year, month, msg='Transaction "{}" has been '\
                        'added to the list.'.format(str(transaction)))
コード例 #2
0
ファイル: transactions.py プロジェクト: vokomokum/vkmkm-erp
def get_transaction_sums(year, month, ttype):
    '''
    Get the sum of transaction count and money amounts of this type in this month.
    If month is None, get for the whole year.
    If type is None, get the sum for all types.
    '''
    if not month:
        start_month = 1
        end_month = 12
    else:
        start_month = end_month = month
    tz = pytz.timezone('Europe/Amsterdam')
    end_month_date = datetime.date(year, end_month, 1)
    em_info = month_info(end_month_date)
    first = tz.localize(datetime.datetime(year, start_month, 1, 0, 0, 0))
    last = tz.localize(
        datetime.datetime(year, end_month, em_info.days_in_month, 23, 59, 59))
    query_filter = " WHERE date >= '{}' AND date <= '{}'".format(first, last)
    if ttype:
        query_filter += " AND ttype_id = {}".format(ttype.id)
    query_a = "SELECT sum(amount) FROM transactions {}".format(query_filter)
    query_c = "SELECT count(*) FROM transactions {}".format(query_filter)
    amount = list(DBSession().connection().engine.execute(query_a))[0][0]
    if not amount:
        amount = 0.0
    count = list(DBSession().connection().engine.execute(query_c))[0][0]
    return {'count': int(count), 'amount': round(float(amount), 2)}
コード例 #3
0
ファイル: workgroup.py プロジェクト: vokomokum/vkmkm-erp
    def __call__(self):
        dbsession = DBSession()
        wg_query = dbsession.query(Workgroup)

        # -- inactive workgroups? --
        show_inactive = True
        if not 'include_inactive' in self.request.params\
           or not self.request.params['include_inactive']:
            show_inactive = False
            wg_query = wg_query.filter(Workgroup.active == True)

        # show msg
        if 'msg' in self.request.params:
            msg = self.request.params['msg']
        else:
            msg = ''

        # -- ordering --
        # direction
        odir = asc
        if 'order_dir' in self.request.params\
           and self.request.params['order_dir'] == 'desc':
            odir = desc
        # ordering choice
        order_name_choice = 'asc'
        if odir == asc:
            order_name_choice = 'desc'

        wg_query = wg_query.order_by(odir('id'))
        workgroups = wg_query.all()
        self.wg_count = len(workgroups)
        return dict(workgroups=workgroups,
                    msg=msg,
                    order_name_choice=order_name_choice,
                    show_inactive=show_inactive)
コード例 #4
0
    def __call__(self):
        db_session = DBSession()

        wg = get_wg(db_session, self.request)
        self.user_is_wgmember = self.user in wg.members
        self.user_is_wgleader = self.user in wg.leaders

        # we view shifts per-month here
        # use parameters to determine month, default is current month
        self.month = int(self.request.matchdict['month'])
        self.year = int(self.request.matchdict['year'])
        schedule_date = datetime.date(self.year, self.month, 1)
        self.month_info = month_info(schedule_date)
        q = """SELECT descr FROM shift_days_descriptions ORDER BY id;"""
        day_literals = [i[0] for i in list(db_session.execute(q))]
        self.days = day_literals + list(
            range(1, self.month_info.days_in_month + 1))
        shifts = db_session.query(Shift).filter(Shift.wg_id == wg.id)\
                                     .filter(Shift.month == self.month)\
                                     .filter(Shift.year == self.year)\
                                     .order_by(Shift.day, Shift.task, Shift.mem_id)\
                                     .all()

        # show msg
        if 'msg' in self.request.params:
            msg = self.request.params['msg']
        else:
            msg = ''

        return dict(shifts=shifts, wg=wg, msg=msg)
コード例 #5
0
ファイル: pwdreset.py プロジェクト: vokomokum/vkmkm-erp
 def __call__(self):
     '''
     Default: Show form to identify member
     If data entered and member identified, send reset request email 
     '''
     self.login_necessary = False
     session = DBSession()
     p = self.request.params
     member = None
     if 'email' in p and p['email'] != "":
         member = session.query(Member)\
                         .filter(Member.mem_email == p['email']).first()
     if 'mem_id' in p and p['mem_id'] != "":
         try:
             member = get_member(session, self.request)
         except Exception:
             member = None
     if member:
         send_pwdreset_request(member, self.request.application_url)
         return dict(msg=u'A reset link has been sent to the email'\
                          ' address {!s}.'.format(member.mem_email),
                     m=member, form=None, key=None)
     if (('email' in p and p['email'] != "")
             or ('mem_id' in p and p['mem_id'] != "")):
         return dict(msg=u'Cannot find any member with this information.',
                     m=member,
                     form='request',
                     key=None)
     return dict(msg=u'', m=member, form='request', key=None)
コード例 #6
0
ファイル: orders.py プロジェクト: vokomokum/vkmkm-erp
def number_of_current_orderers():
    if running_sqlite():
        return -1
    query = """SELECT max(ord_no) from wh_line;"""
    cur_ord_no = list(DBSession().connection().engine.execute(query))[0][0]
    cur_order = DBSession.query(Order).filter(Order.id == cur_ord_no).first()
    members = DBSession.query(Member).all()
    orderers = 0
    for m in members:
        mo = MemberOrder(m, cur_order)
        if mo.amount > 0:
            orderers += 1
    return orderers
コード例 #7
0
ファイル: security.py プロジェクト: vokomokum/vkmkm-erp
def get_member(login):
    '''
    Get a member object
    :param string login: the login can either be the member ID or the email-address
    :returns: The Member object or None if none was found for login information
    '''
    mem = None
    session = DBSession()
    if "@" in str(login):  # email address given as login?
        mem = session.query(Member).filter(Member.mem_email == login).first()
    else:  # then assume id
        mem = session.query(Member).filter(Member.mem_id == login).first()
    return mem
コード例 #8
0
    def validate(self):
        ''' checks on address, bank account, ...
        '''
        # check missing fields
        missing = []
        for f in ('mem_fname', 'mem_lname', 'mem_email'):
            if not f in self.__dict__ or self.__dict__[f] == '':
                missing.append(f)
        if len(missing) > 0:
            raise VokoValidationError('We still require you to fill in: %s'\
                                    % ', '.join([m[4:] for m in missing]))
        self.validate_email()
        # also check unique constraint on email address here for nicer error msg
        session = DBSession()
        members = session.query(Member)\
                         .filter(Member.mem_email == self.mem_email).all()
        if len(members) > 0:
            if not (len(members) == 1 and members[0].mem_id == self.mem_id):
                raise VokoValidationError('The email address already exists '\
                                          'for a member in the database.')

        # we want one telephone number, as well
        sd = self.__dict__
        if ((not 'mem_home_tel' in sd and not 'mem_work_tel' in sd
             and not 'mem_mobile' in sd)
                or (self.mem_home_tel == "" and self.mem_work_tel == ""
                    and self.mem_mobile == "")):
            raise VokoValidationError('Please specify at least one telephone '\
                                      'number.')

        # check postcode
        if self.mem_postcode and len(self.mem_postcode) > 0\
                and not (self.mem_postcode[:4].isdigit()\
                and self.mem_postcode[-2:].isalpha()):
            raise VokoValidationError('The postcode does not seem to be'\
                    ' valid (should be NNNNLL, where N=number and L=letter).')
        # check bank no
        if self.mem_bank_no:
            bank_no_clean = self.mem_bank_no.replace(' ', '').replace('-', '')
            if not len(bank_no_clean) in [0, 7, 8, 9]:
                # length of 8 is legacy data
                raise VokoValidationError('Bank number needs to consist of 7 '\
                                          '(postbank) or 9 numbers.')
            if len(bank_no_clean) > 0 and not bank_no_clean.isdigit():
                raise VokoValidationError('Bank number needs to consist of '\
                                          'only numbers.')
        # household size
        if self.mem_household_size is None or self.mem_household_size < 1:
            raise VokoValidationError('Please specify how many people live '\
                                      'in the household.')
コード例 #9
0
    def __call__(self):
        session = DBSession()
        self.wg = session.query(Workgroup).get(
            int(self.request.matchdict['wg_id']))
        self.year = int(self.request.matchdict['year'])

        self.all_shift_data = {}
        self.month_sums = {}
        self.member_sums = {}
        self.members_with_shifts = set()
        for m in self.wg.members:
            self.member_sums[m.mem_id] = [0, 0]
        self.sum_overall = [0, 0]
        self.sum_open_overall = 0
        self.months = [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'
        ]

        q = session.query(Shift).filter(Shift.wg_id == self.wg.id)\
                                .filter(Shift.year == self.year)

        for month in self.months:
            self.all_shift_data[month] = {}
            self.month_sums[month] = [0, 0]
            qm = q.filter(Shift.month == self.months.index(month) + 1)
            for m in self.wg.members:
                qmm = qm.filter(Shift.mem_id == m.mem_id)
                # worked shifts shifts of this member this month
                wmm = qmm.filter(Shift.state == 'worked').count()
                # all assigned (assigned, worked or not-worked)
                amm = wmm + qmm.filter(Shift.state == 'assigned').count()
                amm += qmm.filter(Shift.state == 'no-show').count()
                if amm > 0:
                    self.members_with_shifts.add(m)
                    self.all_shift_data[month][m.mem_id] = wmm, amm
                    self.month_sums[month][0] += wmm
                    self.month_sums[month][1] += amm
                    self.member_sums[m.mem_id][0] += wmm
                    self.member_sums[m.mem_id][1] += amm
                    self.sum_overall[0] += wmm
                    self.sum_overall[1] += amm
            # now open (not assigned) shifts
            om = qm.filter(Shift.state == 'open').count()
            self.all_shift_data[month][-1] = om
            self.sum_open_overall += om

        return dict(msg='')
コード例 #10
0
ファイル: pwdreset.py プロジェクト: vokomokum/vkmkm-erp
    def __call__(self):
        '''
        Actually reset the password, if correct key (from sent link) 
        is used to come here and member is identifiable from request.
        '''
        self.login_necessary = False
        session = DBSession()
        md = self.request.matchdict

        def info(msg):
            return dict(form="", m=None, key=None, msg=msg)

        if not 'key' in md or md['key'] == "":
            return info(u'Sorry, no key given to grant reset request.')
        member = get_member(session, self.request)
        if not member:
            return info(u'Sorry, cannot identify member.')
        if member.mem_pwd_url != md['key']:
            return info(u'Sorry, the reset request cannot be authorised.')
        if 'pwd1' not in self.request.params:
            # show password reset form
            return dict(m=member, form='reset', key=md['key'])
        # set new password
        member.validate_pwd(self.request)
        pwd = str(self.request.params['pwd1'])
        member.mem_enc_pwd = md5_crypt.hash(pwd)
        member.mem_pwd_url = ''
        return info(u'Password has been set.'\
               ' Please use the new password the next time you log in.')
コード例 #11
0
    def __call__(self):
        dbsession = DBSession()
        m_query = dbsession.query(Member)

        # show msg
        if 'msg' in self.request.params:
            msg = self.request.params['msg']
        else:
            msg = ''

        # -- inactive members? --
        show_inactive = True
        if not 'include_inactive' in self.request.params\
           or not self.request.params['include_inactive']:
            show_inactive = False
            m_query = m_query.filter(Member.mem_active == True)

        # -- ordering --
        # direction
        odir = asc
        if 'order_dir' in self.request.params\
           and self.request.params['order_dir'] == 'desc':
            odir = desc
        # order by
        # key is what the outside world sees, value is what SQLAlchemy uses
        order_idxs = {'id': Member.mem_id, 'name': Member.mem_lname}
        order_by = 'id'
        if 'order_by' in self.request.params\
          and self.request.params['order_by'] in order_idxs:
            order_by = self.request.params['order_by']
        # ordering choices
        order_id_choice = 'asc'
        if order_by == 'id' and odir == asc:
            order_id_choice = 'desc'
        order_name_choice = 'asc'
        if order_by == 'name' and odir == asc:
            order_name_choice = 'desc'

        m_query = m_query.order_by(odir(order_idxs[order_by]))
        members = m_query.all()
        self.mem_count = len(members)
        return dict(members=members,
                    msg=msg,
                    order_by=order_by,
                    order_id_choice=order_id_choice,
                    order_name_choice=order_name_choice,
                    show_inactive=show_inactive)
コード例 #12
0
 def __call__(self):
     session = DBSession()
     self.m = get_member(session, self.request)
     msg = ''
     if 'msg' in self.request.params:
         msg = self.request.params['msg']
     nov12 = datetime.datetime(2012, 11, 1)
     orders = [MemberOrder(self.m, o) for o in session.query(Order)\
                 .order_by(desc(Order.completed)).all()]
     old_orders = [o for o in orders if o.amount > 0\
                                   and str(o.order.completed).strip() != ''\
                                   and str(o.order.completed) < str(nov12)]
     return dict(m=self.m,
                 msg=msg,
                 shifts=self.m.shifts,
                 old_orders=old_orders,
                 transactions=self.m.transactions)
コード例 #13
0
 def add_shift(month=None, year=None):
     ''' add a shift object to session, several times if people > 1 '''
     shift = Shift(wg_id, '', None, None, None, None)
     shift.workgroup = DBSession().query(Workgroup).get(wg_id)
     shift = fill_shift_from_request(shift, self.request)
     shift.validate()
     db_session.add(shift)
     self.added_shifts.append(shift)
     if month:
         shift.month = month
     if year:
         shift.year = year
     if people > 1:
         for _ in range(1, people):
             s = shift.clone()
             s.workgroup = DBSession().query(Workgroup).get(s.wg_id)
             s.validate()
             db_session.add(s)
             self.added_shifts.append(s)
コード例 #14
0
 def __call__(self):
     if 'msg' in self.request.params:
         msg = self.request.params['msg']
     else:
         msg = ''
     self.user_can_edit = self.user.mem_admin\
                          or 'Finance' in self.user.workgroups
     return dict(msg=msg,
                 reserved_names = reserved_ttype_names,
                 transaction_types=get_transaction_types(DBSession()))
コード例 #15
0
ファイル: graphs.py プロジェクト: vokomokum/vkmkm-erp
def orders_money_and_people():
    '''
    Count money and number of people who ordered for each order cycle.
    A more straightforward way to do this might be transactions, but we have 
    lots of legacy data without them at Vokomokum and this also works okay.
    '''
    # 1. preparing the data
    session = DBSession()
    orders = session.query(Order).order_by(Order.completed).all()
    members = session.query(Member).all()
    money_list = []
    people_list = []
    max_money = 0
    max_people = 0

    for o in orders:
        money = 0
        people = 0
        for m in members:
            mo = MemberOrder(m, o)
            if mo.amount > 0:
                money += mo.amount
                people += 1
        money_list.append(round(money, 1))
        max_money = max(money, max_money)
        max_people = max(people, max_people)
        people_list.append(people)

    # 2. writing graph configuration
    graph = dict(title=dict(text='Order history'), credits=dict(enabled=False))
    graph['series'] = []
    graph['series'].append(dict(name='money', data=money_list))
    graph['series'].append(dict(name='people', data=people_list, yAxis=1))
    graph['xAxis'] = dict(categories=[o.label for o in orders],
                          tickPositions=[0, len(orders)/2, len(orders)-1])
    graph['yAxis'] = [dict(title=dict(text='money'), min=0, max=max_money*1.1),
                      dict(title=dict(text='people'), min=0, max=max_people*1.1,
                           opposite=True)]

    # 3. write to file 
    settings = get_settings()
    gf = settings['vokomokum.graph_folder']
    json.dump(graph, open('{}/orders_money_and_people.json'.format(gf), 'w')) 
コード例 #16
0
ファイル: workgroup.py プロジェクト: vokomokum/vkmkm-erp
    def __call__(self):
        if 'msg' in self.request.params:
            msg = self.request.params['msg']
        else:
            msg = ''

        session = DBSession()
        wg = get_wg(session, self.request)
        self.user_is_wgleader = self.user in wg.leaders

        return dict(wg=wg, msg=msg, now=datetime.now())
コード例 #17
0
ファイル: security.py プロジェクト: vokomokum/vkmkm-erp
def groupfinder(memid, request):
    session = DBSession()
    groups = ['group:members']
    context = request.context

    if context.__class__ == Member:
        mem_id = request.matchdict.get('mem_id', -1)
        if not mem_id == 'new':
            if int(mem_id) == memid:
                groups.append('group:this-member')

    if context.__class__ == Workgroup:
        if 'wg_id' in request.matchdict:
            wg_id = request.matchdict['wg_id']
            if not wg_id == 'new':
                wg = session.query(Workgroup).get(wg_id)
                if memid in [m.mem_id for m in wg.leaders]:
                    groups.append('group:wg-leaders')
                if memid in [m.mem_id for m in wg.members]:
                    groups.append('group:wg-members')
    admins = session.query(Member).filter(Member.mem_admin == True).all()
    if memid in [m.mem_id for m in admins]:
        groups.append('group:admins')
    # membership people:
    membership = session.query(Workgroup).\
                    filter(Workgroup.name == 'Membership').first()
    if membership:
        if memid in [m.mem_id for m in membership.members]:
            groups.append('group:membership')
    # finance people:
    finance = session.query(Workgroup).\
                    filter(Workgroup.name == 'Finance').first()
    if finance:
        if memid in [m.mem_id for m in finance.members]:
            groups.append('group:finance')
    # bestelling people:
    bestelling = session.query(Workgroup).\
                    filter(Workgroup.name == 'Bestelling').first()
    if bestelling:
        if memid in [m.mem_id for m in bestelling.members]:
            groups.append('group:bestelling')
    # vers bestel people:
    vers_bestel = session.query(Workgroup).\
                    filter(Workgroup.name == 'Vers bestel').first()
    if vers_bestel:
        if memid in [m.mem_id for m in vers_bestel.members]:
            groups.append('group:vers-bestel')

    #print "+++++++++++++++++++++++++++++++++++++++ User is in groups:", groups
    return groups
コード例 #18
0
 def __call__(self):
     session = DBSession()
     tt_id = self.request.matchdict['tt_id']
     name = self.request.params['name']
     tt = get_transaction_type(session, tt_id)
     if tt.name in reserved_ttype_names:
         return self.redirect('/transaction-types?msg=The name {} is '\
                              'reserved and cannot be changed'\
                              .format(tt.name))
     tt.name = name
     tt.validate()
     return self.redirect('/transaction-types?msg=Transaction type "{}" '\
                          'has been saved.'.format(tt.name))
コード例 #19
0
 def __call__(self):
     session = DBSession()
     a_id = self.request.matchdict['a_id']
     applicant = get_applicant(session, a_id)
     session.delete(applicant)
     session.flush()
     return dict(applicants=get_applicants(session),
                 msg="Applicant has been removed from list.")
コード例 #20
0
 def __call__(self):
     session = DBSession()
     if self.logged_in:
         self.show_all = False
         if 'show-all-todos' in self.request.params:
             if self.request.params['show-all-todos'] == '1'\
                and self.user.mem_admin:
                 self.show_all = True
         todos = get_todos(session, self.user, self.show_all)
         graphs = get_graphs()
     else:
         todos = graphs = []
     co = number_of_current_orderers()
     return dict(todos=todos, graphs=graphs, cur_orderers=co)
コード例 #21
0
 def __call__(self):
     '''
     Send members an email about their negative balance.
     We send these mails after orders, that is why this action is tied
     to an order number (it also helps us to keep track a little over
     when we already sent these reminders). 
     '''
     o_id = self.request.matchdict['o_id']
     session = DBSession()
     order = session.query(Order).\
                 filter(Order.id == o_id).first()
     if not order:
         return dict(msg='An order with ID {} does not exist.'.format(o_id),
                     order=None)
     members = [m for m in session.query(Member).all() if m.balance < 0]
     now = datetime.datetime.now()
     deadline = now + datetime.timedelta(days = 3)
     weekdays_en= ['monday', 'tuesday', 'wednesday', 'thursday',
                   'friday', 'saturday', 'sunday']
     weekdays_nl = ['maandag', 'dinsdag', 'woensdag', 'donderdag',
                    'vrijdag', 'zaterdag', 'zondag']
     deadline_en = '{} {}.{}.{}'.format(weekdays_en[deadline.weekday()],
                     deadline.day, deadline.month, deadline.year)
     deadline_nl = '{} {}.{}.{}'.format(weekdays_nl[deadline.weekday()],
                     deadline.day, deadline.month, deadline.year)
     for m in members:
         subject = 'Payment request / Verzoek tot betaling'
         mail_templ = open('members/templates/order_charge_txt.eml', 'r')
         mail = mail_templ.read()
         body = mail.format(mem_id=m.mem_id, label=order.label, amount=round(m.balance, 2),
                    deadline_nl=deadline_nl, deadline_en=deadline_en)
         sendmail(m.mem_email, subject, body,
                     folder='order-charges/{}'.format(order.id),
                     sender='*****@*****.**')
     return dict(msg=u'Emails with payment reminders have been sent out '\
                     'after order {}'.format(order.label))
コード例 #22
0
 def __call__(self):
     session = DBSession()
     member = get_member(session, self.request)
     self.user_may_edit_admin_settings = (
         self.user.mem_admin and not self.user.mem_id == member.mem_id)
     if 'action' in self.request.params:
         action = self.request.params['action']
         if action == "save":
             member = fill_member_from_request(
                 member, self.request, self.user_may_edit_admin_settings)
             member.validate()
             if not member.exists:
                 session.add(member)
                 session.flush()  # flush manually so the member gets an ID
                 send_pwdreset_request(member,
                                       self.request.application_url,
                                       first=True)
                 return self.redirect('/member/{0:d}?msg=Member has been'\
                                      ' created and got an email to set up'\
                                      ' a password. Note: no membership'\
                                      ' fee has been charged (we do not'\
                                      ' know the household size).'\
                                      .format(member.mem_id))
             return dict(m=member, msg='Member has been saved.')
         elif action == 'toggle-active':
             member = get_member(session, self.request)
             self.confirm_toggle_active = True
             return dict(m=member)
         elif action == 'toggle-active-confirmed':
             member.mem_active = not member.mem_active
             msg='Member {} is now {}active.'.\
                 format(member, {False:'in', True:''}[member.mem_active])
             if not member.mem_active and not running_sqlite():
                 query = "select remove_inactive_member_order({});"\
                         .format(member.mem_id)
                 try:
                     session.connection().engine.execute(query)
                 except:
                     msg += ' Warning: Their current order could not be removed,'\
                            ' (e.g. because it has already been sent to suppliers)'\
                            ' so the member will probably still need to pay.'
             return dict(m=member, msg=msg)
     return dict(m=member, msg='')
コード例 #23
0
 def __call__(self):
     name = self.request.params['name']
     pos_neg = self.request.params['pos_neg']
     mem_sup = self.request.params['mem_sup']
     tt = TransactionType(None, name=name, pos_neg=pos_neg, mem_sup=mem_sup)
     tt.validate()
     session = DBSession()
     existing = session.query(TransactionType)\
                       .filter(TransactionType.name == tt.name).all()
     if len(existing) > 0: 
         return self.redirect('/transaction-types?msg=Transaction type '\
                              ' with name "{}" already exists'\
                              .format(tt.name))
     session.add(tt)
     session.flush()
     return self.redirect('/transaction-types?msg=Transaction type "{}"'\
                          ' has been added to the list.'.format(tt.name))
コード例 #24
0
 def __call__(self):
     session = DBSession()
     tt_id = self.request.matchdict['tt_id']
     tt = get_transaction_type(session, tt_id)
     if not tt.locked:
         session.delete(tt)
         session.flush()
         return self.redirect('/transaction-types?msg='\
                              'Transaction type "{}" has been deleted.'\
                               .format(tt.name))
     else:
         return self.redirect('/transaction-types?msg=Cannot remove'\
                              ' transaction type "{}": transactions'\
                              ' refer to it.'.format(tt.name))
コード例 #25
0
ファイル: transactions.py プロジェクト: vokomokum/vkmkm-erp
 def __call__(self):
     session = DBSession()
     t_id = self.request.matchdict['t_id']
     t = get_transaction(session, t_id)
     if t.locked():
         return self.redir_to_list(t.year, t.month,
                         msg='Cannot remove transaction "{}":'\
                              ' It is locked.'.format(t), show_list=True)
     else:
         session.delete(t)
         session.flush()
         return self.redir_to_list(t.date.year, t.date.month,
                          msg='Transaction "{}" has been deleted.'\
                              .format(t), show_list=True)
コード例 #26
0
ファイル: orders.py プロジェクト: vokomokum/vkmkm-erp
 def is_first_order(self):
     '''
     True if this member is ordering for the first time.
     The modern way would be to check for an Order Charge transaction,
     however, we have to check legacy data from before Nov 2012, as well
     (TODO: remove this after some time, let's say Summer 2014).
     If this is the first order, then there exists only one result in the 
     mem_order table for this member (which is this one).
     Explaining the WHERE clause: We don't care for (past) orders where the 
     amount was <= 0 and we also ignore any order after this one (that 
     start later than this order was completed).
     '''
     query = "SELECT count(*) FROM mem_order WHERE mem_id = {}"\
             " AND (memo_amt > 0 OR mo_vers_groente > 0 OR mo_vers_kaas > 0)"\
             " AND memo_order_open <= '{}';"\
             .format(self.member.mem_id, str(self.order.completed))
     if running_sqlite():  # sqlite can't handle this query
         return False
     return int(list(
         DBSession().connection().engine.execute(query))[0][0]) <= 1
コード例 #27
0
 def __call__(self):
     session = DBSession()
     a_id = self.request.matchdict['a_id']
     applicant = get_applicant(session, a_id)
     # copy over our knowledge of him/her
     member = Member(self.request, applicant.fname, '', applicant.lname)
     now = datetime.now()
     txt = "Joined orientation in {}, became member in {}/{}.".format(\
             applicant.month, now.month, now.year)
     member.mem_adm_comment = "{}\n{}".format(txt, applicant.comment)
     member.mem_email = applicant.email
     member.mem_home_tel = applicant.telnr
     member.mem_household_size = applicant.household_size
     member.validate()
     session.add(member)
     session.delete(applicant)
     session.flush()
     send_pwdreset_request(member, self.request.application_url, first=True)
     return self.redirect("/member/{}?msg=Applicant has been made "\
                         "into a new Member and got an email to set up a "\
                         "password."\
                         .format(member.mem_id))
コード例 #28
0
def fill_shift_from_request(shift, request):
    '''overwrite shift properties from request'''
    if request and shift:
        # overwrite shift properties from request
        for attr in ['task', 'state']:
            if attr in request.params:
                shift.__setattr__(attr, request.params[attr])
        for attr in ['wg_id', 'month', 'year']:
            if attr in request.params:
                shift.__setattr__(attr, int(request.params[attr]))
        if 'mem_id' in request.params:
            mem_id = request.params['mem_id']
            if mem_id == '--':
                shift.mem_id = shift.member = None
            else:
                shift.mem_id = int(mem_id)
                shift.member = DBSession().query(Member).get(mem_id)
                shift.state = 'assigned'
        if 'day' in request.params:
            shift.day = request.params[
                'day']  # brutally using the strings here
    return shift
コード例 #29
0
 def __call__(self):
     fname = self.request.params['fname']
     lname = self.request.params['lname']
     now = datetime.now()
     month = "{}/{}".format(
         str(now.month).rjust(2, '0'),
         str(now.year)[-2:])
     comment = self.request.params['comment']
     email = self.request.params['email']
     telnr = self.request.params['telnr']
     if not self.request.params['household_size'].isdigit():
         raise VokoValidationError(
             "Please enter valid household size (number > 1), not: '%s'" %
             self.request.params['household_size'])
     hsize = int(self.request.params['household_size'])
     applicant = Applicant(None, fname, lname, month, comment, email, telnr,
                           hsize)
     applicant.validate()
     session = DBSession()
     session.add(applicant)
     session.flush()
     return dict(applicants=get_applicants(session),
                 msg="Applicant has been added to the list.")
コード例 #30
0
ファイル: workgroup.py プロジェクト: vokomokum/vkmkm-erp
    def __call__(self):
        session = DBSession()
        wg = get_wg(session, self.request)
        req = self.request

        self.possible_members = get_possible_members(session, wg)
        if 'action' in req.params:
            action = req.params['action']
            if action == "save":
                old_name = wg.name
                uwgs = [w.name for w in self.user.workgroups]
                wg = fill_wg_from_request(wg, req, session)
                if wg.exists and not wg.name == old_name\
                   and not 'Systems' in uwgs:
                    raise Exception('Only members of Systems can change the'\
                                    ' name of an existing workgroup, because'\
                                    ' it changes the email addresses of the'\
                                    ' group.')
                wg.validate()
                if not wg.exists:
                    session.add(wg)
                    session.flush()  # flushing manually so the wg gets an ID
                    return self.redirect('/workgroup/%d?msg='\
                                         'Workgroup was created.' % wg.id)
                return dict(wg=wg, msg='Workgrup has been saved.')

            elif action == 'toggle-active':
                wg = get_wg(session, self.request)
                self.confirm_toggle_active = True
                return dict(wg=wg)
            elif action == 'toggle-active-confirmed':
                wg.active = not wg.active
                msg='Workgroup {} is now {}active.'.\
                    format(wg.name, {False:'in', True:''}[wg.active])
                return dict(wg=wg, msg=msg)

        return dict(wg=wg, msg='')