Ejemplo n.º 1
0
    def test_cancellation(self):
        Transaction.objects.create(from_user=None,
                                   to_user=self.user,
                                   amount=10000000,
                                   verified=True)
        today = date.today()
        for date_pair in (
            (today - timedelta(days=1), today),
            (today + timedelta(days=5), today + timedelta(days=7)),
            (today + timedelta(days=10), today + timedelta(days=12)),
            (today + timedelta(days=15), today + timedelta(days=17)),
        ):
            self.selenium_client.get(
                '/reservation/{}/?from_date={}&to_date={}'.format(
                    self.habitat.id, *date_pair))
            button = self.selenium_client.web_driver.find_elements_by_tag_name(
                'input')[-1]
            button.location_once_scrolled_into_view
            button.click()
            sleep(1)
            button = self.selenium_client.web_driver.find_element_by_link_text(
                'بله')
            button.location_once_scrolled_into_view
            button.click()
            sleep(1)
        self.assertEqual(Transaction.get_balance_from_user(self.user),
                         10000000 - self.cost_per_day * 6)

        # do a little stupid thing to travel in the time
        for reservation in Reservation.objects.all():
            reservation.from_date -= timedelta(days=5)
            reservation.to_date -= timedelta(days=5)
            reservation.save()

        self.selenium_client.get('/reservation/list')

        cancel_buttons = self.get_cancel_buttons()
        self.assertEqual(len(cancel_buttons), 2)

        cancel_buttons[0].click()
        sleep(1)

        cancel_buttons = self.get_cancel_buttons()
        self.assertEqual(len(cancel_buttons), 1)

        cancel_buttons[0].click()
        sleep(1)

        cancel_buttons = self.get_cancel_buttons()
        self.assertEqual(len(cancel_buttons), 0)

        punishment = self.cost_per_day * 2 * settings.CANCELLATION_FEE * 5
        self.assertEqual(Transaction.get_balance_from_user(self.user),
                         10000000 - self.cost_per_day * 2 - punishment)

        self.assertEqual(
            Transaction.get_balance_from_user(self.habitat_owner_user),
            self.cost_per_day * 2 * (1 - settings.RESERVATION_FEE) +
            punishment)
Ejemplo n.º 2
0
def adduser(request):
    email = request.session.get('email', None)
    user_type = request.session.get('user_type', None)
    if email and user_type == 1:
        if request.method == "POST":
            first_name = request.POST.get('first_name', None)
            last_name = request.POST.get('last_name', None)
            email = request.POST.get('email', None)
            address = request.POST.get('address', None)
            password = request.POST.get('password', None)
            amount = request.POST.get('amount', None)
            context_dict = dict()
            if (first_name == '') or (last_name == '') or (email == '') or (address == '') or (password == '' )or (amount == '' ):
                context_dict['messages'] = "First name, Last name, email, password, Amount, address can't be empty. all fields required."
                context_dict['status'] = 0
            else:
                check_email = email__exist(email)
                if check_email:
                    context_dict['messages'] = "This email is already registered please enter another one."
                    context_dict['status'] = 0
                else:
                    gmt = time.gmtime()
                    userData = AuthUser()
                    dataDeposit = Deposit()
                    accuntData = CustomerAccountdetail()
                    tran = Transaction()
                    userData.first_name = first_name.capitalize()
                    userData.last_name = last_name
                    userData.email = email.capitalize()
                    userData.password = make_password(password,salt=None,hasher='default')
                    userData.username = email
                    userData.is_superuser = 2
                    userData.is_staff = 1
                    userData.is_active = 1
                    userData.date_joined = datetime.now()
                    userData.save()
                    # print(userData.id)
                    accuntData.address = address
                    accuntData.account_no = calendar.timegm(gmt)
                    accuntData.acc_user_id = userData.id
                    accuntData.created = datetime.now()
                    accuntData.save()
                    dataDeposit.amount += int(amount)
                    dataDeposit.date = datetime.now()
                    dataDeposit.dep_user_id = userData.id
                    dataDeposit.save()
                    tran.amount = amount
                    tran.account_no = accuntData.account_no
                    tran.tran_type = 'Deposit'
                    tran.date = datetime.now()
                    tran.tran_user_id = userData.id
                    tran.save()
                    context_dict['messages'] = "Successfully Created Account."
                    context_dict['status'] = 1
            return JsonResponse(context_dict)
    elif email:
        return HttpResponseRedirect('/account/summary')
    else:
        return HttpResponseRedirect('/')
