Ejemplo n.º 1
0
def create(journal_entry=None,
           account=None,
           debit=Decimal('0'),
           credit=Decimal('0'),
           transaction_date=None,
           description=None):

    assert isinstance(journal_entry,
                      JournalEntry), "Must be a Journal Entry instance"
    assert isinstance(account, Account), "Must be a Account instance"

    logger.debug(debit)
    logger.debug(credit)

    t = Transaction(journal_entry=journal_entry,
                    account=account,
                    description=description,
                    debit=debit,
                    credit=credit)

    if transaction_date:
        t.transaction_date = datetime.now()

    t.save()

    return t
def save_transaction(request):
    if request.method == "POST":
        data = json.loads(request.body)
        user = CustomUser.objects.get(pk=request.user.pk)
        txn_id = request.user.username + "-" + timezone.datetime.today(
        ).isoformat() + "-" + str(random.randint(0, 10000000))
        bank_info = {
            'bank': data['bank'],
            'bank_acc_no': data['bank_acc_no'],
            'real_name': data['real_name']
        }
        status = 2 if data['type'] == 0 else 3
        try:
            txn = Transaction(
                transaction_id=txn_id,
                user_id=user,
                amount=data['amount'],
                currency=data['currency'],
                method="Local Bank Transfer",
                transaction_type=data['type'],
                bank_info=bank_info,
                channel=11,  # 11 = LBT
                status=status)
            txn.save()
            return JsonResponse({'success': True, 'transaction_id': txn_id})
        except Exception as e:
            logger.error(repr(e))
            return JsonResponse({'success': False, 'transaction_id': None})
Ejemplo n.º 3
0
def insert_transaction_for_payment(sender, instance, **kwargs):
    if instance.approved:
        note = note_from_month(instance.paid_month.month, instance.for_membership)
        transaction = Transaction(amount=instance.amount, realized_date=instance.payment_date,
                                  created_by=instance.updated_by, updated_by=instance.updated_by,
                                  note=note, type_id=1, media=instance.media)
        transaction.save()
        
Ejemplo n.º 4
0
def insert_transaction_for_payment(sender, instance, **kwargs):
    if instance.approved:
        note = note_from_month(instance.paid_month.month,
                               instance.for_membership)
        transaction = Transaction(amount=instance.amount,
                                  realized_date=instance.payment_date,
                                  created_by=instance.updated_by,
                                  updated_by=instance.updated_by,
                                  note=note,
                                  type_id=1,
                                  media=instance.media)
        transaction.save()
Ejemplo n.º 5
0
 def do_transaction(self, source, dest, amount):
     transaction = Transaction()
     transaction.relation = self.relation
     transaction.date = datetime.strptime('2012-01-01:00:00:00', '%Y-%m-%d:%H:%M:%S')
     transaction.account = source
     transaction.transfer = dest
     transaction.description = 'Monies!'
     transaction.amount = amount
     transaction.save()
