Exemple #1
0
	def test_against_cascade_deletion_of_purchaseditem(self):
		"""Test that purchased items are not removed when related merchandise
		is

		"""
		account = Account(name="tset")
		account.deposit(500) # Depost issues the save routine
		operator = None

		m1 = Merchandise(name="m1", internal_price=3, ordinary_price=4)
		m1.save()
		m2 = Merchandise(name="m2", internal_price=2, ordinary_price=4)
		m2.save()

		# Test a basic purchase:
		trans = buy_merchandise(account, [m1], operator)

		# Test that transactions are not deleted when related merchandise is,
		# and that backup information is stored to merchandise_tags and
		# merchandise_name:
		pm1_id = PurchasedItem.objects.get(transaction=trans).id
		merchandise_name = m1.name[:30]
		merchandise_tags = "|".join((unicode(t) for t in m1.tags.all()))[:30]
		m1.delete()
		pm1 = PurchasedItem.objects.get(id=pm1_id)
		self.failUnlessEqual(pm1.merchandise_name, merchandise_name)
		self.failUnlessEqual(pm1.merchandise_tags, merchandise_tags)
Exemple #2
0
	def test_ordinary_purchase(self):
		"""Test basic purchases (ordinary price)

		"""
		account = Account(name="tset")
		account.deposit(500) # Depost issues the save routine
		operator = None

		m1 = Merchandise(name="m1", internal_price=3, ordinary_price=4)
		m1.save()
		m2 = Merchandise(name="m2", internal_price=2, ordinary_price=4)
		m2.save()

		merchandise_list = [m1, m1, m1, m2]

		# Test a basic purchase:
		total_price = sum(m.ordinary_price for m in merchandise_list)
		trans = buy_merchandise(account, merchandise_list, operator)
		account = Account.objects.get(id=account.id) # Force update
		self.failUnlessEqual(trans.amount, -total_price)
		self.failUnlessEqual(account.balance, 500 - total_price)

		# Test if the number of purchased items related to the transaction is
		# correct:
		pm_count = PurchasedItem.objects.filter(transaction=trans).count()
		item_count = len(merchandise_list)
		self.failUnlessEqual(pm_count, item_count)
Exemple #3
0
    def setUp(self):
        self.test_user = Client.objects.create_user('test', 'user',
                                                    '*****@*****.**',
                                                    'testpassword')
        self.application = Application(
            name="Test Application",
            redirect_uris="http://localhost",
            user=self.test_user,
            client_type=Application.CLIENT_CONFIDENTIAL,
            authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
        )
        self.application.save()
        self.test_account = Account(owner=self.test_user,
                                    name='test',
                                    domain='http://www.example.com')
        self.test_account.save()

        self.test_list = models.List(account=self.test_account,
                                     created_by=self.test_user,
                                     title="Foo List")
        self.test_list.save()
        self.create_url = reverse('lists:list_create',
                                  kwargs={'account': self.test_account.uaid})
        self.retrieve_url = reverse('lists:retrieve_update_delete',
                                    kwargs={
                                        'ugid': self.test_list.ugid,
                                        'account': self.test_account.uaid,
                                    })
Exemple #4
0
    def setUp(self):
        self.beneficiary = CustomUser.objects.create(
            email="*****@*****.**",
            first_name="beneficiary",
            last_name="beneficiaryt",
            type=CustomUser.BENEFICIARY)

        self.beneficiary_account = Account.generate(self.beneficiary)

        self.facililator = CustomUser.objects.create(
            email="*****@*****.**",
            first_name="facililator",
            last_name="facililator",
            type=CustomUser.FACILITATOR)

        self.facililator_account = Account.generate(self.facililator)

        self.investor = CustomUser.objects.create(email="*****@*****.**",
                                                  first_name="investor",
                                                  last_name="investor",
                                                  type=CustomUser.INVESTOR)

        self.investor_account = Account.generate(self.investor)

        self.project = Project.objects.create(owner=self.facililator,
                                              start="2020-03-01",
                                              end="2021-03-01",
                                              title="Ma project",
                                              description="Test")
Exemple #5
0
    def get(self, request, *args, **kwargs):

        # bring in a serializer with many=True

        accounts = Account.objects.all().exclude(
                                    Q(balance=0.0) & Q(control_account=False)).exclude(
                                        parent_account__isnull=False).order_by('pk')
        date  = datetime.date.today()
        total_debit = Account.total_debit()
        total_credit = Account.total_credit()
        inventory_value = InventoryItem.total_inventory_value()
        # manufactured_items stock value

        data = {
            'date': date,
            'total_debit': total_debit,
            'total_credit': total_credit,
            'inventory_value': inventory_value,
        }

        return Response(data, status=status.HTTP_200_OK)
        


        
def test_account_model_value_invalid(value, code):
    account = Account(value=value)
    with pytest.raises(ValidationError) as exc_info:
        account.full_clean()
    assert 'value' in exc_info.value.error_dict
    assert len(exc_info.value.error_dict['value']) == 1
    assert exc_info.value.error_dict['value'][0].code == code
Exemple #7
0
def register(request):
    if request.method == "POST":
        nextPage = request.POST.get("next", "/")
        form = RegisterForm(request.POST)
        if form.is_valid():
            try:
                form.save()
            except:
                print "Unable to save form..."
                return render_to_response("registration/registration.html", {'form': form, 'next': nextPage}, context_instance=RequestContext(request))
            user = authenticate(username=request.POST.get("username"), password=request.POST.get("password1"))
            login(request, user)
            account = Account()
            account.user = User.objects.get(pk=user.id)
            account.created_by = user
            account.save()
            return redirect(nextPage)
        else:
            print "errors in registration"
            print form.errors
    else:
        form = RegisterForm()
        nextPage = request.GET.get("next", "/")
    # return render_to_response("registration/login.html", {}, context_instance=RequestContext(request))
    return redirect("ig.api.connectInstagram")
