def account2(bucket):
    account = Account("Testing Account",
                      "This is a second testing account",
                      bucket=bucket)
    uid = account.uid()
    assert (uid is not None)
    assert (account.balance() == 0)
    assert (account.liability() == 0)

    account.set_overdraft_limit(account2_overdraft_limit)
    assert (account.get_overdraft_limit() == account2_overdraft_limit)

    return account
    def perform_transaction(key, result):
        delta1 = zero
        delta2 = zero
        auth = Authorisation()

        # need to work with thread-local copies of the accounts
        my_account1 = Account(uid=account1.uid())
        my_account2 = Account(uid=account2.uid())

        for i in range(0, 5):
            transaction = Transaction(value=create_decimal(random.random()),
                                      description="Transaction %d" % i)

            if random.randint(0, 1):
                Ledger.perform(transaction, my_account1, my_account2, auth)
                delta1 -= transaction.value()
                delta2 += transaction.value()
            else:
                Ledger.perform(transaction, my_account2, my_account1, auth)
                delta1 += transaction.value()
                delta2 -= transaction.value()

        with rlock:
            result[key] = (delta1, delta2)
def account2(bucket):
    if not have_freezetime:
        return None

    with freeze_time(start_time) as frozen_datetime:
        now = datetime.datetime.now()
        assert (frozen_datetime() == now)
        account = Account("Testing Account", "This is the test account")

        uid = account.uid()
        assert (uid is not None)
        assert (account.balance() == 0)
        assert (account.liability() == 0)

        account.set_overdraft_limit(account2_overdraft_limit)
        assert (account.get_overdraft_limit() == account2_overdraft_limit)

    return account
Example #4
0
def account1(bucket):
    push_is_running_service()
    accounts = Accounts(user_guid=account1_user)
    account = Account(name="Testing Account",
                      description="This is the test account",
                      group_name=accounts.name(),
                      bucket=bucket)
    uid = account.uid()
    assert (uid is not None)
    assert (account.balance() == Balance())

    account.set_overdraft_limit(account1_overdraft_limit)
    assert (account.get_overdraft_limit() == account1_overdraft_limit)
    pop_is_running_service()

    return account
def account1(bucket):
    if not have_freezetime:
        return None

    with freeze_time(start_time) as _frozen_datetime:
        now = get_datetime_now()
        assert (start_time == now)
        push_is_running_service()
        accounts = Accounts(user_guid=account1_user)
        account = Account(name="Testing Account",
                          description="This is the test account",
                          group_name=accounts.name())
        uid = account.uid()
        assert (uid is not None)
        assert (account.balance() == Balance())

        account.set_overdraft_limit(account1_overdraft_limit)
        assert (account.get_overdraft_limit() == account1_overdraft_limit)
        pop_is_running_service()

    return account
    def perform_transaction(key, result):
        delta1 = zero
        delta2 = zero

        # need to work with thread-local copies of the accounts
        my_account1 = Account(uid=account1.uid())
        my_account2 = Account(uid=account2.uid())

        for i in range(0, 10):
            transaction = Transaction(value=create_decimal(random.random()),
                                      description="Transaction %d" % i)

            if random.randint(0, 1):
                auth = Authorisation(
                    resource=transaction.fingerprint(),
                    testing_key=testing_key,
                    testing_user_guid=my_account1.group_name())

                Ledger.perform(transaction=transaction,
                               debit_account=my_account1,
                               credit_account=my_account2,
                               authorisation=auth)
                delta1 -= transaction.value()
                delta2 += transaction.value()
            else:
                auth = Authorisation(
                    resource=transaction.fingerprint(),
                    testing_key=testing_key,
                    testing_user_guid=my_account2.group_name())

                Ledger.perform(transaction=transaction,
                               debit_account=my_account2,
                               credit_account=my_account1,
                               authorisation=auth)
                delta1 += transaction.value()
                delta2 -= transaction.value()

        with rlock:
            result[key] = (delta1, delta2)
