def setUp(self):
        '''
        set up test fixtures
        '''
        self.ledger = OcLedger()

        # set up regular user
        self.userReg = OcUser().setup_user(
            username='******',
            email='*****@*****.**',
        )

        # set up user with a npf affiliation
        self.userOrg = OcUser().setup_user(
            username='******',
            email='*****@*****.**',
        )

        # set up user with a biz affiliation
        self.userBiz = OcUser().setup_user(
            username='******',
            email='*****@*****.**',
        )

        # set up test org
        self.orgTest = OcOrg().setup_org(name='test_org_123', status='npf')

        self.projectUserRegMT = Project(org=self.orgTest, name='MT by userReg')
        self.projectUserRegMT.save()

        self.eventUserRegMT = Event(
            project=self.projectUserRegMT,
            description='MT by userReg',
            location='test',
            coordinator=self.userOrg,
            creator_id=self.userOrg.id,
            event_type='MN',
            datetime_start=datetime.now(tz=pytz.utc) - timedelta(hours=2),
            datetime_end=datetime.now(tz=pytz.utc) - timedelta(hours=1))
        self.eventUserRegMT.save()

        self.userRegTimeLog = UserTimeLog(
            user=self.userReg,
            event=self.eventUserRegMT,
            is_verified=True,
            datetime_start=datetime.now(tz=pytz.utc),
            datetime_end=datetime.now(tz=pytz.utc) + timedelta(hours=1))
        self.userRegTimeLog.save()

        self.actionUserReg = AdminActionUserTime(
            user=self.userOrg,
            usertimelog=self.userRegTimeLog,
            action_type='app')
        self.actionUserReg.save()

        # issue currents to userReg
        self.ledger.issue_currents(self.orgTest.orgentity.id,
                                   self.userReg.userentity.id,
                                   self.actionUserReg, 1)
Beispiel #2
0
    def get_top_issued_npfs(self, period, quantity=10, active=False):
        result = list()
        orgs = Org.objects.filter(status='npf')

        for org in orgs:
            issued_cur_amount = OcLedger().get_issued_cur_amount(
                org.id, period)['total']
            if not issued_cur_amount:
                issued_cur_amount = 0

            has_approved_admins = False
            try:
                has_approved_admins = OcOrg(org.id).get_admins().exists()
            except InvalidOrgException:
                pass

            if not active or (active and has_approved_admins
                              and issued_cur_amount > 0):
                result.append({'name': org.name, 'total': issued_cur_amount})

        result.sort(key=lambda org_dict: org_dict['total'], reverse=True)

        if isinstance(quantity, int):
            result = result[:quantity]

        return result
Beispiel #3
0
    def get_balance_available(self, currency='cur'):
        '''
        report total available currents
        '''
        balance = OcLedger().get_balance(entity_id=self.org.orgentity.id,
                                         entity_type='org',
                                         currency=currency)

        return balance
Beispiel #4
0
    def get_balance_available_usd(self):
        '''
        available usd balance is composed of:
            - transactions in ledger
        '''
        balance_usd = OcLedger().get_balance(entity_id=self.user.userentity.id,
                                             entity_type='user',
                                             currency='usd')

        return round(balance_usd, 2)
def setup_redemptions(users, orgs):
    biz_orgs = [org for org in orgs if org.status == 'biz']

    transactions = Transaction.objects.filter(user__in=users)
    if len(transactions) >= 20:
        print 'Sufficient number of redemptions already'
        return

    for i in xrange(20):
        org = _get_random_item(biz_orgs)
        orgs_offers = Offer.objects.filter(org=org)
        users = [
            user for user in users
            if OcUser(user.id).get_balance_available() > 0
        ]

        if not users:
            print 'No users with currents available!'
            return

        user = _get_random_item(users)
        user_balance = OcUser(user.id).get_balance_available()
        amount_spent_cur = round(random.random() * float(user_balance), 3)

        offer = _get_random_item(orgs_offers)
        price_reported = round(1000. / offer.currents_share * amount_spent_cur,
                               2)

        transaction = Transaction.objects.create(
            user=user,
            offer=offer,
            pop_no_proof=_get_random_string(),
            pop_type='oth',
            price_reported=price_reported,
            currents_amount=amount_spent_cur)

        action = random.choice(['req', 'app', 'red', 'dec'])
        transaction_action = TransactionAction.objects.create(
            transaction=transaction, action_type=action)
        print str(transaction_action)

        is_verified = (action in ['app', 'red'])
        if is_verified:
            OcLedger().transact_currents(entity_type_from='user',
                                         entity_id_from=user.userentity.id,
                                         entity_type_to='org',
                                         entity_id_to=org.orgentity.id,
                                         action=transaction_action,
                                         amount=amount_spent_cur)