Exemple #8
0
def reg_service(request):
    if request.method == 'GET':
        raise Http404('Wrong URL')

    try:
        name = request.POST['name']
        email = request.POST['email']
        password = request.POST['password']

        if not (re.match(r'^.{2,15}$', name) or
                re.match(r'^[a-zA-Z0-9.-_]{2,50}@[a-zA-Z0-9]{2,30}.[a-zA-Z0-9]{1,10}$', email) or
                re.match(r'^.{6,20}$', password)):
            return HttpResponse('false')

        try:
            # If email has been registered, return 'register'
            # Or continue
            if Account.objects.get(email=email):
                return HttpResponse('registered')
        except:
            pass

        salt = generate_salt()
        encrypted_password = encrypt_pwd(password, salt)
        user = Account(name=name, email=email, pwd=encrypted_password, salt=salt, last_ip=request.META['REMOTE_ADDR'])
        user.save()
        request.session['user_id'] = user.id
        return HttpResponse('true')
    except:
        return HttpResponse('false')
Exemple #9
0
def createAccount(request):
    template_name = "accounts/accountcreate.html"

    form = AccountCreateForm()
    context = {}
    context["form"] = form
    if request.method == "POST":
        form = AccountCreateForm(request.POST)

        if form.is_valid():
            personname = form.cleaned_data.get("personname")
            accno = form.cleaned_data.get("accno")
            actype = form.cleaned_data.get("actype")
            balance = form.cleaned_data.get("balance")
            phonenumber = form.cleaned_data.get("phonenumber")
            mpin = form.cleaned_data.get("mpin")

            obj = Account(personname=personname,
                          accno=accno,
                          actype=actype,
                          balance=balance,
                          phonenumber=phonenumber,
                          mpin=mpin)
            obj.save()
            return render(request, template_name, context)
    return render(request, template_name, context)
Exemple #10
0
def hub_add_account(request, pk):
    if request.is_ajax():
        # POST method for creating a new object
        if request.method == 'POST':

            try:
                a_type = request.POST['account_type']
                b = request.POST['balance']
                curr = request.POST['currency']
                currency = Currency.objects.filter(name=curr)
                hub = get_object_or_404(Hubs, pk=pk)
                if a_type == 'b':
                    bank = request.POST['bank_name']
                    number = request.POST['number']
                    new_acc = Account(account_type=a_type, balance=b, currency=currency[0],
                                      bank_name=bank, number=number, owner=hub)
                else:
                    new_acc = Account(account_type=a_type, balance=b, currency=currency[0],
                                      owner=hub)

            except KeyError, e:
                print "Key Error account_new_get POST"
                print e
                return HttpResponseServerError(request)
            except Exception as e:
                print "Turbo Exception account_new_get GET"
                print e.args
                return HttpResponseServerError(request)

            new_acc.save()

            return JsonResponse({'code': '200',
                                 'msg': 'all cool',
                                 'pk': new_acc.pk},
                                )
def reg_service(request):
    if request.method == "GET":
        raise Http404("Wrong URL")

    try:
        name = request.POST["name"]
        email = request.POST["email"]
        password = request.POST["password"]

        if not (
            re.match(r"^.{2,15}$", name)
            or re.match(r"^[a-zA-Z0-9.-_]{2,50}@[a-zA-Z0-9]{2,30}.[a-zA-Z0-9]{1,10}$", email)
            or re.match(r"^.{6,20}$", password)
        ):
            return HttpResponse("false")

        try:
            # If email has been registered, return 'register'
            # Or continue
            if Account.objects.get(email=email):
                return HttpResponse("registered")
        except:
            pass

        salt = generate_salt()
        encrypted_password = encrypt_pwd(password, salt)
        user = Account(name=name, email=email, pwd=encrypted_password, salt=salt, last_ip=request.META["REMOTE_ADDR"])
        user.save()
        request.session["user_id"] = user.id
        return HttpResponse("true")
    except:
        return HttpResponse("false")
Exemple #12
0
def create_mock_data(email):
    account = Account(username=email, email=email)
    account.save()
    workspace = Workspace(account=account)
    workspace.save()
    project1 = Project(title='Project 1',
                       description='Project1 description',
                       workspace=workspace,
                       color='#ffffff')
    project1.save()
    task1 = Task(title='task 1',
                 description='task 1 description',
                 project=project1,
                 estimated_hours=1,
                 status='OPEN',
                 workspace=workspace,
                 assigned_user=account)
    task1.save()
    task2 = Task(title='task 2',
                 description='task 2 description',
                 project=project1,
                 estimated_hours=1,
                 status='READY',
                 workspace=workspace,
                 assigned_user=account)
    task2.save()
    project2 = Project(title='Project 2',
                       description='Project2 description',
                       workspace=workspace,
                       color='#ffff00')
    project2.save()
    task3 = Task(title='task 3',
                 description='task 3 description',
                 project=project2,
                 estimated_hours=1,
                 status='IN_PROGRESS',
                 workspace=workspace,
                 assigned_user=account)
    task3.save()
    task4 = Task(title='task 4',
                 description='task 4 description',
                 project=project2,
                 estimated_hours=1,
                 status='DONE',
                 workspace=workspace,
                 assigned_user=account)
    task4.save()
    tasks = Task.objects.all()
    cycle = Cycle(goal_title='Default',
                  start_date=timezone.now(),
                  workspace=workspace)
    cycle.save()
    activeCycle = Cycle(goal_title='Active',
                        start_date=timezone.now(),
                        end_date=timezone.now() + timezone.timedelta(7),
                        workspace=workspace)
    activeCycle.save()
    activeCycle.tasks.set(tasks)
    cycle.save()
 def create(self, validated_data):
     account = Account(user=User.objects.create_user(
         validated_data['username'], validated_data['email'],
         validated_data['password']),
                       currency=1000)
     account.user.save()
     account.save()
     return account
