예제 #1
0
def seed_db():
    from core.models import Account,Server,ConnectionType
    local_c = ConnectionType(name='local',connection_class='local')
    local_c.save()
    local = Server(ip_address='127.0.0.1',name='localhost',connection_type_id=local_c.id)    
    local.save()
    act = Account(username='******',password='******',base_dir='/',server_id=local.id)
    act.save()
예제 #2
0
 def save(self):
   account = Account(
       wealth=self.wealth,
       type=self.cleaned_data['type'],
       name=self.cleaned_data['name'],
       balance=self.cleaned_data['opening_balance'],
       modified_date=datetime.utcnow(),
       currency=self.cleaned_data['currency'],
       opening_balance=self.cleaned_data['opening_balance'],
       opened_date=self.cleaned_data['opened_date'])
   account.save()
   return account
예제 #3
0
def index():
    accounts = Account.select(Account.id, Account.account_number,
                              Account.balance, Account.deleted,
                              Account.time_deposit, User.first_name,
                              User.last_name).join(User,
                                                   attr='user').execute()
    return render_template('account/index.html', accounts=accounts)
예제 #4
0
파일: admin.py 프로젝트: iecruz/qa-bank
def deposit():
    form = TransactionForm(request.form)
    if form.validate_on_submit():
        Account.update(
            balance = Account.balance + form.amount.data,
            updated_at = datetime.now()
        ).where(Account.account_number == form.account_number.data).execute()

        Transaction.insert(
            account_number = form.account_number.data,
            reference_number = form.account_number.data,
            amount = form.amount.data,
            type = 'DEPOSIT'
        ).execute()
        flash('Deposit successful')
        return redirect(url_for('admin.deposit'))
    return render_template('admin/deposit.html', form=form)
예제 #5
0
파일: main.py 프로젝트: iecruz/qa-bank
def transfer():
    accounts = Account.select().where(
        (Account.user_id == session['user']['id'])
        & (Account.type != 3)).execute()

    form = UserTransferForm(request.form)
    form.sender_account_number.choices = [
        (account.account_number,
         "{} ({})".format(account.account_number,
                          'Savings' if account.type == 1 else 'ATM'))
        for account in accounts
    ]
    if form.validate_on_submit():
        sender_account = Account.get(
            Account.account_number == form.sender_account_number.data)
        receiver_account = Account.get(
            Account.account_number == form.receiver_account_number.data)

        Account.update(balance=Account.balance - form.amount.data,
                       updated_at=datetime.now()).where(
                           Account.account_number ==
                           form.sender_account_number.data).execute()

        Account.update(balance=Account.balance + form.amount.data,
                       updated_at=datetime.now()).where(
                           Account.account_number ==
                           form.receiver_account_number.data).execute()

        Transaction.insert(account_number=form.sender_account_number.data,
                           reference_number=form.receiver_account_number.data,
                           amount=form.amount.data,
                           type='FUND TRANSFER').execute()
        flash('Fund Transfer successful')
        return redirect(url_for('main.transfer'))
    return render_template('main/transfer.html', form=form)
예제 #6
0
파일: views.py 프로젝트: kcole16/finishedyo
def handle_yoauth(request):
	yoauth_token = request.GET['yoauth_token']
	url = 'http://yoauth.herokuapp.com/validate'
	payload = {'yoauth_token':yoauth_token}
	r = requests.get(url, params=payload)
	text = json.loads(r.text)
	username = str(text['user']['yo_username'])

	try:
		user = Account.objects.get(yo_name=username)
	except ObjectDoesNotExist:
		user = Account(yo_name=username, password='******')
		user.save()

	user.backend = 'django.contrib.auth.backends.ModelBackend'
	login(request, user)
	url = reverse('home')
	return HttpResponseRedirect(url)
예제 #7
0
파일: teller.py 프로젝트: iecruz/qa-bank
def login():
    form = TellerLoginForm(request.form)
    if form.validate_on_submit():
        account = Account.get_or_none((Account.account_number == form.account_number.data) & (Account.deleted == False))

        if account and check_password_hash(account.pin, form.password.data):
            session['atm_auth'] = account.id

            return redirect(url_for('teller.index'))
        else:
            flash('Invalid Account Number and PIN')
    return render_template('teller/login.html', form=form)