Example #7
0
def run(args):
    """This function is called to handle request to cash cheques. This
       will verify that the cheque is valid and will then create
       the debit/credit note pair for the transation. It will return
       the CreditNote to the caller so they can see that the funds have
       been reserved, and can receipt the transaction once goods/services
       have been delivered.

       Args:
            args (dict): information for payment for service

        Returns:
            dict: contains status, status message and credit note if valid

    """

    credit_notes = []

    try:
        cheque = args["cheque"]
    except:
        raise ValueError("You must supply a cheque to be cashed!")

    try:
        cheque = Cheque.from_data(cheque)
    except Exception as e:
        from Acquire.Service import exception_to_string
        raise TypeError("Unable to interpret the cheque.\n\nCAUSE: %s" %
                        exception_to_string(e))

    try:
        spend = args["spend"]
    except:
        spend = None

    if spend is not None:
        try:
            spend = string_to_decimal(spend)
        except Exception as e:
            from Acquire.Service import exception_to_string
            raise TypeError("Unable to interpret the spend.\n\nCause: %s" %
                            exception_to_string(e))

    try:
        resource = str(args["resource"])
    except:
        raise ValueError(
            "You must supply a string representing the resource that will "
            "be paid for using this cheque")

    try:
        account_uid = str(args["account_uid"])
    except:
        raise ValueError("You must supply the UID of the account to which the "
                         "cheque will be cashed")

    try:
        receipt_by = args["receipt_by"]
    except:
        raise ValueError(
            "You must supply the datetime by which you promise to "
            "receipt this transaction")

    try:
        receipt_by = string_to_datetime(receipt_by)
    except Exception as e:
        from Acquire.Service import exception_to_string
        raise TypeError(
            "Unable to interpret the receipt_by date.\n\nCAUSE: %s" %
            exception_to_string(e))

    # now read the cheque - this will only succeed if the cheque
    # is valid, has been signed, has been sent from the right
    # service, and was authorised by the user, the cheque
    # has not expired and we are the
    # service which holds the account from which funds are drawn
    info = cheque.read(resource=resource, spend=spend, receipt_by=receipt_by)

    try:
        description = str(args["description"])
    except:
        description = info["resource"]

    authorisation = info["authorisation"]
    auth_resource = info["auth_resource"]
    user_guid = authorisation.user_guid()

    # the cheque is valid
    bucket = get_service_account_bucket()

    try:
        debit_account = Account(uid=info["account_uid"], bucket=bucket)
    except Exception as e:
        from Acquire.Service import exception_to_string
        raise PaymentError("Cannot find the account associated with the cheque"
                           "\n\nCAUSE: %s" % exception_to_string(e))

    try:
        credit_account = Account(uid=account_uid, bucket=bucket)
    except Exception as e:
        from Acquire.Service import exception_to_string
        raise PaymentError(
            "Cannot find the account to which funds will be creditted:"
            "\n\nCAUSE: %s" % exception_to_string(e))

    # validate that this account is in a group that can be authorised
    # by the user (this should eventually go as the ACLs now allow users
    # to authorised payments from many accounts)
    accounts = Accounts(user_guid=user_guid)
    if not accounts.contains(account=debit_account, bucket=bucket):
        raise PermissionError(
            "The user with UID '%s' cannot authorise transactions from "
            "the account '%s' as they do not own this account." %
            (user_guid, str(debit_account)))

    transaction = Transaction(value=info["spend"], description=description)

    # we have enough information to perform the transaction
    # - this is provisional as the service must receipt everything
    transaction_records = Ledger.perform(transactions=transaction,
                                         debit_account=debit_account,
                                         credit_account=credit_account,
                                         authorisation=authorisation,
                                         authorisation_resource=auth_resource,
                                         is_provisional=True,
                                         receipt_by=receipt_by,
                                         bucket=bucket)

    # extract all of the credit notes to return to the user,
    # and also to record so that we can check if they have not
    # been receipted in time...
    credit_notes = []

    for record in transaction_records:
        credit_notes.append(record.credit_note())

    credit_notes = list_to_string(credit_notes)

    receipt_key = "accounting/cashed_cheque/%s" % info["uid"]
    mutex = Mutex(receipt_key, bucket=bucket)

    try:
        receipted = ObjectStore.get_object_from_json(bucket, receipt_key)
    except:
        receipted = None

    if receipted is not None:
        # we have tried to cash this cheque twice!
        mutex.unlock()
        Ledger.refund(transaction_records, bucket=bucket)
    else:
        info = {"status": "needs_receipt", "creditnotes": credit_notes}
        ObjectStore.set_object_from_json(bucket, receipt_key, info)
        mutex.unlock()

    return {"credit_notes": credit_notes}