Exemple #14
0
 def setUp(self):
     self.client = Client()
     Account.register("bobthebuilder", "*****@*****.**", "password", "password")
     self.client.login(username="******", password="******")
     self.account_id = Account.objects.get(username="******").id
     self.file_dir = os.path.join(settings.MEDIA_ROOT, files.models.rel_local_file_dir(self.account_id))
     if not os.path.isdir(self.file_dir):
         os.makedirs(self.file_dir)
Exemple #15
0
def create_profile(sender, instance, created, **kwargs):
    if created:
        user_profile = Profile(user=instance)
        user_evaluation = UserEvaluation(user=instance)
        user_member_account = Account(user=instance)
        user_evaluation.save()
        user_profile.save()
        user_member_account.save()
class TestAnAccountWithFunds(TestCase):
    def setUp(self):
        self.account = Account()
        self.account.balance = D('100.00')

    def test_cannot_be_closed(self):
        with self.assertRaises(exceptions.AccountNotEmpty):
            self.account.close()
Exemple #17
0
    def setUp(self):
        PlotTest.files = []

        # used for tests that use fake requests
        self.client = Client()
        Account.register("brobot2", "*****@*****.**", "password", "password")
        self.account_id = Account.objects.get(username="******").id
        self.client.login(username="******", password="******")
Exemple #18
0
def registerUser(request):
	rtn_dict = {'success': False, "msg": ""}

	login_failed = False

	if request.method == 'POST':
		try:
			new_user = User(username=request.POST.get("username"))
			new_user.is_active = True
			new_user.password = make_password(request.POST.get('password1'))
			new_user.email = request.POST.get('email')
			new_user.save()
			user = authenticate(username=request.POST.get("username"), password=request.POST.get("password1"))

			if user is None:
				login_failed = True
				status = 401

			else:
				auth_login(request, user)
				account = Account(user=user)
				account.email = user.email
				account.user_name = user.username
				account.save()

				rtn_dict['success'] = True
				rtn_dict['msg'] = 'Successfully registered new user'
				rtn_dict['user'] = new_user.id
				rtn_dict['account'] = account.id
				return HttpResponse(json.dumps(rtn_dict, cls=DjangoJSONEncoder), content_type="application/json", status=status)

			'''
			r = R.r
			#PUSH NOTIFICATIONS
			token = request.POST.get('device_token', None)
			if token is not None:
				try:
					# Strip out any special characters that may be in the token
					token = re.sub('<|>|\s', '', token)
					registerDevice(user, token)
					device_token_key = 'account.{0}.device_tokens.hash'.format(account.id)
					token_dict = {str(token): True}
					r.hmset(device_token_key, token_dict)
				except Exception as e:
					print 'Error allowing push notifications {0}'.format(e)
			
			user_key = 'account.{0}.hash'.format(account.id)
			r.hmset(user_key, model_to_dict(account))
			'''
		except Exception as e:
			print 'Error registering new user: {0}'.format(e)
			logger.info('Error registering new user: {0}'.format(e))
			rtn_dict['msg'] = 'Error registering new user: {0}'.format(e)

	else:
		rtn_dict['msg'] = 'Not POST'

	return HttpResponse(json.dumps(rtn_dict, cls=DjangoJSONEncoder), content_type="application/json")
Exemple #19
0
    def test_accounts(self):
        from django.core.urlresolvers import reverse

        # Can't access when we are not logged in.
        response = self.client.get(reverse('accounts'))
        self.assertEqual(response.status_code, 200)

        response = self.client.get(
            reverse('accounts_detail', kwargs={'object_id': self.bob.id}))
        self.assertEqual(response.status_code, 200)

        response = self.client.get(
            reverse('accounts_edit', kwargs={'object_id': self.bob.id}))
        self.assertEqual(response.status_code, 302)

        self.client.login(username='******', password='******')
        response = self.client.get(
            reverse('accounts_edit', kwargs={'object_id': self.bob.id}))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "%s" % self.bob.name)

        response = self.client.get(
            reverse('accounts_remove', kwargs={'object_id': self.alice.id}))
        self.assertEqual(response.status_code, 302)

        self.client.logout()
        self.user_bob.is_staff = True
        self.user_bob.is_superuser = True
        self.user_bob.save()
        self.assertTrue(self.user_bob.is_superuser)
        self.client.login(username='******', password='******')

        response = self.client.get(
            reverse('accounts_remove', kwargs={'object_id': self.alice.id}))
        self.assertEqual(response.status_code, 200)

        name = self.alice.name
        local_id = self.alice.local_id

        response = self.client.post(reverse(
            'accounts_remove', kwargs={'object_id': self.alice.id}),
                                    data={
                                        'object_name': name,
                                        'result': 'Cancel'
                                    })
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Account.objects(name=name).count(), 1)

        # no Resources in setup so delete works
        response = self.client.post(reverse(
            'accounts_remove', kwargs={'object_id': self.alice.id}),
                                    data={
                                        'object_name': name,
                                        'result': 'Delete'
                                    })
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Account.objects(name=name).count(), 0)
        self.assertEqual(User.objects.filter(pk=local_id).count(), 0)
Exemple #20
0
def add(data, db_session, username):
    logger.debug(LogMsg.START, username)

    permissions, presses = get_user_permissions(username, db_session)
    has_permission([Permissions.ACCOUNT_ADD_PREMIUM], permissions)
    check_schema(['person_id', 'type'], data.keys())
    logger.debug(LogMsg.SCHEMA_CHECKED)
    check_enum(data.get('type'), AccountTypes)
    logger.debug(LogMsg.ENUM_CHECK, {
        'enum': data.get('type'),
        'reference_enum': 'AccountTypes'
    })

    user = check_user(username, db_session)
    logger.debug(LogMsg.USER_CHECKING, username)

    if user is None:
        logger.error(LogMsg.INVALID_USER, username)
        raise Http_error(404, Message.INVALID_USER)

    logger.info(LogMsg.USER_XISTS, username)

    if user.person_id is None:
        logger.info(LogMsg.PERSON_NOT_EXISTS, username)

        raise Http_error(404, Message.Invalid_persons)

    validate_person(user.person_id, db_session)
    logger.info(LogMsg.PERSON_EXISTS, username)

    type = data.get('type', 'Main')
    value = data.get('value', 0.0)
    person_id = data.get('person_id')

    logger.info(LogMsg.GETTING_USER_ACCOUNTS, type)

    account = get(person_id, type, db_session)
    if account is not None:
        logger.error(LogMsg.ACCOUNT_BY_TYPE_EXISTS, type)

        raise Http_error(409, Message.ALREADY_EXISTS)

    model_instance = Account()

    populate_basic_data(model_instance, username, data.get('tags'))
    logger.debug(LogMsg.POPULATING_BASIC_DATA)

    model_instance.type = type
    model_instance.person_id = person_id
    model_instance.value = value

    db_session.add(model_instance)

    logger.debug(LogMsg.DB_ADD, account_to_dict(model_instance))

    logger.info(LogMsg.END)

    return account_to_dict(model_instance)