def save_momopay(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            user = CustomUser.objects.get(pk=request.user.pk)
            txn_id = request.user.username + "-" + timezone.datetime.today(
            ).isoformat() + "-" + str(random.randint(0, 10000000))
            txn = Transaction(
                transaction_id=txn_id,
                user_id=user,
                amount=data['amount'],
                currency=7,
                method="Momo Pay",
                transaction_type=data['type'],
                channel=12,  # 11 = LBT
                status=2)
            txn.save()
            return JsonResponse({'success': True, 'transaction_id': txn_id})
        except Exception as e:
            logger.error(repr(e))
            return JsonResponse({'success': False, 'transaction_id': None})
Ejemplo n.º 7
0
    def post(self, request, *args, **kwargs):
        resp = super(PaymentCreateView, self).post(request, *args, **kwargs)
        p = Payment.objects.latest('pk')
        if request.POST.get('create_transaction', False):
            Transaction(
                date=p.date,
                amount=p.invoice.total,
                memo="transaction concluded from payment number: " + str(p.pk),
                reference="transaction concluded from payment number: " +
                str(p.pk),
                credit=Account.objects.get(name="Current Account"),
                debit=Account.objects.get(name="Accounts Receivable"),
                Journal=Journal.objects.first()  # change this!
            ).save()

        return resp
Ejemplo n.º 8
0
    def post(self, request, *args, **kwargs):
        resp = super(InvoiceCreateView, self).post(request, *args, **kwargs)
        inv = Invoice.objects.latest("pk")
        for item in request.POST.getlist("items[]"):
            pk, quantity = tuple(item.split("-"))
            inv.items.create(quantity=quantity, item=Item.objects.get(pk=pk))

        if request.POST.get('create_transaction', False):
            Transaction(
                date=inv.date,
                amount=inv.total,
                memo="transaction concluded from invoice number: " +
                str(inv.pk),
                reference="transaction concluded from invoice number: " +
                str(inv.pk),
                credit=Account.objects.get(name="Accounts Receivable"),
                debit=Account.objects.get(name="General Sales"),
                Journal=Journal.objects.first()  # change this!
            ).save()

        return resp
Ejemplo n.º 9
0
    def post(self, request, *args, **kwargs):
        resp = super(OrderCreateView, self).post(request, *args, **kwargs)
        items = request.POST.getlist("items[]")
        order = models.Order.objects.latest('pk')

        for item in items:
            print item
            pk, price, quantity = item.split('-')
            order.items.create(item=models.Item.objects.get(pk=pk),
                               quantity=quantity,
                               order_price=price)

        #determine accounts based on order status
        debit = None
        credit = None
        if order.status == 'draft':
            pass
        elif order.status == 'submitted':
            debit = Account.objects.get(name='Current Account')
            credit = Account.objects.get(name='Accounts Receivable')
        else:  # received
            debit = Account.objects.get(name='Accounts Receivable')
            credit = Account.objects.get(name='Inventory')

        if request.POST.get('create_transaction', False) and debit:
            Transaction(
                date=order.issue_date,
                amount=order.total,
                memo="transaction derived from order number: " + str(order.pk),
                reference="transaction derived from order number: " +
                str(order.pk),
                credit=credit,
                debit=debit,
                Journal=Journal.objects.first()  # change this!
            ).save()

        return resp
Ejemplo n.º 10
0
def transaction_data(request):
    """ AJAX handler for transaction data in the transaction view """

    # New transactions come in through a POST request
    if request.method == "POST": 
        response = json.loads(request.raw_post_data, parse_float=Decimal)

        # Catch phony record creation request.
        if response['date'] == None:
            return HttpResponse('')

        # Insert the main transaction
        transaction = Transaction()
        transaction.account = Account.objects.get(pk=int(request.GET['account']))
        transaction.date = datetime.strptime(response['date'], '%Y-%m-%dT%H:%M:%S')
        transaction.transfer = Account.objects.get(pk=int(response['transfer']))
        transaction.description = response['description']
        if response['relation'] != 0:
            transaction.relation = Relation.objects.get(pk=int(response['relation']))
        transaction.amount = Decimal(response['amount'])
        transaction.save()

        response['transfer_display'] = '%s %s' % (transaction.transfer.number, transaction.transfer.name)
        response['id'] = transaction.id
        if transaction.relation != None:
            response['relation_display'] = transaction.relation.displayname

        return HttpResponse(json.dumps({ 'success': True, 'data': response }))
    
    # Existing transactions come in through a PUT request on /transactiondata/id
    elif request.method == "PUT":
        response = json.loads(request.raw_post_data, parse_float=Decimal)

        transaction = Transaction.objects.get(pk=response['id'])
        transaction.date = datetime.strptime(response['date'], '%Y-%m-%dT%H:%M:%S')
        transaction.transfer = Account.objects.get(pk=int(response['transfer']))
        transaction.description = response['description']
        transaction.amount = Decimal(response['amount'])

        if response['relation']:
            transaction.relation = Relation.objects.get(pk=int(response['relation']))
        transaction.save()


        response['transfer_display'] = '%s %s' % (transaction.transfer.number, transaction.transfer.name)
        if transaction.relation != None:
            response['relation_display'] = transaction.relation.displayname
        else:
            response['relation_display'] = ''

        return HttpResponse(json.dumps({ 'success': True, 'data': response }))

    # A delete  is done via DELETE /transactiondata/id
    elif request.method == "DELETE":
        response = json.loads(request.raw_post_data, parse_float=Decimal)

        transaction = Transaction.objects.get(pk=response['id'])

        # Delete the related transaction first (There can be only one!)
        assert transaction.related.count() == 1
        for related in transaction.related.all():
            related.delete()
        transaction.delete()

        return HttpResponse(json.dumps({ 'success': True }))

    # Requesting transactions is done via GET /transactiondata?account=..
    else:
        transactions = Transaction.objects.filter(account=request.GET['account'])
        # XXX May want to change this to use simplejson
        response = '{success:true,data:['
        for transaction in transactions:
            response += '{id:%d,' % transaction.id
            response += 'date:"%s",' % transaction.date
            response += 'transfer:%d,' % transaction.transfer.id
            response += 'transfer_display:"%s %s",' % (transaction.transfer.number, transaction.transfer.name)
            response += 'description:"%s",' % transaction.description
            if transaction.relation != None:
                response += 'relation:%d,' % transaction.relation.id
                response += 'relation_display:"%s",' % transaction.relation.displayname
            else:
                response += 'relation:null,'
                response += 'relation_display:"",'
            response += 'amount:%s},' % transaction.amount
        response += ']}'

        return HttpResponse(response)
Ejemplo n.º 11
0
    def post(self, request): # user will need to submit bank acc information
        data = json.loads(request.body)
        username = request.user.username

        try:
            user = CustomUser.objects.get(username=username)
            withdraw_password = data.get("withdrawPassword")
            
            # toBankAccountName = 'orion'
            # toBankAccountNumber = '12345123'
            toBankAccountName = data.get("toBankAccountName")
            toBankAccountNumber = data.get("toBankAccountNumber")

            amount = float(data.get("amount"))
            currency = data.get("currency") or 2 # 2 = THB, 8 = VND
            currency = int(currency)
            trans_id = username+"-"+timezone.datetime.today().isoformat()+"-"+str(random.randint(0, 10000000))
            # trans_id = "orion-"+timezone.datetime.today().isoformat()+"-"+str(random.randint(0, 10000000))
            ip = helpers.get_client_ip(request)
            bank = data.get("bank")

            user_id=user.pk
            
            merchant_code = '123'
            secret_key = '123'
            payoutURL = '123'
            
            if currency == 2:
                merchant_code = HELP2PAY_MERCHANT_THB
                secret_key = HELP2PAY_SECURITY_THB
                payoutURL = H2P_PAYOUT_URL_THB
                
            elif currency == 8:
                merchant_code = HELP2PAY_MERCHANT_VND
                secret_key = HELP2PAY_SECURITY_VND
                payoutURL = H2P_PAYOUT_URL_VND
            
            
            strAmount = str('%.2f' % amount)
            
            utc_datetime = datetime.datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
            Datetime = utc_datetime.strftime("%Y-%m-%d %H:%M:%S%p")
            key_time = utc_datetime.strftime("%Y%m%d%H%M%S")
          
            secretMsg = merchant_code+trans_id+str(user_id)+strAmount+currencyConversion[currency]+key_time+toBankAccountNumber+secret_key
            
            checksum = MD5(secretMsg)
       
            if check_password(withdraw_password, user.withdraw_password):
                try:
                    db_currency_code = 7 if currency == 8 else 2
                    withdraw_request = Transaction(
                        transaction_id=trans_id,
                        amount=amount,
                        user_id=user,
                        method='Bank Transfer',
                        currency=currency,
                        transaction_type=TRANSACTION_WITHDRAWAL,
                        channel=0,
                        request_time=timezone.now(),
                        other_data={'checksum': checksum}
                    )
                    withdraw_request.save()
                    logger.info("Withdraw request created: " + str(withdraw_request))

                    can_withdraw = helpers.addOrWithdrawBalance(username, amount, "withdraw")

                    if can_withdraw:
                        data = {
                            "Key": checksum,
                            "ClientIP": ip,
                            "ReturnURI": HELP2PAY_RETURN_URL,
                            "MerchantCode": merchant_code,
                            "TransactionID": str(trans_id),
                            "MemberCode": user_id,
                            "CurrencyCode": currencyConversion[currency],
                            "Amount": amount,
                            "TransactionDateTime": Datetime,
                            "BankCode": bank,
                            "toBankAccountName": toBankAccountName,
                            "toBankAccountNumber": toBankAccountNumber,
                        }

                        r = requests.post(payoutURL, data=data)
                        
                        if r.status_code == 200:
                            return HttpResponse(r.content, content_type="text/xml")
                        else:
                            return JsonResponse({
                                'status_code': ERROR_CODE_FAIL,
                                'message': 'Payment service unavailable'

                            })
                    else:
                        return JsonResponse({
                            'status_code': ERROR_CODE_FAIL,
                            'message': 'Insufficient funds'
                        })
                except (ObjectDoesNotExist, IntegrityError, DatabaseError) as e:
                    logger.critical("FATAL__ERROR::Help2Pay::Exception occured when submitting a payout request", exc_info=1)
                    return HttpResponse(status=500)
            else:
                logger.error("withdraw password is not correct.")    
                return JsonResponse({
                    'status_code': ERROR_CODE_INVALID_INFO,
                    'message': 'Withdraw password is not correct.'
                })
                
        except ObjectDoesNotExist as e:
            logger.error(repr(e))
            return HttpResponse(status=500)