Ejemplo n.º 3
0
def send_money(request):
    request_details = request.data
    try:
        amount = decimal.Decimal(request_details['amount'])
        sender = User.objects.get(email=request_details['sender'])
        receiver = User.objects.get(email=request_details['receiver'])
    except ObjectDoesNotExist:
        return Response({'error': 'Account Does Not Exist'},
                        status=status.HTTP_404_NOT_FOUND)

    if request_details['sender'] == request_details['receiver']:
        return Response({'error': 'You cannot send to same account'},
                        status=status.HTTP_422_UNPROCESSABLE_ENTITY)
    if amount < 10.0:
        return Response(
            {'error': "Transaction Failed, Amount is less than 10"},
            status=status.HTTP_400_BAD_REQUEST)

    # sender Account deducted
    sender_acc = Account.objects.get(user=sender)
    if sender_acc.balance > amount and sender_acc.balance > 1:

        sender_balance = sender_acc.balance - amount
        sender_acc.balance = sender_balance
        sender_acc.save()

        # receiver Account added
        receiver_acc = Account.objects.get(user=receiver)
        receiver_balance = receiver_acc.balance + amount
        receiver_acc.balance = receiver_balance
        receiver_acc.save()

        # Add transaction
        tran = Transaction(transact_account=sender_acc,
                           sender=sender.email,
                           receiver=receiver.email,
                           amount=amount,
                           transaction_type="send")
        tran.save()

        push_notify(
            "Wallet Transaction successful",
            str("Transfer cash of Ksh " + str(amount) + " From " +
                str(sender.email) + " To " + str(receiver.email)))
        return Response({'success': "Transaction successful"})
    else:
        return Response(
            {
                'error':
                "You have insufficient Amount in account to complete the transaction"
            },
            status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 4
0
def transaction_for_account(request):
    if request.user.is_authenticated():
        json_obj = json.loads(request.body)
        data = json_obj['data']
        Acc_list = data.get("Acc_list")
        transaction_date = data.get("transaction_date")
        transactiontype = data.get("transactiontype")
        transactiontype_obj = TransactionType(optionType=transactiontype)
        transactiontype_obj.save()
        user_obj = User.objects.get(id=request.user.id)
        transaction_date = datetime.datetime.fromtimestamp(transaction_date/1000)
        description = data.get("description")
        try:
            accountingyear_obj = AccountingYear.objects.get(start_date__lte=transaction_date,end_date__gte=transaction_date,user__id=request.user.id)
        except AccountingYear.DoesNotExist:
            if transaction_date <= datetime.datetime(transaction_date.year, 03, 31, 23, 59, 59):
                start_date = datetime.datetime(transaction_date.year-1, 04, 01, 00, 00, 00)
                end_date = datetime.datetime(transaction_date.year, 03, 31, 23, 59, 59)
                user_obj = User.objects.get(id=request.user.id)
                accountingyear_obj = AccountingYear(start_date=start_date,end_date=end_date,duration=1,user=user_obj)
                accountingyear_obj.save()
            else:
                year = int(transaction_date.year)
                start_date = datetime.datetime(transaction_date.year, 04, 01, 00, 00, 00)
                end_date = datetime.datetime(transaction_date.year+1, 03, 31, 23, 59, 59)
                user_obj = User.objects.get(id=request.user.id)
                accountingyear_obj = AccountingYear(start_date=start_date,end_date=end_date,duration=1,user=user_obj)
                accountingyear_obj.save()
        transaction_obj = Transaction(transaction_date=transaction_date,description=description,transactiontype=transactiontype_obj,user=user_obj)
        transaction_obj.save()
        accountingyear_obj.transaction.add(transaction_obj)
        accountingyear_obj.save()
        for i in Acc_list:
            amount = i['amount']
            account = i['account']
            account_id = account.get("id")
            is_debit = i['is_debit']
            print is_debit.capitalize()
            if is_debit == "D":
                is_debit = True
            else:
                is_debit = False
            account_obj = Account.objects.get(id=account_id)
            print account_obj
            transactionrecord_queries = TransactionRecord(amount=amount,is_debit=is_debit,account=account_obj)
            transactionrecord_queries.save()
            transaction_obj.transaction_record.add(transactionrecord_queries)
            transaction_obj.save()
        print "Transaction saved Successfully..."
        return HttpResponse(json.dumps({"validation":"Transaction Saved Successfully","status":True}), content_type="application/json")
Ejemplo n.º 5
0
def create_transaction(debit_ledger_entry, credit_ledger_entry):
    transaction = Transaction()
    if debit_ledger_entry:
        transaction.debit_ledger = debit_ledger_entry
        transaction.debit_amount = debit_ledger_entry.debit_amount
        transaction.transaction_ref = debit_ledger_entry.transaction_reference_number
    if credit_ledger_entry:
        transaction.credit_ledger = credit_ledger_entry
        transaction.credit_amount = credit_ledger_entry.credit_amount
        transaction.transaction_ref = credit_ledger_entry.transaction_reference_number
    transaction.save()
    return transaction
Ejemplo n.º 6
0
    def test_login_redirect(self):

        self.selenium_client.logout()

        Transaction.objects.create(from_user=None,
                                   to_user=self.user,
                                   amount=10000000,
                                   verified=True)
        self.selenium_client.get(
            '/reservation/{}/?persons=1&from_date={}&to_date={}'.format(
                self.habitat.id,
                date.today() + timedelta(days=50),
                date.today() + timedelta(days=52),
            ))
        button = self.selenium_client.web_driver.find_elements_by_tag_name(
            'input')[-1]
        button.location_once_scrolled_into_view
        button.click()
        sleep(1)

        self.selenium_client.login_without_navigation('ali', 'hello')
        button = self.selenium_client.web_driver.find_elements_by_tag_name(
            'input')[-1]
        button.location_once_scrolled_into_view
        button.click()
        sleep(1)

        button = self.selenium_client.web_driver.find_element_by_link_text(
            'بله')
        button.location_once_scrolled_into_view
        button.click()
        sleep(1)
        self.assertEqual(Transaction.get_balance_from_user(self.user),
                         10000000 - self.cost_per_day * 2)
Ejemplo n.º 7
0
    def test_withdrawal_request(self):
        # request withdrawal
        self.client.force_login(self.user)
        post_url = self.navigate_to_withdrawal_page()
        amount = self.prior_balance // 2
        response = self.client.post(post_url,
                                    data={'amount': amount},
                                    follow=True)
        self.assertTrue(
            'درخواست شما ثبت شد.' in response.content.decode('utf8'))
        transaction = Transaction.objects.last()
        self.client.logout()

        # approve withdrawal
        self.client.force_login(self.staff_user)
        post_url, response = self.navigate_to_withdrawal_approval_page()
        self.assertTrue(
            transaction.from_user.username in response.content.decode('utf8'))
        self.assertTrue(
            str(transaction.amount) in response.content.decode('utf8'))
        response = self.client.post(post_url,
                                    data={'verified': '1'},
                                    follow=True)
        self.assertFalse(
            str(transaction.amount) in response.content.decode('utf8'))
        transaction.refresh_from_db()
        self.assertTrue(transaction.verified)
        self.assertEqual(Transaction.get_balance_from_user(self.user),
                         self.prior_balance - amount)
Ejemplo n.º 8
0
 def clean(self):
     description = self.cleaned_data.get("description")
     amount = self.cleaned_data.get("amount")
     source = self.cleaned_data.get("sourceiban")
     destinationiban = self.cleaned_data.get("destinationiban")
     if source.user != self.request.user:
         raise ValidationError("This is not your Account")
     try:
         destination = Accounts.objects.get(iban = destinationiban)
     except Accounts.DoesNotExist:
         raise ValidationError("Wrong Destination IBAN")
     if source.amount > amount:
         transaction = Transaction()
         transaction.amount = amount
         transaction.description = description
         transaction.sourceaccount = source
         transaction.destinationaccount = destination
         transaction.currency_type = source.currency_type
         transaction.sending_date = date.today()
         transaction.make_transaction()
     else:
         raise ValidationError("Not Enough Account Balance")
Ejemplo n.º 9
0
    def clean(self):
        cleaned_data = super().clean()
        room_type = cleaned_data.get('room')
        from_date = cleaned_data.get('from_date')
        to_date = cleaned_data.get('to_date')

        if from_date and to_date:
            if to_date <= from_date:
                raise ValidationError('بازه زمانی رزرو صحیح نیست.')
            if room_type:
                if not room_type.has_empty_room(from_date, to_date):
                    raise ValidationError('اتاق در این زمان خالی نیست.')
                days = (to_date - from_date) / timedelta(days=1)
                required_money = room_type.cost_per_night * days
                self.cost = required_money
                balance = Transaction.get_balance_from_user(self.member.user)
                if balance < required_money:
                    self.amount_required = required_money - balance
                    raise ValidationError(
                        'باید حداقل {} در حساب خود داشته باشید. لطفا حساب خود را شارژ کنید.'
                        .format(required_money))
Ejemplo n.º 10
0
def transaction_create(request, account_id):
    account = Account.get_by_id(int(account_id))
    if account is None:
        raise Http404
 
    if request.method == 'POST':
        t = Transaction(parent=account)
        form = TransactionForm(request.POST, instance=t)
        if form.is_valid():
            form.save(commit=False)
            t.setDate()
            t.save()
            logging.info('new transaction created - id: %s key: %s data: %s' % (t.key().id() , t.key(), t))
            return redirect('/accounts/'+account_id+'/transactions/')
    else:
        form = TransactionForm() 

    return render_to_response('accounts/transaction_create.html', RequestContext(request, { 'form':form }))
Ejemplo n.º 11
0
    @staticmethod
    @non_recurse
    def update():
        today = date.today()
        Transaction.objects.filter(fee_reservations__from_date__lte=today,
                                   fee_reservations__is_active=True,
                                   verified=False).update(verified=True)

    def __str__(self):
        return 'رزرو اتاق {} در اقامتگاه {}، از تاریخ {} تا {} با هزینهٔ {}'.format(
            self.room, self.room.habitat, self.from_date, self.to_date,
            self.cost)


Transaction.register_observer(Reservation)


class ReservationComment(models.Model):
    reservation = models.OneToOneField(to='reservation.Reservation',
                                       on_delete=models.CASCADE,
                                       related_name='comment',
                                       verbose_name='رزرو')

    rating = models.IntegerField(
        null=True,
        validators=[MinValueValidator(1),
                    MaxValueValidator(5)],
        verbose_name='امتیاز')
    review = models.TextField(null=True, verbose_name='متن نظر')
    created_at = models.DateTimeField(auto_now_add=True,
Ejemplo n.º 12
0
def task_do_clearance(request, clearance_id):
    logging.info('task do clearance - clearance_id=%s'%clearance_id)
    clearance = Clearance.get_by_id(int(clearance_id))
    if clearance is None:
        raise Http404

    logging.info('clearance = %s'%clearance)


         
    items = ClearanceItem.objects.all().ancestor(clearance)
    for i in items:
        logging.info('i=%s'%i) 
        if not (i.transaction_item is None):
            logging.info('has transaction...')
            if not i.clear:
                logging.info('but,not clear...')
                i.clear = True
                i.save()
                logging.info('cleared')
        else:
            tr = Transaction.objects.all().filter('clearance_item_key =', i.key()).get()
            if not (tr is None):
                logging.info('corresponding transaction found (%s)'%tr)
                i.transaction_item=tr
                logging.info('linked')
            else:
                logging.info('no corresponding transaction found')
                tr = Transaction(parent=i.account)
                tr.setDate()
                tr.clearance_item_key = i.key()
                if i.purpose == 'pick':
                    logging.info('pick item')
                    tr.purpose = 'payment'
                    tr.order_item_key = i.order_item.key()
                    tr.amount = -i.cost
                    tr.desc = i.desc
                elif i.purpose == 'give':
                    logging.info('give item')
                    tr.purpose = 'payment'
                    tr.amount = -i.cost
                    tr.desc = i.desc
                elif i.purpose == 'deposit':  
                    logging.info('deposit item')
                    tr.purpose = 'deposit'
                    tr.amount = i.cost
                    tr.desc = i.desc
                elif i.purpose == 'load':
                    logging.info('load item')
                    tr.purpose = 'deposit'
                    tr.amount = i.cost
                    tr.desc = i.desc
                else:
                    logging.info('unexpected purpose (%s)'%i.purpose)
                    tr = None

                logging.info('new tr=%s'%tr)
                if not (tr is None):
                    tr.save()
                    logging.info('tr save ok %s'%tr) 
                    i.transaction_item = tr
                    i.clear = True
                
            i.save()    
            logging.info('new tr=%s'%tr)
                


    logging.info('unlock clearance') 
    clearance.status = 'closed'
    clearance.lock = False
    clearance.clear = True
    clearance.save()

    return HttpResponse('ok')
Ejemplo n.º 13
0
 def balance(self):
     return Transaction.get_balance_from_user(self.user)
Ejemplo n.º 14
0
 def clean_amount(self):
     amount = self.cleaned_data['amount']
     if amount > Transaction.get_balance_from_user(self.request.user):
         raise ValidationError('مبلغ بیش از موجودی حساب شماست.')
     return amount
Ejemplo n.º 15
0
    def close_accounts(self, request):
        accounts = Account.objects.filter(is_active=True,
                                          account_type__category__in=[2, 3, 4])

        income_value = 0
        debits = []
        credits = []
        has_income_adjustment = False

        closing_journal = JournalEntry(
            date=timezone.now(),
            creator=request.user,
            description="Auto-generated closing journal",
            entry_type=JournalEntryTypes.CLOSING,
            is_approved=None)
        closing_journal.save()

        for account in accounts:
            balance = account.get_balance()
            if balance == 0:
                # No need to close an account that does not have a balance
                continue

            closer = Transaction(affected_account=account,
                                 journal_entry=closing_journal,
                                 is_debit=not account.is_debit(),
                                 value=abs(balance))

            if account.account_type.category == 3 or account.account_type.category == 4:
                has_income_adjustment = True

                if closer.is_debit:
                    debits.append(closer)
                else:
                    credits.append(closer)

                income_value += closer.get_value()

            elif account.account_type.category == 2 and "Drawing" in account.name:
                # NOTE: We are only accounting for business owner equity here, not shareholders equity.
                try:
                    equity_adjuster = Account.objects.get_by_natural_key(
                        account.name.replace("Drawing", "Capital"))

                    if not equity_adjuster.is_active:
                        equity_adjuster.is_active = True
                        equity_adjuster.save()

                except Model.DoesNotExist:
                    closing_journal.delete()

                    return Response({
                        'message': 'The Drawing account "%s" does not have a corresponding Capital account to adjust.' % \
                            account.name }, status=403)

                debits.append(
                    Transaction(affected_account=equity_adjuster,
                                journal_entry=closing_journal,
                                value=abs(balance),
                                is_debit=True))
                credits.append(closer)

        if not len(debits) and not len(credits):
            closing_journal.delete()
            return Response({'message': 'Accounts have already been closed.'},
                            status=200)

        if has_income_adjustment:
            try:
                income_account = Account.objects.get_by_natural_key(
                    'Retained Earnings')

                if not income_account.is_active:
                    income_account.is_active = True
                    income_account.save()

            except Model.DoesNotExist:
                closing_journal.delete()

                return Response(
                    {
                        'message':
                        'There is no acccount named "Retaining Earnings".'
                    },
                    status=403)

            income_adjuster = Transaction(affected_account=income_account,
                                          journal_entry=closing_journal,
                                          value=abs(income_value))
            income_adjuster.is_debit = income_value < 0  # if income_value is positive, it debits the Retained Earnings else credits

            if income_adjuster.is_debit:
                debits.append(income_adjuster)
            else:
                credits.append(income_adjuster)

        transaction_list = debits + credits
        for transaction in transaction_list:
            transaction.save()

        return Response({'message': 'Closing Entry has been created.'},
                        status=200)
Ejemplo n.º 16
0
def transaction_for_account(request):
    if request.user.is_authenticated():
        json_obj = json.loads(request.body)
        data = json_obj['data']
        Acc_list = data.get("Acc_list")
        transaction_date = data.get("transaction_date")
        transactiontype = data.get("transactiontype")
        transactiontype_obj = TransactionType(optionType=transactiontype)
        transactiontype_obj.save()
        user_obj = User.objects.get(id=request.user.id)
        transaction_date = datetime.datetime.fromtimestamp(transaction_date /
                                                           1000)
        description = data.get("description")
        try:
            accountingyear_obj = AccountingYear.objects.get(
                start_date__lte=transaction_date,
                end_date__gte=transaction_date,
                user__id=request.user.id)
        except AccountingYear.DoesNotExist:
            if transaction_date <= datetime.datetime(transaction_date.year, 03,
                                                     31, 23, 59, 59):
                start_date = datetime.datetime(transaction_date.year - 1, 04,
                                               01, 00, 00, 00)
                end_date = datetime.datetime(transaction_date.year, 03, 31, 23,
                                             59, 59)
                user_obj = User.objects.get(id=request.user.id)
                accountingyear_obj = AccountingYear(start_date=start_date,
                                                    end_date=end_date,
                                                    duration=1,
                                                    user=user_obj)
                accountingyear_obj.save()
            else:
                year = int(transaction_date.year)
                start_date = datetime.datetime(transaction_date.year, 04, 01,
                                               00, 00, 00)
                end_date = datetime.datetime(transaction_date.year + 1, 03, 31,
                                             23, 59, 59)
                user_obj = User.objects.get(id=request.user.id)
                accountingyear_obj = AccountingYear(start_date=start_date,
                                                    end_date=end_date,
                                                    duration=1,
                                                    user=user_obj)
                accountingyear_obj.save()
        transaction_obj = Transaction(transaction_date=transaction_date,
                                      description=description,
                                      transactiontype=transactiontype_obj,
                                      user=user_obj)
        transaction_obj.save()
        accountingyear_obj.transaction.add(transaction_obj)
        accountingyear_obj.save()
        for i in Acc_list:
            amount = i['amount']
            account = i['account']
            account_id = account.get("id")
            is_debit = i['is_debit']
            print is_debit.capitalize()
            if is_debit == "D":
                is_debit = True
            else:
                is_debit = False
            account_obj = Account.objects.get(id=account_id)
            print account_obj
            transactionrecord_queries = TransactionRecord(amount=amount,
                                                          is_debit=is_debit,
                                                          account=account_obj)
            transactionrecord_queries.save()
            transaction_obj.transaction_record.add(transactionrecord_queries)
            transaction_obj.save()
        print "Transaction saved Successfully..."
        return HttpResponse(json.dumps({
            "validation": "Transaction Saved Successfully",
            "status": True
        }),
                            content_type="application/json")