Exemple #21
0
	def test_get_samples(self):
		acc = Account()
		acc.user = self.user
		fake_task_id = str(uuid4())
		run = ScanRun.objects.create_pending_scan_run(self.inert, fake_task_id)
		sample = acc.get_samples()
		# sample = [<FileSample: 4>]
		self.assertTrue(isinstance(sample[0], FileSample),
		                msg='Sample object is not instance of FileSample: {0}'.format(sample[0]))
Exemple #22
0
 def setUp(self):
     self.client = Client()
     Account.register(HistogramTest.username, "*****@*****.**", "password", "password")
     self.account_id = Account.objects.get(username="******").id
     self.client.login(username="******", password="******")
     self.title = 'HISTOGRAM TEST TITLE'
     self.file_dir = os.path.join(settings.MEDIA_ROOT, files.models.rel_local_file_dir(self.account_id))
     if not os.path.isdir(self.file_dir):
         os.makedirs(self.file_dir)
Exemple #23
0
def user_register(request):
    with transaction.atomic():
        serializer = CustomUserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        Account.generate(user)

        return Response(status=status.HTTP_201_CREATED)
class TestAnAccountWithFunds(TestCase):

    def setUp(self):
        self.account = Account()
        self.account.balance = D('100.00')

    def test_cannot_be_closed(self):
        with self.assertRaises(exceptions.AccountNotEmpty):
            self.account.close()
Exemple #25
0
 def test_double_amount(self):
     user = get_user_model().objects.create(
         username='******',
     )
     # Transaction.objects.create(account_from='test', account_to='test', user=user)
     acc = Account(name='qwe', user=user)
     acc.save()
     trans2 = Transaction(account_from=acc, account_to=acc, user=user)
     self.assertRaisesMessage(ValidationError, 'Accounts must differ', trans2.clean)
Exemple #26
0
    def test_create_account(self):
        """An account object can be created."""
        account = Account(
            id="8dd89dc4-ac43-4ecd-88d0-75791d63621c",
            user=self.user,
            account_blocked=False,
            account_number="PA24RIKIGB1U",
            buying_power=400000,
            cash=100000,
            created_at="2020-10-31T23:40:50.376107Z",
            currency="USD",
            daytrade_count=0,
            daytrading_buying_power=400000,
            equity=100000,
            initial_margin=0,
            last_equity=100000,
            last_maintenance_margin=20000,
            long_market_value=50000,
            maintenance_margin=10000,
            multiplier=4,
            pattern_day_trader=False,
            portfolio_value=60000,
            regt_buying_power=5000,
            shorting_enabled=True,
            sma=1000,
            status=Account.ACTIVE,
            trade_suspended_by_user=False,
            trading_blocked=False,
            transfers_blocked=False,
        )
        account.save()

        self.assertEqual(account.id, "8dd89dc4-ac43-4ecd-88d0-75791d63621c")
        self.assertEqual(account.user, self.user)
        self.assertFalse(account.account_blocked)
        self.assertEqual(account.account_number, "PA24RIKIGB1U")
        self.assertEqual(account.buying_power, 400000)
        self.assertEqual(account.cash, 100000)
        self.assertEqual(account.currency, "USD")
        self.assertEqual(account.daytrade_count, 0)
        self.assertEqual(account.daytrading_buying_power, 400000)
        self.assertEqual(account.equity, 100000)
        self.assertEqual(account.initial_margin, 0)
        self.assertEqual(account.last_equity, 100000)
        self.assertEqual(account.last_maintenance_margin, 20000)
        self.assertEqual(account.long_market_value, 50000)
        self.assertEqual(account.maintenance_margin, 10000)
        self.assertEqual(account.multiplier, 4)
        self.assertFalse(account.pattern_day_trader)
        self.assertEqual(account.portfolio_value, 60000)
        self.assertEqual(account.regt_buying_power, 5000)
        self.assertTrue(account.shorting_enabled)
        self.assertEqual(account.sma, 1000)
        self.assertEqual(account.status, Account.ACTIVE)
        self.assertFalse(account.trade_suspended_by_user)
        self.assertFalse(account.trading_blocked)
        self.assertFalse(account.transfers_blocked)
Exemple #27
0
    def setUp(self):
        django.setup()
        self.client = Client()
        Account.register(FilesTest.username, "*****@*****.**", "password", "password")
        self.account_id = Account.objects.get(username="******").id
        self.client.login(username="******", password="******")

        self.file_dir = os.path.join(settings.MEDIA_ROOT, files.models.rel_local_file_dir(self.account_id))
        if not os.path.isdir(self.file_dir):
            os.makedirs(self.file_dir)
Exemple #28
0
	def test_get_pending_scans_not_empty(self):
		acc = Account()
		acc.user = self.user

		fake_task_id = str(uuid4())
		run = ScanRun.objects.create_pending_scan_run(self.inert, fake_task_id)
		pending = acc.get_pending_scans()
		#  pending == ['<ScanRun: 3 2013-08-19 14:37:56.165701+00:00>']
		self.assertTrue(isinstance(pending[0], ScanRun),
		                msg='Pending scan object is not of instance of ScanRun: {0}'.format(pending[0]))