def setup_volunteer_requests(users, orgs):
    npf_orgs = [org for org in orgs if org.status == 'npf']
    usertimelogs = UserTimeLog.objects.filter(user__in=users,
                                              event__event_type='MN')
    if len(usertimelogs) >= 30:
        print 'Sufficient number of existing hour requests already'
        return

    for i in xrange(30):
        user = _get_random_item(users)
        org = random.choice(npf_orgs)
        action = random.choice(['req', 'app', 'dec'])
        is_verified = action == 'app'

        project, created = Project.objects.get_or_create(org=org,
                                                         name='ManualTracking')

        datetime_start = datetime.now(tz=pytz.utc) - \
            timedelta(days=random.randint(7)) + \
            timedelta(hours=random.randint(24)) + \
            timedelta(minutes=random.randint(4) * 15)
        datetime_end = datetime_start + \
            timedelta(minutes=random.randint(1,16) * 15)

        event = Event.objects.create(project=project,
                                     description=_get_random_string(),
                                     event_type='MN',
                                     datetime_start=datetime_start,
                                     datetime_end=datetime_end)

        usertimelog = UserTimeLog.objects.create(user=user,
                                                 event=event,
                                                 datetime_start=datetime_start,
                                                 datetime_end=datetime_end,
                                                 is_verified=is_verified)

        admin = _get_random_item(
            User.objects.filter(last_name=org.name + 'Admin'))
        actiontimelog = AdminActionUserTime.objects.create(
            user=admin, usertimelog=usertimelog, action_type=action)
        amount = diffInHours(datetime_start, datetime_end)
        print str(actiontimelog)

        if is_verified:
            OcLedger().issue_currents(entity_id_from=org.orgentity.id,
                                      entity_id_to=user.userentity.id,
                                      action=actiontimelog,
                                      amount=amount)
Beispiel #7
0
    def get_balance_available(self):
        '''
        report total available currents
            - balance based on ledger
            - minus redeemed offers
        '''
        if not self.userid:
            raise InvalidUserException()

        current_balance = OcLedger().get_balance(
            entity_id=self.user.userentity.id, entity_type='user')

        # offer redemption requests
        transactions = self._get_transactions_annotated()
        actions = self._get_actions_for_annotated_transactions(
            transactions, 'req')
        total_req_redemptions = common._get_redemption_total(actions)

        return round(current_balance - total_req_redemptions, 3)
Beispiel #8
0
    def get_top_received_users(self, period, quantity=10):
        result = list()
        users = User.objects.filter(userentity__isnull=False)

        for user in users:
            earned_cur_amount = OcLedger().get_earned_cur_amount(
                user.id, period)['total']

            # only include active volunteers
            if earned_cur_amount > 0 and user.has_usable_password():
                if user.first_name and user.last_name:
                    name = ' '.join([user.first_name, user.last_name])
                else:
                    name = user.username

                result.append({'name': name, 'total': earned_cur_amount})

        result.sort(key=lambda user_dict: user_dict['total'], reverse=True)
        return result[:quantity]