예제 #8
0
파일: teller.py 프로젝트: iecruz/qa-bank
def transfer():
    form = TransactionForm(request.form)
    if form.validate_on_submit():
        account = Account.get(Account.id == session['atm_auth'])

        if form.account_number.data == account.account_number:
            flash('You cannot transfer funds to your own account')

        else:
            Account.update(balance = Account.balance - form.amount.data).where(Account.id == session['atm_auth']).execute()
            Account.update(balance = Account.balance + form.amount.data).where(Account.account_number == form.account_number.data).execute()

            Transaction.insert(
                account_number = account.account_number,
                reference_number = form.account_number.data,
                amount = request.form.get('amount'),
                type = 'ATM FUND TRANSFER'
            ).execute()

            return redirect(url_for('teller.inquiry'))
    return render_template('teller/transfer.html', form=form)
예제 #9
0
    def form_valid(self, form):

        # save client
        form.save()
        # generate data
        num_card = utils.generateNumCard()
        num_pin = utils.generateNumPin()
        getClient = form.cleaned_data['document_number']
        # add user
        user = User(username=num_card, client=Client.objects.get(document_number=getClient))
        user.set_password(num_pin)
        user.save()
        # add card
        card = CreditCard(num_card=num_card, num_pin=num_pin,
                            expiration_date=utils.generateExpDate(), num_cvv=utils.generateNumCvv())
        card.save()
        # add account
        account = Account(
            num_account=utils.generateNumAccount(), client=Client.objects.get(document_number=getClient), card=CreditCard.objects.get(num_card=num_card))
        account.save()
        return super(SignUpView, self).form_valid(form)
예제 #10
0
파일: views.py 프로젝트: shane-Git/EzMeal
def UserRegHandler(request):
    NewAccount = Account()
    NewAccount.username = request.POST['username'].encode('utf-8')
    NewAccount.password = request.POST['password'].encode('utf-8')
    NewAccount.urtype = request.POST['urtype'].encode('utf-8')
    NewAccount.created = datetime.now()
    NewUser = User()
    NewUser.name = request.POST['name'].encode('utf-8')
    NewUser.mobile = request.POST['mobile'].encode('utf-8')
#    NewUser.address = request.POST['address'].encode('utf-8')
    NewUser.save()
    NewAccount.urid = NewUser.id
    NewAccount.save()
    return HttpResponse(NewAccount.id) 