Exemple #29
0
    def post(self, request):
        a = Account()
        account, msg = a.authenticateUser(request.data)

        if account and account.token:
            result = AccountLoginSerializer(account)

            return Response(result.data)

        return Response({'error': msg}, status=status.HTTP_404_NOT_FOUND)
Exemple #30
0
    def test_accounts(self):
        from django.core.urlresolvers import reverse

        # Can't access when we are not logged in.
        response = self.client.get(reverse('accounts'))
        self.assertEqual(response.status_code, 200)

        response = self.client.get(
                reverse('accounts_detail', kwargs={'object_id': self.bob.id}))
        self.assertEqual(response.status_code, 200)

        response = self.client.get(
                reverse('accounts_edit', kwargs={'object_id': self.bob.id}))
        self.assertEqual(response.status_code, 302)

        self.client.login(username='******', password='******')
        response = self.client.get(
                reverse('accounts_edit', kwargs={'object_id': self.bob.id}))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "%s" % self.bob.name)

        response = self.client.get(
                reverse('accounts_remove', kwargs={'object_id': self.alice.id}))
        self.assertEqual(response.status_code, 302)

        self.client.logout()
        self.user_bob.is_staff = True
        self.user_bob.is_superuser = True
        self.user_bob.save()
        self.assertTrue(self.user_bob.is_superuser)
        self.client.login(username='******', password='******')

        response = self.client.get(
                reverse('accounts_remove', kwargs={'object_id': self.alice.id}))
        self.assertEqual(response.status_code, 200)

        name = self.alice.name
        local_id = self.alice.local_id

        response = self.client.post(
                reverse('accounts_remove',
                    kwargs={'object_id': self.alice.id}),
                    data={'object_name': name, 'result': 'Cancel'})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Account.objects(name=name).count(), 1)

        # no Resources in setup so delete works
        response = self.client.post(
                reverse('accounts_remove',
                    kwargs={'object_id': self.alice.id}),
                    data={'object_name': name, 'result': 'Delete'})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Account.objects(name=name).count(), 0)
        self.assertEqual(User.objects.filter(pk=local_id).count(), 0)
Exemple #31
0
	def test_linkedin_auth(self):
		# create new user
		default_user = User.objects.create_user(username="******",password="******")
		# add LI info
		acct = Account(owner=default_user,service="linkedin",uniq_id="1e3r5y78i!")
		acct.save()
		# test auth
		result = self.c.login(acct_id=acct.uniq_id)
		if result is not None:
			result = True
		self.assertEqual(result,True)
Exemple #32
0
	def test_unlinked_process_connections(self):
		# create new user
		default_user = User.objects.create_user(username="******",password="******")
		# add bogus LI account
		acct = Account(service="linkedin",status="unlinked",owner=default_user)
		acct.save()

		# ensure that lilib won't process connections
		li_cxn_parser = self.lilib.LIConnections(default_user.id,acct.id)
		res = li_cxn_parser.process_connections()
		self.assertEqual(res,"Error: LI accont is not active, aborting")
Exemple #33
0
    def create(self, validated_data):
        user = User.objects.filter(**{
            "id": validated_data.get("user_id")
        }).order_by().first()
        if user:
            instance = Account(user=user)
            instance.save()
            self.instance = instance
            return self

        return None
Exemple #34
0
    def process(self, uid):
        data = self.cleaned_data
        name = data['name']
        user = User.objects.get(id=uid)
        profile = user.get_profile()
        accounts = profile.accounts

        account = Account(name=name, owner=user)
        account.save()
        accounts.add(account)
        profile.save()
        user.save()
Exemple #35
0
def add_initial_account(person_id, db_session, username):
    logger.info(LogMsg.START, username)

    logger.debug(LogMsg.ADD_INITIAL_ACCOUNT, person_id)

    model_instance = Account()
    populate_basic_data(model_instance, username, [])
    model_instance.type = 'Main'
    model_instance.person_id = person_id
    db_session.add(model_instance)
    logger.info(LogMsg.END)

    return account_to_dict(model_instance)
Exemple #36
0
    def test_account_update(self):
        user = CustomUser.objects.create_user(username='******',
                                              email='*****@*****.**',
                                              password='******')
        credential = Credential(user=user,
                                bank='FNB',
                                username=USERNAME,
                                password=PASSWORD)
        credential.save()
        account_1 = Account(credential=credential,
                            name='cheque',
                            account_type='cheque')
        account_1.save()
        account_2 = Account(credential=credential,
                            name='credit',
                            account_type='credit',
                            limit=20000)
        account_2.save()
        cron_job = FetchCronJob()

        # cron_job.do() for a real test
        # mock steps for speed
        self.mock_balances(cron_job, credential, ['1000', '1000'])

        self.assertQuerysetEqual(
            Account.objects.order_by('id'),
            ['<Account: cheque 1000.00>', '<Account: credit -19000.00>'])
Exemple #37
0
	def add_dormant_user(self,user_info):

		# create dormant user account
		temp_username = user_info['firstName'] + user_info['lastName'] + user_info['id']
		temp_username = temp_username[:30]
		# self.stdout.write(temp_username)
		user = User()
		user.username = temp_username
		user.save()

		# create user profile
		user.profile.first_name = user_info['firstName']
		user.profile.last_name = user_info['lastName']
		if 'headline' in user_info:
			user.profile.headline = user_info['headline']		
		user.profile.status = "dormant"
		user.profile.save()

		# add pofile picture
		if 'pictureUrl' in user_info:
			self.add_profile_pic(user,user_info['pictureUrl'])

		# create LinkedIn account
		acct = Account()
		acct.owner = user
		acct.service = 'linkedin'
		acct.uniq_id = user_info['id']
		if 'publicProfileUrl' in user_info:
			acct.public_url = user_info['publicProfileUrl']
		acct.status = "unlinked"
		acct.save()

		return user
