예제 #1
0
class StatisticsController(BaseController):

  def __init__(self):
    super(StatisticsController, self).__init__()
    self.lmf = LdapModelFactory()

  def __before__(self):
    super(StatisticsController, self).__before__()

    if not self.identity:
      redirect(url(controller='error', action='forbidden'))

  @BaseController.needAdmin
  def index(self):
    c.heading = _('Statistics')

    c.members = len(self.lmf.getUserList())
    activeMembers = self.lmf.getActiveMemberList()
    c.activeMembers = len(activeMembers)
    c.formerMembers = c.members - c.activeMembers

    c.paymentsOk = 0

    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 Exception as e:
        ''' Don't care if there is no payment '''
        print e
        print uid
        pass

      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):
          c.paymentsOk += 1

    c.paymentsNotOk = c.activeMembers - c.paymentsOk

    return render('/statistics/index.mako')
예제 #2
0
class TestLdapModelFactory(unittest.TestCase):
    def setUp(self):
        unittest.TestCase.setUp(self)

        self.username = '******'
        self.password = '******'

        ldap_connector = LdapConnector(username=self.username,
                                       password=self.password)
        self.ldapcon = ldap_connector.get_connection()
        self.ldmf = LdapModelFactory(self.ldapcon)

    def tearDown(self):
        unittest.TestCase.tearDown(self)
        self.ldapcon = None

    ################# User
    def test_getUser(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user, mematool.model.ldapmodel.Member)

    def test_getUserList(self):
        o = self.ldmf.getUserList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getActiveMemberList(self):
        o = self.ldmf.getActiveMemberList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getUserGroupList(self):
        o = self.ldmf.getUserGroupList(self.username)
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getHighestUidNumber(self):
        o = self.ldmf.getHighestUidNumber()
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r'^\d+$')
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    def test_getUidNumberFromUid(self):
        o = self.ldmf.getUidNumberFromUid(self.username)
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r'^\d+$')
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    '''
  def test_prepareVolatileAttribute(self):
    # @todo
    raise NotImplemented()

  def test__updateMember(self):
    # @todo
    raise NotImplemented()

  def test__addMember(self):
    # @todo
    raise NotImplemented()

  def test_deleteUser(self):
    # @todo
    raise NotImplemented()

  def test_changeUserGroup(self):
    # @todo
    raise NotImplemented()

  def test_updateAvatar(self):
    # @todo
    raise NotImplemented()
  '''

    ################# Group

    def test_getGroup(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user.groups, list)
        self.assertGreaterEqual(len(user.groups), 1)

        for g in user.groups:
            group = self.ldmf.getGroup(g)
            self.assertIsInstance(group, mematool.model.dbmodel.Group)

    def test_getGroupList(self):
        o = self.ldmf.getGroupList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getGroupMembers(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user.groups, list)
        self.assertGreaterEqual(len(user.groups), 1)

        for g in user.groups:
            o = self.ldmf.getGroupMembers(g)
            self.assertIsInstance(o, list)
            self.assertGreaterEqual(len(o), 1)

    def test_addDeleteGroup(self):
        # add
        self.assertTrue(self.ldmf.addGroup('test_group'))
        o = self.ldmf.getGroupList()
        self.assertIn('test_group', o)

        # delete
        self.assertTrue(self.ldmf.deleteGroup('test_group'))
        o = self.ldmf.getGroupList()
        self.assertNotIn('test_group', o)

    def test_getHighestGidNumber(self):
        o = self.ldmf.getHighestGidNumber()
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r'^\d+$')
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    ################# Domain

    def test_addDeleteDomain(self):
        res = self.ldmf.addDomain('example.com')
        self.assertTrue(res)

        res = self.ldmf.getDomainList()
        self.assertIn('example.com', res)

        res = self.ldmf.deleteDomain('example.com')
        self.assertTrue(res)

        res = self.ldmf.getDomainList()
        self.assertNotIn('example.com', res)

    def test_getDomain(self):
        res = self.ldmf.addDomain('example.com')
        self.assertTrue(res)

        d = self.ldmf.getDomain('example.com')
        self.assertIsInstance(d, mematool.model.ldapmodel.Domain)

        res = self.ldmf.deleteDomain('example.com')
        self.assertTrue(res)

    def test_getDomainList(self):
        res = self.ldmf.getDomainList()
        self.assertIsInstance(res, list)

    ################# Alias

    def test_getAlias(self):
        res = self.ldmf.addDomain('example.com')

        alias = mematool.model.ldapmodel.Alias()
        alias.dn_mail = '*****@*****.**'
        alias.mail = ['*****@*****.**']
        alias.maildrop = ['*****@*****.**']

        try:
            res = self.ldmf.addAlias(alias)
            self.assertTrue(res)
        except mematool.helpers.exceptions.EntryExists:
            pass

        res = self.ldmf.getAlias('*****@*****.**')
        self.assertIsInstance(res, mematool.model.ldapmodel.Alias)

        res = self.ldmf.deleteAlias('*****@*****.**')
        self.assertTrue(res)

        res = self.ldmf.deleteDomain('example.com')
        self.assertTrue(res)

    def test_getAliasList(self):
        res = self.ldmf.getAliasList('example.com')
        self.assertIsInstance(res, list)

    def test_getMaildropList(self):
        res = self.ldmf.getMaildropList('*****@*****.**')
        self.assertIsInstance(res, dict)

    def test_addDeleteAlias(self):
        res = self.ldmf.addDomain('example.com')
        #self.assertTrue(res)

        alias = mematool.model.ldapmodel.Alias()
        alias.dn_mail = '*****@*****.**'
        alias.mail = ['*****@*****.**']
        alias.maildrop = ['*****@*****.**']

        try:
            res = self.ldmf.addAlias(alias)
            self.assertTrue(res)
        except mematool.helpers.exceptions.EntryExists:
            pass

        res = self.ldmf.deleteAlias('*****@*****.**')
        self.assertTrue(res)

        res = self.ldmf.deleteDomain('example.com')
        self.assertTrue(res)

    '''
예제 #3
0
class TestLdapModelFactory(unittest.TestCase):
    def setUp(self):
        unittest.TestCase.setUp(self)

        self.username = "******"
        self.password = "******"

        ldap_connector = LdapConnector(username=self.username, password=self.password)
        self.ldapcon = ldap_connector.get_connection()
        self.ldmf = LdapModelFactory(self.ldapcon)

    def tearDown(self):
        unittest.TestCase.tearDown(self)
        self.ldapcon = None

    ################# User
    def test_getUser(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user, mematool.model.ldapmodel.Member)

    def test_getUserList(self):
        o = self.ldmf.getUserList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getActiveMemberList(self):
        o = self.ldmf.getActiveMemberList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getUserGroupList(self):
        o = self.ldmf.getUserGroupList(self.username)
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getHighestUidNumber(self):
        o = self.ldmf.getHighestUidNumber()
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r"^\d+$")
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    def test_getUidNumberFromUid(self):
        o = self.ldmf.getUidNumberFromUid(self.username)
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r"^\d+$")
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    """
  def test_prepareVolatileAttribute(self):
    # @todo
    raise NotImplemented()

  def test__updateMember(self):
    # @todo
    raise NotImplemented()

  def test__addMember(self):
    # @todo
    raise NotImplemented()

  def test_deleteUser(self):
    # @todo
    raise NotImplemented()

  def test_changeUserGroup(self):
    # @todo
    raise NotImplemented()

  def test_updateAvatar(self):
    # @todo
    raise NotImplemented()
  """

    ################# Group

    def test_getGroup(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user.groups, list)
        self.assertGreaterEqual(len(user.groups), 1)

        for g in user.groups:
            group = self.ldmf.getGroup(g)
            self.assertIsInstance(group, mematool.model.dbmodel.Group)

    def test_getGroupList(self):
        o = self.ldmf.getGroupList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getGroupMembers(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user.groups, list)
        self.assertGreaterEqual(len(user.groups), 1)

        for g in user.groups:
            o = self.ldmf.getGroupMembers(g)
            self.assertIsInstance(o, list)
            self.assertGreaterEqual(len(o), 1)

    def test_addDeleteGroup(self):
        # add
        self.assertTrue(self.ldmf.addGroup("test_group"))
        o = self.ldmf.getGroupList()
        self.assertIn("test_group", o)

        # delete
        self.assertTrue(self.ldmf.deleteGroup("test_group"))
        o = self.ldmf.getGroupList()
        self.assertNotIn("test_group", o)

    def test_getHighestGidNumber(self):
        o = self.ldmf.getHighestGidNumber()
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r"^\d+$")
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    ################# Domain

    def test_addDeleteDomain(self):
        res = self.ldmf.addDomain("example.com")
        self.assertTrue(res)

        res = self.ldmf.getDomainList()
        self.assertIn("example.com", res)

        res = self.ldmf.deleteDomain("example.com")
        self.assertTrue(res)

        res = self.ldmf.getDomainList()
        self.assertNotIn("example.com", res)

    def test_getDomain(self):
        res = self.ldmf.addDomain("example.com")
        self.assertTrue(res)

        d = self.ldmf.getDomain("example.com")
        self.assertIsInstance(d, mematool.model.ldapmodel.Domain)

        res = self.ldmf.deleteDomain("example.com")
        self.assertTrue(res)

    def test_getDomainList(self):
        res = self.ldmf.getDomainList()
        self.assertIsInstance(res, list)

    ################# Alias

    def test_getAlias(self):
        res = self.ldmf.addDomain("example.com")

        alias = mematool.model.ldapmodel.Alias()
        alias.dn_mail = "*****@*****.**"
        alias.mail = ["*****@*****.**"]
        alias.maildrop = ["*****@*****.**"]

        try:
            res = self.ldmf.addAlias(alias)
            self.assertTrue(res)
        except mematool.helpers.exceptions.EntryExists:
            pass

        res = self.ldmf.getAlias("*****@*****.**")
        self.assertIsInstance(res, mematool.model.ldapmodel.Alias)

        res = self.ldmf.deleteAlias("*****@*****.**")
        self.assertTrue(res)

        res = self.ldmf.deleteDomain("example.com")
        self.assertTrue(res)

    def test_getAliasList(self):
        res = self.ldmf.getAliasList("example.com")
        self.assertIsInstance(res, list)

    def test_getMaildropList(self):
        res = self.ldmf.getMaildropList("*****@*****.**")
        self.assertIsInstance(res, dict)

    def test_addDeleteAlias(self):
        res = self.ldmf.addDomain("example.com")
        # self.assertTrue(res)

        alias = mematool.model.ldapmodel.Alias()
        alias.dn_mail = "*****@*****.**"
        alias.mail = ["*****@*****.**"]
        alias.maildrop = ["*****@*****.**"]

        try:
            res = self.ldmf.addAlias(alias)
            self.assertTrue(res)
        except mematool.helpers.exceptions.EntryExists:
            pass

        res = self.ldmf.deleteAlias("*****@*****.**")
        self.assertTrue(res)

        res = self.ldmf.deleteDomain("example.com")
        self.assertTrue(res)

    """
예제 #4
0
파일: payments.py 프로젝트: ot4me/mematool
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