Example #8
0
def test_account(bucket):
    name = "test account"
    description = "This is a test account"

    push_is_running_service()

    try:
        account = Account(name, description, bucket=bucket)

        assert (account.name() == name)
        assert (account.description() == description)
        assert (not account.is_null())

        uid = account.uid()
        assert (uid is not None)

        account2 = Account(uid=uid, bucket=bucket)

        assert (account2.name() == name)
        assert (account2.description() == description)

        assert (account.balance() == Balance())
    except:
        pop_is_running_service()
        raise

    pop_is_running_service()
Example #9
0
def run(args):
    """This function is called to handle requests to perform transactions
       between accounts

       Args:
            args (dict): data for account transfers

        Returns:
            dict: contains status, status message and transaction
            records if any are available
    """

    transaction_records = None

    try:
        debit_account_uid = str(args["debit_account_uid"])
    except:
        debit_account_uid = None

    try:
        credit_account_uid = str(args["credit_account_uid"])
    except:
        credit_account_uid = None

    try:
        authorisation = Authorisation.from_data(args["authorisation"])
    except:
        authorisation = None

    try:
        transaction = Transaction.from_data(args["transaction"])
    except:
        transaction = None

    try:
        is_provisional = bool(args["is_provisional"])
    except:
        is_provisional = None

    if debit_account_uid is None:
        raise TransactionError("You must supply the account UID "
                               "for the debit account")

    if credit_account_uid is None:
        raise TransactionError("You must supply the account UID "
                               "for the credit account")

    if debit_account_uid == credit_account_uid:
        raise TransactionError(
            "You cannot perform a transaction where the debit and credit "
            "accounts are the same!")

    if transaction is None or transaction.is_null():
        raise TransactionError("You must supply a valid transaction to "
                               "perform!")

    if is_provisional is None:
        raise TransactionError("You must say whether or not the "
                               "transaction is provisional using "
                               "is_provisional")

    if authorisation is None:
        raise PermissionError("You must supply a valid authorisation "
                              "to perform transactions between accounts")

    authorisation.assert_once()
    user_guid = authorisation.user_guid()

    # load the account from which the transaction will be performed
    bucket = get_service_account_bucket()
    debit_account = Account(uid=debit_account_uid, bucket=bucket)

    # validate that this account is in a group that can be authorised
    # by the user - This should eventually go as this is all
    # handled by the ACLs
    if not Accounts(user_guid).contains(account=debit_account,
                                        bucket=bucket):
        raise PermissionError(
            "The user with GUID '%s' cannot authorise transactions from "
            "the account '%s' as they do not own this account." %
            (user_guid, str(debit_account)))

    # now load the two accounts involved in the transaction
    credit_account = Account(uid=credit_account_uid, bucket=bucket)

    # we have enough information to perform the transaction
    transaction_records = Ledger.perform(transactions=transaction,
                                         debit_account=debit_account,
                                         credit_account=credit_account,
                                         authorisation=authorisation,
                                         is_provisional=is_provisional,
                                         bucket=bucket)

    return_value = {}

    if transaction_records:
        try:
            transaction_records[0]
        except:
            transaction_records = [transaction_records]

        for i in range(0, len(transaction_records)):
            transaction_records[i] = transaction_records[i].to_data()

        return_value["transaction_records"] = transaction_records

    return return_value
def test_account(bucket):
    name = "test account"
    description = "This is a test account"

    account = Account(name, description, bucket=bucket)

    assert (account.name() == name)
    assert (account.description() == description)
    assert (not account.is_null())

    uid = account.uid()
    assert (uid is not None)

    account2 = Account(uid=uid, bucket=bucket)

    assert (account2.name() == name)
    assert (account2.description() == description)

    assert (account.balance() == 0)