Exemple #38
0
	def process_connection_and_finish_user(self, user, user_info):
		"""
		Delegates to helpers to process rest of User, adds Account, maps positions
		Return: User
		"""

		## add LI account
		acct = Account()
		acct.owner = user
		acct.service = 'linkedin'
		acct.uniq_id = user_info['id']
		if 'publicProfileUrl' in user_info:
			acct.public_url = user_info['publicProfileUrl']
		acct.status = 'unlinked'
		acct.save()

		## Edge case that showed up in production
		if 'publicProfileUrl' not in user_info:
			return user
		
		## parse public page
		self.process_public_page_existing(user_info['publicProfileUrl'], user)

		## Map Positions
		# match all positions to ideals
		for p in user.positions.all():
			careerlib.match_position_to_ideals(p)
		# process first_ideal_position
		user.profile.set_first_ideal_job()

		return user
class TestANewZeroCreditLimitAccount(TestCase):
    def setUp(self):
        self.account = Account()

    def test_defaults_to_zero_credit_limit(self):
        self.assertEqual(D('0.00'), self.account.credit_limit)

    def test_does_not_permit_any_debits(self):
        self.assertFalse(self.account.is_debit_permitted(D('1.00')))

    def test_has_zero_balance(self):
        self.assertEqual(D('0.00'), self.account.balance)

    def test_has_zero_transactions(self):
        self.assertEqual(0, self.account.num_transactions())
Exemple #40
0
    def test_account_should_be_informed_about_tag_in_region_he_interested_in(self):
        """
        User should be informed about event that appeared in region that he is interested in
        """

        user = User.objects.create_user(username='******', email="*****@*****.**",  password="******")
        account = Account(
            user=user,
            all_of_canada=False,
            regions=[Region.objects.filter(name="Alberta"), Region.objects.filter(name="Saskatchewan")],
            tags=["boo"]
        )

        venue = Venue(
            name="Test venue",
            city=City.objects.filter(name="Saskatoon"),
            country=Country.objects.filter(name="Canada")
        )

        event = Event(
            name="Test event",
            venue=venue,
            tags=["boo"]
        )

        self.assertIn(
            event,
            InTheLoopSchedule.unprocessed_for_account(account)
        )        
Exemple #41
0
 def destroy(self, request, pk=None, *args, **kwargs):
     account = Account(pk=pk)
     account.user.delete()
     return Response({
         'status': HTTP_200_OK,
         'message': 'HTTP_200_OK'
     }, status=HTTP_200_OK)
Exemple #42
0
def login():
    if "email" in session:
        account = Account.find_by_email(session["email"])
        if account:
            return redirect(url_for("instances.list"))

    return render_template("auth/login.html", form=AuthenticationForm())
Exemple #43
0
        class PostValidLogin(DjangoHTTPContext):

            def setup(self):
                self.validUser = Account(username='******',password='******')
                self.validUser.save()

            def teardown(self):
                self.validUser.delete()

            def topic(self):
               return self.post('/login/',
                                {'username':self.validUser.username,
                                 'password':self.validUser.password})

            def should_return_valid_login(self, (topic,content)):
               expect(content).to_equal("Login Succesful")
Exemple #44
0
class TestAnAccountWithFunds(TestCase):
    def setUp(self):
        self.account = Account()
        self.account.balance = D('100.00')

    def test_cannot_be_closed(self):
        with self.assertRaises(exceptions.AccountNotEmpty):
            self.account.close()

    def test_allows_allocations_less_than_balance(self):
        amt = self.account.permitted_allocation(None, D('2.00'), D('12.00'))
        self.assertEqual(D('12.00'), amt)

    def test_doesnt_allow_allocations_greater_than_balance(self):
        amt = self.account.permitted_allocation(None, D('2.00'), D('120.00'))
        self.assertEqual(D('100.00'), amt)
Exemple #45
0
def saveSfdcAccountsToMaster(user_id=None, company_id=None, job_id=None, run_type=None):    
    #delete later
    #job_id = ObjectId("569fd4078afb002426ef2fd3")
    if run_type == 'initial':
        accounts = TempData.objects(Q(company_id=company_id) & Q(record_type='account') & Q(source_system='sfdc') & Q(job_id=job_id) ).only('source_record') #& Q(job_id=job_id) 
    else:
        accounts = TempDataDelta.objects(Q(company_id=company_id) & Q(record_type='account') & Q(source_system='sfdc') & Q(job_id=job_id) ).only('source_record') #& Q(job_id=job_id) 
    
    accountListTemp = list(accounts)
    accountList = [i['source_record'] for i in accountListTemp]
    
    try: 
        for newAccount in accountList:
            sfdc_id = str(newAccount['Id']) 
            #find all leads that have this account ID 
            relatedLeadList = []
            relatedLeadListTemp = None
            relatedLeads = Lead.objects(Q(company_id=company_id) & Q(sfdc_account_id=sfdc_id)).only('sfdc_contact_id') #if SFDC Account, then matching lead must have a SFDC Contact ID
            if relatedLeads is not None:
                relatedLeadListTemp = [lead.to_mongo().to_dict() for lead in relatedLeads]
                #print 'rll is ' + str(relatedLeadListTemp)
                for i in relatedLeadListTemp:
                    if 'sfdc_contact_id' in i:
                        relatedLeadList.append({'sfdc_contact_id': i['sfdc_contact_id']})
    
                #print 'related leads are ' + str(relatedLeadList)