Beispiel #9
0
    def get_top_bizs(self, period, quantity=10, accepted_only=True):
        result = list()
        bizs = Org.objects.filter(Q(status='biz') | Q(name='openCurrents'))

        for biz in bizs:
            total_cur_amount = 0

            if not accepted_only:
                # pending currents
                try:
                    biz_org = OcOrg(biz.id)
                except InvalidOrgException:
                    logger.warning(
                        'can\'t instantiate org interface for biz org %s',
                        biz.name)
                    continue

                biz_admins = biz_org.get_admins()
                if biz_admins:
                    biz_admin = biz_admins.first()
                    total_cur_amount = BizAdmin(
                        biz_admin.id).get_balance_pending()

            # accepted currents
            accepted_cur_amount = OcLedger().get_accepted_cur_amount(
                biz.id, period)['total']
            if not accepted_cur_amount:
                accepted_cur_amount = 0

            total_cur_amount += accepted_cur_amount
            result.append({'name': biz.name, 'total': total_cur_amount})

        result.sort(key=lambda biz_dict: biz_dict['total'], reverse=True)

        if isinstance(quantity, int):
            result = result[:quantity]

        return result
def setup_events(users, orgs):
    npf_orgs = [org for org in orgs if org.status == 'npf']
    names = random.choice(list(string.letters), 10, replace=False)

    projects = Project.objects.filter(org__in=npf_orgs)

    if len(projects) >= 10:
        print 'Sufficient number of projects created already'
        return

    for name in names:
        org = _get_random_item(npf_orgs)
        project, created = Project.objects.get_or_create(name=' '.join(
            ['Let\'s', name]),
                                                         org=org)

        datetime_start = datetime.now(tz=pytz.utc) + \
            _get_random_item([-1, 1]) * timedelta(days=random.randint(60)) + \
            timedelta(hours=random.randint(12, 24))
        datetime_end = datetime_start + timedelta(hours=random.randint(4))
        num_locations = random.randint(3)

        for loc in xrange(num_locations):
            admin = _get_random_item(
                User.objects.filter(last_name=org.name + 'Admin'))
            event = Event.objects.create(project=project,
                                         description=_get_random_string(),
                                         location='Location' + str(loc),
                                         coordinator=admin,
                                         is_public=True,
                                         datetime_start=datetime_start,
                                         datetime_end=datetime_end)
            print str(event)

            # register for event
            users_reg = random.choice(users,
                                      random.randint(1, len(users)),
                                      replace=False)
            for user in users_reg:
                try:
                    uer = UserEventRegistration.objects.create(
                        user=user, event=event, is_confirmed=True)
                    print str(uer)
                except Exception as e:
                    print e.message
                    pass

            # checkin at random time
            users_checkin = random.choice(users_reg,
                                          random.randint(len(users_reg)),
                                          replace=False)
            event_duration = datetime_end - datetime_start

            for user_chk in users_checkin:
                try:
                    utl = UserTimeLog.objects.create(
                        user=user_chk,
                        event=event,
                        is_verified=True,
                        datetime_start=datetime_start +
                        _get_random_item([-1, 0, 1]) * random.randint(4) *
                        event_duration)

                    # randomly checkout
                    if random.randint(2):
                        utl.datetime_end = datetime_start + timedelta(
                            hours=random.randint(12))
                        utl.save()
                    print str(utl)

                    actiontimelog = AdminActionUserTime.objects.create(
                        user=admin, usertimelog=utl, action_type='app')

                    OcLedger().issue_currents(
                        entity_id_from=org.orgentity.id,
                        entity_id_to=user_chk.userentity.id,
                        action=actiontimelog,
                        amount=diffInHours(datetime_start, datetime_end))

                except Exception as e:
                    print e.message
                    pass