예제 #11
0
 def create(self, request, *args, **kwargs):
     crypto_obj = get_data(request)
     plain_text = crypto_obj.decrypt_text(request.data['data']).replace(
         '\'', '\"')
     data = json.loads(plain_text)
     data = data if isinstance(data, dict) else {}
     try:
         serializer = self.get_serializer(data=data)
         serializer.is_valid(raise_exception=True)
         data = serializer.validated_data
         password = data.pop('password')
         user = Account(**data)
         user.set_password(password)
         user.save()
         response = crypto_obj.encrypt_text("{}".format(
             {"response": "user created."}))
         return Response({'response': response}, status.HTTP_201_CREATED)
     except IntegrityError as e:
         response = crypto_obj.encrypt_text("{}".format(
             {"response": "This username exist."}))
         return Response({"response": response},
                         status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         response = crypto_obj.encrypt_text("{}".format({'response': e}))
         return Response({'response': response},
                         status=status.HTTP_400_BAD_REQUEST)
예제 #12
0
파일: admin.py 프로젝트: iecruz/qa-bank
def transfer():
    form = TransferForm(request.form)
    if form.validate_on_submit():
        sender_account = Account.get(Account.account_number == form.sender_account_number.data)
        receiver_account = Account.get(Account.account_number == form.receiver_account_number.data)

        Account.update(
            balance = Account.balance - form.amount.data,
            updated_at = datetime.now()
        ).where(Account.account_number == form.sender_account_number.data).execute()

        Account.update(
            balance = Account.balance + form.amount.data,
            updated_at = datetime.now()
        ).where(Account.account_number == form.receiver_account_number.data).execute()

        Transaction.insert(
            account_number = form.sender_account_number.data,
            reference_number = form.receiver_account_number.data,
            amount = form.amount.data,
            type = 'FUND TRANSFER'
        ).execute()
        flash('Fund Transfer successful')
        return redirect(url_for('admin.transfer'))
    return render_template('admin/transfer.html', form=form)
예제 #13
0
파일: admin.py 프로젝트: iecruz/qa-bank
def inquiry():
    form = InquiryForm(request.form)
    account = None
    if form.validate_on_submit():
        account = Account.select(
            User.first_name,
            User.last_name,
            Account.balance,
        ).join(User, attr='user').where(
            (Account.account_number == form.account_number.data)
        ).get()

    return render_template('admin/inquiry.html', form=form, account=account)
예제 #14
0
파일: main.py 프로젝트: iecruz/bank-admin
def withdraw():
    form = TransactionForm(request.form)
    if form.validate_on_submit():
        account = Account.get(
            Account.account_number == form.account_number.data)

        if account.balance - form.amount.data <= 0:
            flash('Withdraw amount is greater than account remaining balance')

        else:
            Account.update(balance=Account.balance - form.amount.data,
                           updated_at=datetime.now()).where(
                               Account.account_number ==
                               form.account_number.data).execute()

            Transaction.insert(account_number=form.account_number.data,
                               reference_number=form.account_number.data,
                               amount=form.amount.data,
                               type='WITHDRAW').execute()
            flash('Withdraw successful')
            return redirect(url_for('main.withdraw'))
    return render_template('main/withdraw.html', form=form)
예제 #15
0
파일: main.py 프로젝트: iecruz/bank-admin
def index():
    time_deposits = TimeDeposit.select().where(
        (TimeDeposit.terminal_date <= datetime.now())
        & (TimeDeposit.deleted == False)).execute()

    for time_deposit in time_deposits:
        Account.update(account=Account.balance +
                       (time_deposit.amount * time_deposit.interest) +
                       time_deposit.amount).where(
                           Account.account_number ==
                           time_deposit.account_number).execute()

        TimeDeposit.update(deleted=True).where(
            TimeDeposit.id == time_deposit.id).execute()

    try:
        log = (Log.select().where((Log.action == 'LOGIN') & (
            Log.user_id == session['user']['id'])).order_by(
                Log.created_at.desc()).get()
               ).created_at.strftime('%d %B %Y %I:%M %p')
    except DoesNotExist:
        log = None
    return render_template('main/index.html', log=log)
예제 #16
0
파일: admin.py 프로젝트: iecruz/qa-bank
def time_deposit():
    form = TimeDepositForm(request.form)
    form.duration.choices = ([
        (3, '3 months (7.0% interest)'),
        (6, '6 months (8.0% interest)'),
        (12, '12 months (9.0% interest)')
    ])

    if form.validate_on_submit():
        interest_ref = {
            3: 7.0,
            6: 8.0,
            12: 9.0
        }

        Account.update(
            balance = Account.balance + form.amount.data,
            updated_at = datetime.now()
        ).where(Account.account_number == form.account_number.data).execute()

        TimeDeposit.insert(
            account_number = form.account_number.data,
            amount = form.amount.data,
            interest = interest_ref[form.duration.data],
            terminal_date = datetime.now() + timedelta(days=form.duration.data*30)
        ).execute()

        Transaction.insert(
            account_number = form.account_number.data,
            reference_number = form.account_number.data,
            amount = form.amount.data,
            type = 'TIME DEPOSIT'
        ).execute()
        flash('Time Deposit successful')
        return redirect(url_for('admin.time_deposit'))
    return render_template('admin/time_deposit.html', form=form)
예제 #17
0
파일: ioc.py 프로젝트: jnaudon/datal
    def process_request(self, request):
        domain = get_domain_by_request(request)
        request.bucket_name = settings.AWS_BUCKET_NAME

        try:
            account = Account.get_by_domain(domain)
        except Account.DoesNotExist:
            logger = logging.getLogger(__name__)
            logger.error('The account do not exists: %s' % domain)
            return HttpResponseForbidden('')

        request.account = account

        preferences = account.get_preferences()
        preferences.load_all()
        preferences['account_id'] = account.id
        request.preferences = preferences

        bucket_name = preferences['account_bucket_name']
        if bucket_name:
            request.bucket_name = bucket_name

        is_signin = False  #Deprecado
        is_login = False  #Deprecado
        is_activate = False  #Deprecado
        is_jsi18n = request.path.startswith('/jsi18n')

        language = request.preferences['account_language']
        if language:
            request.session['django_language'] = language
            request.auth_manager.language = language

        # TODO: Esto debería ir en una url y hacer el redirect
        if settings.DOMAINS['microsites'] == domain:
            if request.META.get('REQUEST_URI') == '/':
                return redirect(
                    get_domain_with_protocol('microsites') + "/home")

        # hacemos que el User sea un AccountAnonymousUser
        # lo creamos con el account y el lenguaje que tenga el account_language
        request.user = AccountAnonymousUser(request.account,
                                            preferences['account_language'])

        return None
예제 #18
0
def signup_page(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('index_page'))

    if request.method == "POST":
        email = request.POST.get('email')
        password = request.POST.get('password')

        if Account.objects.filter(email=email).exists():
            context = {"form_message": {"title": "<span class=\"icon-caution\"></span> SIGNUP ERROR", "message": "Email already exists.", "type": "danger", "animation": "animated shake" }}
            return render(request, 'signup.html', context)

        if not email or not password:
            context = {"form_message": {"title": "<span class=\"icon-caution\"></span> SIGNUP ERROR", "message": "All fields are required.", "type": "danger", "animation": "animated shake" }}
            return render(request, 'signup.html', context)

        try:
            validate_email(email)

        except ValidationError:
            context = {"form_message": {"title": "<span class=\"icon-caution\"></span> SIGNUP ERROR", "message": "Enter a valid email address.", "type": "danger", "animation": "animated shake" }}
            return render(request, 'signup.html', context)
            
        try:
            user = Account()
            user.email = email
            user.set_password(password)
            user.is_activated = False
            user.save()
            Notification.objects.create(account=user, description="Account created.")
            token = ActivationToken(email=email)
            token.save()
            send_activation_token(request, token)
            Notification.objects.create(account=user, description="Activation mail sent.")

        except Exception as e:
            context = {"form_message": {"title": "<span class=\"icon-caution\"></span> SIGNUP ERROR", "message": "Cannot create account. Contact support team.<br/> DEBUG" + str(e), "type": "danger"}
                    }
            return render(request, 'signup.html', context)

        context = {"form_message": {"title": "<span class=\"icon-happy\"></span> SIGNUP SUCCESS", "message": " Activation mail sent.", "type": "success"}}
        return render(request, 'login.html', context)
            

    else:
        return render(request, 'signup.html')
예제 #19
0
파일: ioc.py 프로젝트: anukat2015/datal
    def process_request(self, request):
        domain = get_domain_by_request(request)
        request.bucket_name = settings.AWS_BUCKET_NAME

        try:
            account = Account.get_by_domain(domain)
        except Account.DoesNotExist:
            logger = logging.getLogger(__name__)
            logger.error('The account do not exists: %s' % domain)
            return HttpResponseForbidden('') 

        request.account = account

        preferences = account.get_preferences()
        preferences.load_all()
        preferences['account_id'] = account.id
        request.preferences = preferences

        bucket_name = preferences['account_bucket_name']
        if bucket_name:
            request.bucket_name = bucket_name

        is_signin = False #Deprecado
        is_login = False #Deprecado
        is_activate = False #Deprecado
        is_jsi18n = request.path.startswith('/jsi18n')

        language = request.preferences['account_language']
        if language:
            request.session['django_language'] = language
            request.auth_manager.language = language

        # TODO: Esto debería ir en una url y hacer el redirect
        if settings.DOMAINS['microsites'] == domain:
            if request.META.get('REQUEST_URI') == '/':
                return redirect(get_domain_with_protocol('microsites') + "/home")

        # hacemos que el User sea un AccountAnonymousUser
        # lo creamos con el account y el lenguaje que tenga el account_language
        request.user = AccountAnonymousUser(request.account, preferences['account_language'])

        return None
예제 #20
0
    def process_request(self, request):
        """
        Checks user, role and account
        """

        # for anonymous users
        request.session['django_language'] = settings.LANGUAGES[0][0]

        if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
            user_language = request.META['HTTP_ACCEPT_LANGUAGE'].split(
                ',')[0].split('-')[0]
            if user_language in [
                    language[0] for language in settings.LANGUAGES
            ]:
                request.session['django_language'] = user_language

        request.auth_manager = AuthManager(
            language=request.session['django_language'],
            account=Account.get_by_domain(get_domain_by_request(request)))

        # el user se arma en middlerware.ioc ya que necesitamos el account para completar el user
        request.user = None
        return None
예제 #21
0
    def process_request(self, request):
        domain = get_domain_by_request(request)
        request.bucket_name = settings.AWS_BUCKET_NAME

        try:
            account = Account.get_by_domain(domain)
        except Account.DoesNotExist:
            logger = logging.getLogger(__name__)
            logger.error('The account do not exists: %s' % domain)
            raise AccountDoesNotExist

        request.account = account

        preferences = account.get_preferences()
        preferences.load_all()
        preferences['account_id'] = account.id
        request.preferences = preferences

        bucket_name = preferences['account_bucket_name']
        if bucket_name:
            request.bucket_name = bucket_name

        is_signin = False #Deprecado
        is_login = False #Deprecado
        is_activate = False #Deprecado
        is_jsi18n = request.path.startswith('/jsi18n')

        language = request.preferences['account_language']
        if language:
            request.session['django_language'] = language
            request.auth_manager.language = language

        if settings.DOMAINS['microsites'] == domain:
            if request.META.get('REQUEST_URI') == '/':
                return redirect(get_domain_with_protocol('microsites') + "/home")

        return None
예제 #22
0
파일: account.py 프로젝트: iecruz/qa-bank
def activate(id):
    Account.update(
        deleted=False,
        updated_at=datetime.now()
    ).where(Account.id == id).execute()
    return redirect(url_for('account.index'))
예제 #23
0
파일: teller.py 프로젝트: iecruz/qa-bank
def inquiry():
    balance = "{0:,.2f}".format(Account.get(Account.id == session['atm_auth']).balance)
    return render_template('teller/inquiry.html', balance=balance)
예제 #24
0
def validate_time_deposit(form, field):
    if not Account.get_or_none((Account.account_number == field.data)
                               & (Account.time_deposit == 0)):
        raise ValidationError(
            'Account is currently holding an existing time deposit')
예제 #25
0
def validate_account_number(form, field):
    if not Account.get_or_none((Account.account_number == field.data)
                               & (Account.deleted == False)):
        raise ValidationError('Account is inactivate or does not exists')
예제 #26
0
def validate_receiver_account(form, field):
    if not Account.get_or_none((Account.account_number == field.data)
                               & (Account.type <= 2)):
        raise ValidationError('Account is a time deposit account')
예제 #27
0
def validate_time_deposit(form, field):
    if not Account.get_or_none((Account.account_number == field.data)
                               & (Account.type == 3)):
        raise ValidationError('Account is not a time deposit account')
예제 #28
0
from core.models import Account, IncomeCategory, ExpenseCategory

import json

with open('data.json', 'r') as file:
    data = json.load(file)

for acc in data['account']:
    account = Account(name=acc['name'])
    account.save()

for in_c in data['incomeCategory']:
    incomeCategory = IncomeCategory(name=in_c['name'])
    incomeCategory.save()

for ex_c in data['expenseCategory']:
    expenseCategory = ExpenseCategory(name=ex_c['name'])
    expenseCategory.save()
예제 #29
0
파일: auth.py 프로젝트: mxabierto/datal
    def resolve_account(self, request):
        domain = get_domain_by_request(request)

        # creo que en algun punto desreferencia a Account
        from core.models import Account
        return Account.get_by_domain(domain)
예제 #30
0
    def resolve_account(self, request):
        domain = get_domain_by_request(request)

        # creo que en algun punto desreferencia a Account
        from core.models import Account
        return Account.get_by_domain(domain)
예제 #31
0
        payment_time = int(invoice.date.strftime("%s")) + 14 * DAY_SECONDS
        if payment_time < time.time():
             payment_time = datetime.datetime.utcfromtimestamp(payment_time).replace(tzinfo=pytz.utc)
             payment = Payment(account=account, amount=invoice.amount, date=payment_time)
             payment.save()

delete_all(Invoice)
delete_all(Charge)
delete_all(Payment)
delete_all(Account)
delete_all(UsableObject)

for site in Site.objects.all():
    # only create accounts for sites where some slices exist
    if len(site.slices.all()) > 0:
        account = Account(site=site)
        account.save()

for slice in Slice.objects.all():
    site = slice.site
    account = site.accounts.all()[0]
    serviceClass =slice.serviceClass

    if not (slice.name in ["DnsRedir", "DnsDemux", "HyperCache"]):
        continue

    now = int(time.time())/HOUR_SECONDS*HOUR_SECONDS

    charge_kind=None
    for resource in slice.serviceClass.resources.all():
        if resource.name == "cpu.cores":