#             if relatedLeads is not None:
#                 #leadListTemp = list(relatedLeads)
#                 #relatedLeadList = [i.id for i in leadListTemp]
#                 for lead in relatedLeads:
#                     relatedLeadList.append(lead)
                
            print 'account id is ' + sfdc_id
            # sfdc_mkto_id = str(newLead['sfdcLeadId']) #check if there is a corresponding lead from MKTO
            existingAccount = None
            existingAccount = Account.objects(Q(company_id=company_id) & Q(sfdc_id=sfdc_id)).first()
            
            if existingAccount is not None:  # we found this contact already in the DB
                print 'found existing account for id ' + str(sfdc_id)
                if 'sfdc' in existingAccount.accounts:
                    existingAccount.source_name = newAccount['Name']
                    existingAccount.source_source = newAccount['AccountSource']
                    existingAccount.source_industry = newAccount['Industry']
                    existingAccount.source_created_date = newAccount['CreatedDate']
                    existingAccount.accounts["sfdc"] = newAccount
                    if relatedLeadList is not None:
                        existingAccount.leads = relatedLeadList
                    existingAccount.save()
                    #Lead.objects(Q(company_id=company_id) & Q(sfdc_contact_id=sfdc_contact_Id)).update(contacts__sfdc=newContact)
                else:
                    existingAccount.accounts['sfdc'] = {}
                    existingAccount.accounts['sfdc'] = newAccount
                    if relatedLeadList is not None:
                        existingAccount.leads = relatedLeadList
                    existingAccount.save()
            elif existingAccount is None:  # this account does not exist     
                account = _saveSfdcNewAccount(sfdc_id, newAccount, relatedLeadList, company_id)
    except Exception as e:
        print 'exception while saving accounts ' + str(e)
        send_notification(dict(type='error', success=False, message=str(e)))         
Exemple #46
0
def workingWith(request):
    user = Account.login(request)
    if not user:
        return HttpResponseRedirect(reverse(login))

    return HttpResponse(
        json.dumps(graph.ols.workingWith(user), sort_keys=True, indent=4))
Exemple #47
0
def reset(request):
    user = Account.login(request)
    if user:
        user.logout(request)
        user.delete()

    return HttpResponseRedirect(reverse(login))
class TestANewZeroCreditLimitAccount(TestCase):

    def setUp(self):
        self.account = Account()

    def test_defaults_to_zero_credit_limit(self):
        self.assertEqual(D('0.00'), self.account.credit_limit)

    def test_does_not_permit_any_debits(self):
        self.assertFalse(self.account.is_debit_permitted(D('1.00')))

    def test_has_zero_balance(self):
        self.assertEqual(D('0.00'), self.account.balance)

    def test_has_zero_transactions(self):
        self.assertEqual(0, self.account.num_transactions())
Exemple #49
0
def create_account(user):
    try:
        account = Account.objects.get(user=user)
        # print "Account already exists"
    except:
        account = Account()
        account.user = User.objects.get(pk=user.id)
        account.created_by = user
        try:
            account.save()
            return True
        except Exception as e:
            print "Unable to save account..."
            print e
            return False
    return True
Exemple #50
0
def customerio():
    if request.headers.get('x-cio-timestamp', '') == '':
        return make_response(
            jsonify({
                'success': False,
                'reason': 'Invalid request made.'
            }), 400)

    payload = b'v0:' + request.headers.get(
        'x-cio-timestamp').encode() + b':' + request.get_data()

    signature = hmac.new(
        key=current_app.config.get('CUSTOMERIO_SIGNING_KEY').encode(),
        msg=payload,
        digestmod=hashlib.sha256).hexdigest()

    if signature != request.headers.get('x-cio-signature'):
        return make_response(
            jsonify({
                'success': False,
                'reason': 'Invalid request made.'
            }), 400)

    body = request.get_json()
    assert body.get('event_type') == 'email_bounced'
    account = Account.find_by_email(body.get('data').get('email_address'))
    if account is None:
        return 'ok'

    account.lock('bounced')
    account.save(True)

    return 'ok'
Exemple #51
0
    def create(self, request):
        a = Account()
        a_id, msg = a.register(request.data)

        if a_id:
            try:
                account = Account.objects.get(pk=a_id)
            except:
                return Response({'error': 'Not found'},
                                status=status.HTTP_404_NOT_FOUND)

            result = AccountSerializer(account)

            return Response(result.data)

        return Response({'error': msg}, status=status.HTTP_400_BAD_REQUEST)
Exemple #52
0
    def get(self, request, format=None):
        '''
        get my calendar
        '''
        user = Account.find_account_by_user(request.user)
        turn_to_date = lambda x: x and datetime.strptime(x, '%Y%m%d') or date.today()
        start_date = turn_to_date(request.GET.get('start', None))
        end_date = turn_to_date(request.GET.get('end', None))
        plans = []
        calendars = (Calendar.objects
            .select_related('plan')
            .select_related('user')
            .filter(user=user, joined_date__gte=start_date, joined_date__lte=end_date))

        try:
            last_joined = Calendar.objects.filter(user=user, joined_date__lte=start_date).order_by('-joined_date')[0]
            last = CalendarSerializer(last_joined, context={'simple': False}).data
            plans.append(last['plan'])
        except IndexError:
            last = None
        serializer = CalendarSerializer(calendars, many=True, context={'simple': False}).data
        for c in serializer:
            plans.append(c['plan'])
        punchs = Punch.objects.filter(user=user, date__lte=end_date, date__gte=start_date, state__gte=10)
        count = Punch.objects.filter(user=user, state__gte=10)
        result = {
            'lastJoined': last,
            'calendar': serializer,
            'punch': PunchSerializer(punchs, many=True).data,
            'plans': plans,
            'count': len(count)
        }
        return self.success_response(result)
Exemple #53
0
	def test_illegal_purchase(self):
		"""Test if purchases are canceled if they should not be allowed

		"""
		account = Account(name="tset")
		account.deposit(3) # Deposit issues the save routine
		operator = None

		m1 = Merchandise(name="m1", internal_price=3, ordinary_price=4)
		m1.save()

		# Test illegal purchase:
		trans = buy_merchandise(account, [m1], operator)
		account = Account.objects.get(id=account.id) # Force update
		self.failUnlessEqual(trans, None)
		self.failUnlessEqual(account.balance, 3)
Exemple #54
0
def emails(request):
    user = Account.login(request)
    if not user:
        return HttpResponseRedirect(reverse(login))

    return HttpResponse(
        json.dumps(graph.graph.get_my_emails(user), sort_keys=True, indent=4))