Beispiel #11
0
    def test_logged_hours_accept(self):

        self.assertEqual(self.response.status_code, 200)

        org_admin_response = self.client.get('/org-admin/')
        self.assertEqual(org_admin_response.status_code, 200)

        # checking pending hours before approving
        self.assertDictEqual(
            org_admin_response.context['hours_pending_by_admin'],
            {self.npf_admin_1: 5.0})

        # checking total approved hours
        self.assertEqual(org_admin_response.context['issued_by_all'], 0)

        # checking initial balance
        self.assertEqual(0, len(self.oc_vol_1.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_1))
        self.assertEqual(0, len(self.oc_vol_2.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_2))

        # approving hours
        self.response = self.client.post('/approve-hours/', {
            'post-data':
            self.volunteer_2.username + ':1:' + self.monday_prev
        })

        # return to org-amdin after approving
        self.assertRedirects(self.response,
                             '/approve-hours/1/0/',
                             status_code=302)

        # checking ledger records
        ledger_query = Ledger.objects.all()
        self.assertEqual(1, len(ledger_query))
        # asserting the first user
        self.assertEqual(
            0,
            len(ledger_query.filter(
                action__usertimelog__user=self.volunteer_1)))

        # asserting the 2nd user
        self.assertEqual(
            1,
            len(ledger_query.filter(
                action__usertimelog__user=self.volunteer_2)))
        self.assertEqual(
            'cur',
            ledger_query.get(
                action__usertimelog__user=self.volunteer_2).currency)
        self.assertEqual(
            2,
            ledger_query.get(
                action__usertimelog__user=self.volunteer_2).amount)
        self.assertEqual(
            True,
            ledger_query.get(
                action__usertimelog__user=self.volunteer_2).is_issued)

        self.assertEqual(1, len(self.oc_vol_2.get_hours_approved()))
        self.assertEqual(2, OcLedger().get_balance(self.user_enitity_id_vol_2))

        # checking that the the last week submitted hours are displayed
        org_admin_response_approve_second_week = self.client.get(
            '/approve-hours/2/0/')
        context_hr_last_week = org_admin_response_approve_second_week.context[
            0]['week'][0]
        for k in context_hr_last_week:
            self.assertEqual(1, len(context_hr_last_week[k]))

            self.assertEqual(
                3, len(context_hr_last_week[k][self.volunteer_1.email]))
            self.assertEqual(
                3.0, context_hr_last_week[k][self.volunteer_1.email]['Total'])
            self.assertEqual(
                self.volunteer_1_full_name,
                context_hr_last_week[k][self.volunteer_1.email]['name'])

        # approving hours for the last week
        response_post_last_week = self.client.post('/approve-hours/', {
            'post-data':
            self.volunteer_1.username + ':1:' + self.monday_last
        })

        # return to org-amdin after approving
        self.assertRedirects(response_post_last_week,
                             '/org-admin/1/0/',
                             status_code=302)

        # checking ledger records
        ledger_query = Ledger.objects.all()
        self.assertEqual(2, len(ledger_query))
        # asserting the first user
        self.assertEqual(
            1,
            len(ledger_query.filter(
                action__usertimelog__user=self.volunteer_1)))
        self.assertEqual(
            'cur',
            ledger_query.get(
                action__usertimelog__user=self.volunteer_1).currency)
        self.assertEqual(
            3,
            ledger_query.get(
                action__usertimelog__user=self.volunteer_1).amount)
        self.assertEqual(
            True,
            ledger_query.get(
                action__usertimelog__user=self.volunteer_1).is_issued)

        self.assertEqual(1, len(self.oc_vol_2.get_hours_approved()))
        self.assertEqual(3, OcLedger().get_balance(self.user_enitity_id_vol_1))

        # asserting the 2nd user
        self.assertEqual(
            1,
            len(ledger_query.filter(
                action__usertimelog__user=self.volunteer_2)))
        self.assertEqual(
            'cur',
            ledger_query.get(
                action__usertimelog__user=self.volunteer_2).currency)
        self.assertEqual(
            2,
            ledger_query.get(
                action__usertimelog__user=self.volunteer_2).amount)
        self.assertEqual(
            True,
            ledger_query.get(
                action__usertimelog__user=self.volunteer_2).is_issued)

        self.assertEqual(1, len(self.oc_vol_2.get_hours_approved()))
        self.assertEqual(2, OcLedger().get_balance(self.user_enitity_id_vol_2))