Exemple #55
0
def trendingAround(request):
    user = Account.login(request)
    if not user:
        return HttpResponseRedirect(reverse(login))

    return HttpResponse(
        json.dumps(graph.ols.trendingAround(user), sort_keys=True, indent=4))
Exemple #56
0
    def deposit(self, request_data):

        try:
            user = Idm.objects.get(idm=request_data['idm']).account
        except Idm.DoesNotExist:
            raise ValueError(_('User auth failed'))

        deposit = self.model(
            amount=request_data['amount'],
            merchant=request_data['merchant'],
            user=user,
        )
        Account.deposit(user.id, deposit.amount)
        deposit.save()

        return deposit
    def test_retry_atomic(self):
        main_account = Account.get_main_account()
        txn0 = Transaction.objects.create(
            from_account=main_account,
            to_account=self.user_account,
            amount=0.21,
            currency=Transaction.ALGO,
            action=Transaction.OPT_IN,
            status=Transaction.REJECTED,
            atomic=True,
        )
        txn1 = Transaction.objects.create(from_account=self.user_account,
                                          to_account=self.user_account,
                                          amount=0,
                                          currency=Transaction.USDC,
                                          action=Transaction.OPT_IN,
                                          atomic=True,
                                          atomic_prev=txn0)
        txn2 = Transaction.objects.create(from_account=main_account,
                                          to_account=self.user_account,
                                          amount=0.1,
                                          currency=Transaction.USDC,
                                          action=Transaction.FUELING,
                                          atomic=True,
                                          atomic_prev=txn1)

        txids = txn0.retry()
        for txid in txids:
            self.assertTrue(utils.wait_for_confirmation(txid))

        self.assertEqual(Transaction.objects.count(), 6)
Exemple #58
0
    def setUp(self):
        self.client1 = Client()
        self.client2 = Client()
        Account.register(PermissionsTest.user1Name, "*****@*****.**", "password", "password")
        self.account_id_one = Account.objects.get(username=PermissionsTest.user1Name).id
        self.client1.login(username=PermissionsTest.user1Name, password='******')
        Account.register(PermissionsTest.user2Name, "*****@*****.**", "password", "password")
        self.account_id_two = Account.objects.get(username=PermissionsTest.user2Name).id
        self.client2.login(username=PermissionsTest.user2Name, password="******")

        self.file_dir_one = os.path.join(settings.MEDIA_ROOT, files.models.rel_local_file_dir(self.account_id_one))
        self.file_dir_two = os.path.join(settings.MEDIA_ROOT, files.models.rel_local_file_dir(self.account_id_two))
        if not os.path.isdir(self.file_dir_one) and not os.path.isdir(self.file_dir_two):
            os.makedirs(self.file_dir)

        self.createPanePlot()
Exemple #59
0
 def post(self, request, format=None):
     '''
     create a personal plan
     {
         "id": 18,
         "dish": [{
             "type": 0,
             "ingredient": [{
                 "id": 1,
                 "amount": 100
             }],
             "recipe": [{
                 "id": 2,
                 "amount": 200
             }]
         },{
             "type": 1,
             "ingredient": [],
             "recipe": [{
                 "id":3,
                 "amount": 300
             }]
         }],
         "joined_date": "2015-01-01"
     }
     '''
     try:
         body = json.loads(request.body)
         user = Account.find_account_by_user(request.user)
         try:
             joined_date = datetime.strptime(body['joined_date'],'%Y-%m-%d').date()
         except:
             joined_date = date.today()
         planid = body.get('id', None)
         if planid is None:
             # create
             p = Plan.objects.create(user=user)
         else :
             p = Plan.objects.get(user=user, pk=planid)
             p.delete_routines()
         r = Routine.objects.create(plan=p)
         for dish in body.get('dish', []):
             d = Dish.objects.create(type=dish['type'], routine=r)
             for si in dish.get('ingredient', []):
                 ingredient = Ingredient.objects.get(pk=si['id'])
                 SingleIngredient.objects.create(ingredient=ingredient, amount=si['amount'], dish=d)
             for sr in dish.get('recipe', []):
                 recipe = Recipe.objects.get(pk=sr['id'])
                 SingleRecipe.objects.create(recipe=recipe, amount=sr['amount'], dish=d)
         # after created it join it!
         try:
             c = Calendar.objects.get(user=user, joined_date=joined_date)
             if c.plan.id != p.id:
                 c.plan = p
                 c.save()
         except Calendar.DoesNotExist:
             Calendar.objects.create(user=user, plan=p, joined_date=joined_date)
         return self.success_response(PlanSerializer(p).data)
     except:
         return self.fail_response(400, 'fail')
    def setUp(self):
        self.beneficiary = CustomUser.objects.create(
            email="*****@*****.**",
            first_name="beneficiary",
            last_name="beneficiaryt",
            type=CustomUser.BENEFICIARY)

        self.beneficiary_account = Account.generate(self.beneficiary)

        self.facililator = CustomUser.objects.create(
            email="*****@*****.**",
            first_name="facililator",
            last_name="facililator",
            type=CustomUser.FACILITATOR)

        self.facililator_account = Account.generate(self.facililator)

        self.investor = CustomUser.objects.create(email="*****@*****.**",
                                                  first_name="investor",
                                                  last_name="investor",
                                                  type=CustomUser.INVESTOR)

        self.investor_account = Account.generate(self.investor)

        self.project = Project.objects.create(owner=self.facililator,
                                              start="2020-03-01",
                                              end="2021-03-01",
                                              title="Ma project",
                                              description="Test")

        self.task = Task.objects.create(project=self.project,
                                        action="Test",
                                        reward="0.05")

        self.project.tasks.add(self.task)
        self.project.save()

        self.assignment = Assignment.objects.create(
            beneficiary=self.beneficiary,
            project=self.project,
            status=Assignment.ACCEPTED)

        self.activity = Activity.objects.create(
            user=self.beneficiary,
            task=self.task,
            project=self.project,
        )