Beispiel #12
0
    def setUp(self):
        self.test_curr_per_tr = 12

        # dates
        future_date = timezone.now() + timedelta(days=1)
        past_date = timezone.now() - timedelta(days=2)

        # creating orgs
        org1 = _create_org("NPF_org_1", "npf")
        org2 = _create_org("NPF_org_2", "npf")

        # creating a volunteer
        volunteer_1 = _create_test_user('volunteer_1')
        vol_1_entity = UserEntity.objects.get(user=volunteer_1)
        volunteer_2 = _create_test_user('volunteer_2')

        # creting bizorg and its admin
        biz_org = OcOrg().setup_org(name="BIZ_org_1", status='biz')
        biz_admin_1 = _create_test_user('biz_admin_1',
                                        org=biz_org,
                                        is_org_admin=True)

        biz_org_oc = _create_org("openCurrents", "biz")

        # creating an admins for NPF_orgs
        npf_admin_1 = _create_test_user('npf_admin_1',
                                        org=org1,
                                        is_org_admin=True)
        npf_admin_2 = _create_test_user('npf_admin_2',
                                        org=org2,
                                        is_org_admin=True)

        # creating 2 projects for 2 npf orgs
        project_1 = _create_project(org1, 'org1_project_1')
        project_2 = _create_project(org2, 'org2_project_1')

        # 1st event time = 3 hours
        datetime_start_1 = past_date
        datetime_end_1 = past_date + timedelta(hours=3)
        # 2nd event time = 2 hours
        datetime_start_2 = past_date + timedelta(hours=3)
        datetime_end_2 = past_date + timedelta(hours=5)

        # setting two approved events for different NPF orgs in the past
        # approved 3 hrs for org1
        _setup_volunteer_hours(volunteer_1,
                               npf_admin_1,
                               org1,
                               project_1,
                               datetime_start_1,
                               datetime_end_1,
                               is_verified=True,
                               action_type='app')

        # approved 2 hrs for org2
        _setup_volunteer_hours(volunteer_1,
                               npf_admin_2,
                               org2,
                               project_2,
                               datetime_start_2,
                               datetime_end_2,
                               is_verified=True,
                               action_type='app')

        # setting a pending past events 3 hrs
        _setup_volunteer_hours(volunteer_1, npf_admin_1, org1, project_1,
                               datetime_start_1, datetime_end_1)

        # setting up two future events 5 hrs each
        self.event1 = _create_event(project_1,
                                    npf_admin_1.id,
                                    future_date,
                                    future_date + timedelta(hours=5),
                                    is_public=True)
        self.event2 = _create_event(project_1,
                                    npf_admin_1.id,
                                    future_date,
                                    future_date + timedelta(hours=5),
                                    description="Test Event 2",
                                    is_public=True)

        # issuing currents to volunteer1
        OcLedger().issue_currents(
            entity_id_from=org1.orgentity.id,
            entity_id_to=vol_1_entity.id,
            action=None,
            amount=40,
        )

        # registering user for an event
        _setup_user_event_registration(volunteer_1, self.event2)

        # setting up user dollars "Dollars available"
        _setup_ledger_entry(org1.orgentity,
                            vol_1_entity,
                            currency='usd',
                            amount=30.30,
                            is_issued=True)

        # setting approved and pending dollars
        _setup_transactions(biz_org, volunteer_1, self.test_curr_per_tr, 20)
        _setup_transactions(biz_org,
                            volunteer_1,
                            self.test_curr_per_tr,
                            20,
                            action_type='app')
        _setup_transactions(biz_org,
                            volunteer_1,
                            self.test_curr_per_tr,
                            20,
                            action_type='red')

        # create master offer
        _create_offer(biz_org, currents_share=_SHARE * 100, is_master=True)

        # setting up client
        self.client = Client()
Beispiel #13
0
from openCurrents.interfaces.ocuser import OcUser
from openCurrents.interfaces.ledger import OcLedger
from openCurrents.models import UserSettings
from django.contrib.auth.models import User

from csv import writer
from datetime import datetime, timedelta
from pytz import utc

users = User.objects.filter(is_staff=False)
ocledger = OcLedger()
data = {}

for user in users:
    try:
        us = user.usersettings
    except UserSettings.DoesNotExist:
        continue

    ocuser = OcUser(user.id)
    redemptions = ocuser.get_offers_redeemed()
    redemptions_req = filter(lambda x: x.action_type == 'req', redemptions)
    redemptions_app = filter(lambda x: x.action_type == 'app', redemptions)

    hours_req = ocuser.get_hours_requested()
    hours_app = ocuser.get_hours_approved()

    print user.id
    data[user.id] = {
        'email':
        user.email,
class TestOcLedger(TestCase):
    def setUp(self):
        '''
        set up test fixtures
        '''
        self.ledger = OcLedger()

        # set up regular user
        self.userReg = OcUser().setup_user(
            username='******',
            email='*****@*****.**',
        )

        # set up user with a npf affiliation
        self.userOrg = OcUser().setup_user(
            username='******',
            email='*****@*****.**',
        )

        # set up user with a biz affiliation
        self.userBiz = OcUser().setup_user(
            username='******',
            email='*****@*****.**',
        )

        # set up test org
        self.orgTest = OcOrg().setup_org(name='test_org_123', status='npf')

        self.projectUserRegMT = Project(org=self.orgTest, name='MT by userReg')
        self.projectUserRegMT.save()

        self.eventUserRegMT = Event(
            project=self.projectUserRegMT,
            description='MT by userReg',
            location='test',
            coordinator=self.userOrg,
            creator_id=self.userOrg.id,
            event_type='MN',
            datetime_start=datetime.now(tz=pytz.utc) - timedelta(hours=2),
            datetime_end=datetime.now(tz=pytz.utc) - timedelta(hours=1))
        self.eventUserRegMT.save()

        self.userRegTimeLog = UserTimeLog(
            user=self.userReg,
            event=self.eventUserRegMT,
            is_verified=True,
            datetime_start=datetime.now(tz=pytz.utc),
            datetime_end=datetime.now(tz=pytz.utc) + timedelta(hours=1))
        self.userRegTimeLog.save()

        self.actionUserReg = AdminActionUserTime(
            user=self.userOrg,
            usertimelog=self.userRegTimeLog,
            action_type='app')
        self.actionUserReg.save()

        # issue currents to userReg
        self.ledger.issue_currents(self.orgTest.orgentity.id,
                                   self.userReg.userentity.id,
                                   self.actionUserReg, 1)

    def tearDown(self):
        '''
        clean up test fixtures
        '''
        self.userReg.delete()
        self.userOrg.delete()
        self.userBiz.delete()
        self.orgTest.delete()
        Ledger.objects.filter(entity_from__id__in=[
            self.userReg.userentity.id, self.userOrg.userentity.id,
            self.userBiz.userentity.id, self.orgTest.orgentity.id
        ]).delete()

    def test_initial_balance(self):
        '''
        test initial balances correct after set up
        '''
        self.assertEqual(self.ledger.get_balance(self.userReg.userentity.id),
                         1)
        self.assertEqual(self.ledger.get_balance(self.userOrg.userentity.id),
                         0)

        # issued currents not counted towards balances
        self.assertEqual(
            self.ledger.get_balance(self.orgTest.orgentity.id, 'org'), 0)

    def test_transact_user_user(self):
        '''
        transact from one user to another and check balances
        '''
        self.ledger.transact_currents(
            entity_type_from='user',
            entity_id_from=self.userReg.userentity.id,
            entity_type_to='user',
            entity_id_to=self.userBiz.userentity.id,
            action=self.actionUserReg,
            amount=1,
        )
        self.assertEqual(self.ledger.get_balance(self.userReg.userentity.id),
                         0)
        self.assertEqual(self.ledger.get_balance(self.userBiz.userentity.id),
                         1)

    def test_insufficient_funds(self):
        '''
        check appropriate exception raised when sender has insufficient funds
        '''
        def _insufficient_funds_transaction():
            self.ledger.transact_currents(
                entity_type_from='user',
                entity_id_from=self.userReg.userentity.id,
                entity_type_to='user',
                entity_id_to=self.userOrg.userentity.id,
                action=self.actionUserReg,
                amount=100)

        self.assertRaises(InsufficientFundsException,
                          _insufficient_funds_transaction)
Beispiel #15
0
    def test_logged_hours_decline(self):
        self.assertEqual(self.response.status_code, 200)

        org_admin_response = self.client.get('/org-admin/')
        self.assertEqual(org_admin_response.status_code, 200)

        # checking pending hours before declining
        self.assertDictEqual(
            org_admin_response.context['hours_pending_by_admin'],
            {self.npf_admin_1: 5.0})

        # checking total approved hours
        self.assertEqual(org_admin_response.context['issued_by_all'], 0)

        # checking initial balance
        self.assertEqual(0, len(self.oc_vol_1.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_1))
        self.assertEqual(0, len(self.oc_vol_2.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_2))

        # declining hrs for the previous week
        post_decline_hours = self.client.post('/approve-hours/', {
            'post-data':
            self.volunteer_2.username + ':0:' + self.monday_prev
        })

        # return to org-amdin after declining
        self.assertRedirects(post_decline_hours,
                             '/approve-hours/0/1/',
                             status_code=302)

        # checking hours after declining
        # checking ledger records
        ledger_query = Ledger.objects.all()
        self.assertEqual(0, len(ledger_query))
        # asserting the first user
        self.assertEqual(
            0,
            len(ledger_query.filter(
                action__usertimelog__user=self.volunteer_1)))

        # asserting the 2nd user
        self.assertEqual(
            0,
            len(ledger_query.filter(
                action__usertimelog__user=self.volunteer_2)))

        self.assertEqual(0, len(self.oc_vol_2.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_2))

        # declining for the last week
        post_decline_hours_last = self.client.post('/approve-hours/0/1/', {
            'post-data':
            self.volunteer_1.username + ':0:' + self.monday_last
        })

        # return to org-amdin after declining
        self.assertRedirects(post_decline_hours_last,
                             '/org-admin/0/1/',
                             status_code=302)

        # checking hours after declining
        # checking ledger records
        ledger_query = Ledger.objects.all()
        self.assertEqual(0, len(ledger_query))
        # asserting the first user
        self.assertEqual(
            0,
            len(ledger_query.filter(
                action__usertimelog__user=self.volunteer_1)))

        # asserting the 2nd user
        self.assertEqual(
            0,
            len(ledger_query.filter(
                action__usertimelog__user=self.volunteer_2)))

        self.assertEqual(0, len(self.oc_vol_1.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_1))
        self.assertEqual(0, len(self.oc_vol_2.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_2))
Beispiel #16
0
    def setUp(self):
        # dates
        future_date = timezone.now() + timedelta(days=1)
        past_date = timezone.now() - timedelta(days=2)

        # creating orgs
        self.org1 = _create_org("NPF_org_1", "npf")
        self.org2 = _create_org("NPF_org_2", "npf")
        self.biz_org = _create_org("BIZ_org_1", 'biz')

        # creating 2 projects for 2 npf orgs
        self.project_1 = _create_project(self.org1, 'org1_project_1')
        self.project_2 = _create_project(self.org2, 'org2_project_1')

        # creating volunteers
        self.volunteer_1 = _create_test_user('volunteer_1')
        self.vol_1_entity = UserEntity.objects.get(user=self.volunteer_1)

        self.volunteer_2 = _create_test_user('volunteer_2')
        self.vol_2_entity = UserEntity.objects.get(user=self.volunteer_2)

        # creating admins
        self.npf_admin_1 = _create_test_user('npf_admin_1',
                                             org=self.org1,
                                             is_org_admin=True)
        self.npf_adm_1_entity = UserEntity.objects.get(user=self.npf_admin_1)

        self.npf_admin_2 = _create_test_user('npf_admin_2',
                                             org=self.org2,
                                             is_org_admin=True)
        self.npf_adm_2_entity = UserEntity.objects.get(user=self.npf_admin_2)

        self.biz_admin_1 = _create_test_user('biz_admin_1',
                                             org=self.biz_org,
                                             is_org_admin=True)
        # self.biz_adm_1_entity = UserEntity.objects.get(user=self.biz_admin_1)

        # 1st event time = 3 hours
        self.datetime_start_1 = past_date
        self.datetime_end_1 = past_date + timedelta(hours=3)

        # setting 1 pending events - should create 3 pending currents
        _setup_volunteer_hours(self.volunteer_1, self.npf_admin_1, self.org1,
                               self.project_1, self.datetime_start_1,
                               self.datetime_end_1)

        # setting 1 approved events - should create 3 available currents
        _setup_volunteer_hours(self.volunteer_1,
                               self.npf_admin_1,
                               self.org1,
                               self.project_1,
                               self.datetime_start_1,
                               self.datetime_end_1,
                               is_verified=True,
                               action_type='app')

        # issuing currents from npf org to vol1 - should create 20 available
        # currents in total
        OcLedger().issue_currents(
            entity_id_from=self.org1.orgentity.id,
            entity_id_to=self.vol_1_entity.id,
            action=None,
            amount=20,
        )

        # transacting 4 currents from volunteer to biz org - should create 16
        # available currents in total (20 - 4)
        OcLedger().transact_currents(
            entity_type_from=self.vol_1_entity.entity_type,
            entity_id_from=self.vol_1_entity.id,
            entity_type_to=self.biz_org.orgentity.entity_type,
            entity_id_to=self.biz_org.orgentity.id,
            action=None,
            amount=4)

        # setting up pending transaction
        _setup_transactions(self.biz_org, self.biz_admin_1, 0.436, 10.91)

        # create master offer
        _create_offer(self.biz_org,
                      currents_share=_SHARE * 100,
                      is_master=True)

        # setting up client
        self.client = Client()
Beispiel #17
0
    def test_logged_hours_declined(self):
        self.assertEqual(self.response.status_code, 200)

        org_admin_response = self.client.get('/org-admin/')
        self.assertEqual(org_admin_response.status_code, 200)

        # checking pending hours before declining
        self.assertDictEqual(
            org_admin_response.context['hours_pending_by_admin'],
            {self.npf_admin_1: 5.0})

        # checking total approved hours
        self.assertEqual(org_admin_response.context['issued_by_all'], 0)

        # checking initial balance
        self.assertEqual(0, len(self.oc_vol_1.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_1))
        self.assertEqual(0, len(self.oc_vol_2.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_2))

        self.response = self.client.post(
            '/approve-hours/', {
                'post-data':
                self.volunteer_1.username + ':0:' + self.monday + ',' +
                self.volunteer_2.username + ':0:' + self.monday
            })

        # return to org-amdin after declining
        self.assertRedirects(self.response, '/org-admin/0/2/', status_code=302)

        # assert the creation of the corresponding usertimelog and adminaction records
        self.assertEqual(
            0, len(AdminActionUserTime.objects.filter(action_type='app')))
        self.assertEqual(
            0, len(AdminActionUserTime.objects.filter(action_type='app')))
        self.assertEqual(
            2, len(AdminActionUserTime.objects.filter(action_type='dec')))

        self.assertEqual(
            1,
            len(
                UserTimeLog.objects.filter(user=self.volunteer_1).filter(
                    is_verified=False)))
        self.assertEqual(
            1,
            len(
                AdminActionUserTime.objects.filter(
                    usertimelog__user=self.volunteer_1).filter(
                        action_type='dec')))
        self.assertEqual(
            1,
            len(
                UserTimeLog.objects.filter(user=self.volunteer_2).filter(
                    is_verified=False)))
        self.assertEqual(
            1,
            len(
                AdminActionUserTime.objects.filter(
                    usertimelog__user=self.volunteer_2).filter(
                        action_type='dec')))

        # checking ledger records
        ledger_query = Ledger.objects.all()
        self.assertEqual(0, len(ledger_query))
        # asserting the first user
        self.assertEqual(
            0,
            len(ledger_query.filter(
                action__usertimelog__user=self.volunteer_1)))
        self.assertEqual(0, len(self.oc_vol_1.get_hours_approved()))

        self.assertEqual(0, len(self.oc_vol_1.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_1))

        # asserting the 2nd user
        self.assertEqual(
            0,
            len(ledger_query.filter(
                action__usertimelog__user=self.volunteer_2)))
        self.assertEqual(0, len(self.oc_vol_2.get_hours_approved()))

        self.assertEqual(0, len(self.oc_vol_2.get_hours_approved()))
        self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_1))