def decode_many(cls: Type[T], entity: Entity, data: Any) -> List[T]:

        if not isinstance(data, list):
            raise ApiError('Unexpected non-list data returned')

        if len(data) < 1:
            raise ApiError('Unexpected empty response data')

        def decode(data: dict) -> T:
            if not isinstance(data, dict):
                raise ApiError('Unexpected non-dict data returned')
            try:
                transaction = cls(
                    entity=entity,
                    transaction_id=data['transaction_id'],
                    transaction_time=AmatinoTime.decode(
                        data['transaction_time']),
                    version_time=AmatinoTime.decode(data['version_time']),
                    description=data['description'],
                    entries=cls._decode_entries(data['entries']),
                    global_unit_id=data['global_unit_denomination'],
                    custom_unit_id=data['custom_unit_denomination'])
            except KeyError as error:
                raise MissingKey(error.args[0])

            return transaction

        transactions = [decode(t) for t in data]

        return transactions
    def _decode_many(cls: Type[T], entity: Entity,
                     data: List[dict]) -> List[T]:

        if not isinstance(data, list):
            raise ApiError('Unexpected non-list data returned')

        if len(data) < 1:
            raise ApiError('Unexpected empty response data')

        def decode(data: dict) -> T:
            if not isinstance(data, dict):
                raise ApiError('Unexpected non-dict data returned')
            try:
                account = cls(entity=entity,
                              account_id=data['account_id'],
                              name=data['name'],
                              am_type=AMType(data['type']),
                              description=data['description'],
                              parent_account_id=data['parent_account_id'],
                              global_unit_id=data['global_unit_id'],
                              custom_unit_id=data['custom_unit_id'],
                              counterparty_id=data['counterparty_entity_id'],
                              color=Color.from_hex_string(data['colour']))
            except KeyError as error:
                raise MissingKey(error.args[0])

            return account

        accounts = [decode(a) for a in data]

        return accounts
Ejemplo n.º 3
0
    def _decode(cls: Type[T], entity: Entity, data: Any) -> T:

        if not isinstance(data, list):
            raise UnexpectedResponseType(data, list)

        if len(data) < 1:
            raise ApiError('Response unexpectedly empty')

        tx_list_data = data[0]

        try:

            if tx_list_data['versions'] is None:
                tx_list_data['versions'] = list()

            tx_list = cls(
                entity=entity,
                transaction_id=tx_list_data['transaction_id'],
                versions=Transaction.decode_many(
                    entity,
                    tx_list_data['versions']
                )
            )

        except KeyError as error:
            raise MissingKey(error.args[0])

        return tx_list
    def update(self: T,
               name: Optional[str] = None,
               am_type: Optional[AMType] = None,
               parent: Optional[T] = None,
               description: Optional[str] = None,
               denomination: Optional[Denomination] = None,
               counterparty: Optional[Entity] = None,
               color: Optional[Color] = None) -> 'Account':
        """
        Update this Account with new metadata.
        """

        arguments = Account.UpdateArguments(self, name, am_type, parent,
                                            description, denomination,
                                            counterparty, color)

        data = DataPackage.from_object(arguments)
        parameters = UrlParameters(entity_id=self.entity.id_)

        request = ApiRequest(path=Account._PATH,
                             method=HTTPMethod.PUT,
                             credentials=self.entity.session,
                             data=data,
                             url_parameters=parameters)

        account = Account._decode(self.entity, request.response_data)

        if account.id_ != self.id_:
            raise ApiError('Returned Account ID does not match request ID')

        return account
    def _decode_many(cls: Type[T], data: Any) -> List[T]:
        """Return a list of Global Units decoded from raw API response data"""

        if not isinstance(data, list):
            raise ApiError('Unexpected non-list API data response')

        def decode(unit_data: Any) -> T:
            if not isinstance(unit_data, dict):
                raise UnexpectedResponseType(unit_data, dict)

            try:
                unit = cls(code=unit_data['code'],
                           id_=unit_data['global_unit_id'],
                           name=unit_data['name'],
                           priority=unit_data['priority'],
                           description=unit_data['description'],
                           exponent=unit_data['exponent'])
            except KeyError as error:
                message = 'Expected key "{key}" missing from response data'
                message.format(key=error.args[0])
                raise ApiError(message)

            return unit

        units = [decode(u) for u in data]

        return units
    def update(self: T,
               time: Optional[datetime] = None,
               entries: Optional[List[Entry]] = None,
               denomination: Optional[Denomination] = None,
               description: Optional[str] = None) -> T:
        """Replace existing transaction data with supplied data."""

        arguments = Transaction.UpdateArguments(self, time, entries,
                                                denomination, description)

        data = DataPackage.from_object(arguments)
        parameters = UrlParameters(entity_id=self.entity.id_)

        request = ApiRequest(path=Transaction._PATH,
                             method=HTTPMethod.PUT,
                             credentials=self.entity.session,
                             data=data,
                             url_parameters=parameters)

        transaction = Transaction._decode(self.entity, request.response_data)

        if transaction.id_ != self.id_:
            raise ApiError('Mismatched response Trasaction ID - Fatal')

        return transaction
    def _decode(cls: Type[T], response_data: Any):

        if not isinstance(response_data, dict):
            raise ApiError('Unexpected non-dict type when decoding Session')

        try:
            api_key = response_data['api_key']
            session_id = response_data['session_id']
            user_id = response_data['user_id']
        except KeyError as error:
            message = 'Expected key "{key}" missing from response data'
            message.format(key=error.args[0])
            raise ApiError(message)

        entity = cls(user_id, session_id, api_key)

        return entity
        def decode(data: dict) -> T:
            if not isinstance(data, dict):
                raise ApiError('Unexpected non-dict data returned')
            try:
                unit = cls(
                    entity=entity,
                    id_=data['custom_unit_id'],
                    code=data['code'],
                    name=data['name'],
                    priority=data['priority'],
                    description=data['description'],
                    exponent=data['exponent']
                )
            except KeyError as error:
                message = 'Expected key "{key}" missing from response data'
                message.format(key=error.args[0])
                raise ApiError(message)

            return unit
        def decode(obj) -> Entry:
            if not isinstance(obj, dict):
                raise ApiError('Unexpected API object type ' + str(type(obj)))

            try:
                entry = Entry(side=Side(obj['side']),
                              amount=AmatinoAmount.decode(obj['amount']),
                              account_id=obj['account_id'],
                              description=obj['description'])
            except KeyError as error:
                raise MissingKey(error.args[0])

            return entry
    def _decodeMany(
        cls: Type[T],
        entity: Entity,
        data: Any
    ) -> List[T]:

        assert isinstance(entity, Entity)

        if not isinstance(data, list):
            raise ApiError('Unexpected non-list data returned')

        if len(data) < 1:
            raise ApiError('Unexpected empty response data')

        def decode(data: dict) -> T:
            if not isinstance(data, dict):
                raise ApiError('Unexpected non-dict data returned')
            try:
                unit = cls(
                    entity=entity,
                    id_=data['custom_unit_id'],
                    code=data['code'],
                    name=data['name'],
                    priority=data['priority'],
                    description=data['description'],
                    exponent=data['exponent']
                )
            except KeyError as error:
                message = 'Expected key "{key}" missing from response data'
                message.format(key=error.args[0])
                raise ApiError(message)

            return unit

        units = [decode(u) for u in data]

        return units
    def decode(cls: Type[T], session: Session, data: Any) -> T:

        if not isinstance(data, dict):
            raise ApiError('Unexpected data type returned: ' + str(type(data)))

        try:
            user_list = cls(page=data['page'],
                            number_of_pages=data['number_of_pages'],
                            generated_time=AmatinoTime.decode(
                                data['generated_time']),
                            state=State(data['state']),
                            users=User.decode_many(session, data['users']),
                            session=session)
        except KeyError as error:
            raise MissingKey(error.args[0])

        return user_list
        def decode(unit_data: Any) -> T:
            if not isinstance(unit_data, dict):
                raise UnexpectedResponseType(unit_data, dict)

            try:
                unit = cls(code=unit_data['code'],
                           id_=unit_data['global_unit_id'],
                           name=unit_data['name'],
                           priority=unit_data['priority'],
                           description=unit_data['description'],
                           exponent=unit_data['exponent'])
            except KeyError as error:
                message = 'Expected key "{key}" missing from response data'
                message.format(key=error.args[0])
                raise ApiError(message)

            return unit
        def decode(data: dict) -> T:
            if not isinstance(data, dict):
                raise ApiError('Unexpected non-dict data returned')
            try:
                account = cls(entity=entity,
                              account_id=data['account_id'],
                              name=data['name'],
                              am_type=AMType(data['type']),
                              description=data['description'],
                              parent_account_id=data['parent_account_id'],
                              global_unit_id=data['global_unit_id'],
                              custom_unit_id=data['custom_unit_id'],
                              counterparty_id=data['counterparty_entity_id'],
                              color=Color.from_hex_string(data['colour']))
            except KeyError as error:
                raise MissingKey(error.args[0])

            return account
        def decode(data: dict) -> T:
            if not isinstance(data, dict):
                raise ApiError('Unexpected non-dict data returned')
            try:
                transaction = cls(
                    entity=entity,
                    transaction_id=data['transaction_id'],
                    transaction_time=AmatinoTime.decode(
                        data['transaction_time']),
                    version_time=AmatinoTime.decode(data['version_time']),
                    description=data['description'],
                    entries=cls._decode_entries(data['entries']),
                    global_unit_id=data['global_unit_denomination'],
                    custom_unit_id=data['custom_unit_denomination'])
            except KeyError as error:
                raise MissingKey(error.args[0])

            return transaction
    def _decode_entries(cls: Type[T], data: Any) -> List[Entry]:
        """Return Entries decoded from API response data"""
        if not isinstance(data, list):
            raise ApiError('Unexpected API response type ' + str(type(data)))

        def decode(obj) -> Entry:
            if not isinstance(obj, dict):
                raise ApiError('Unexpected API object type ' + str(type(obj)))

            try:
                entry = Entry(side=Side(obj['side']),
                              amount=AmatinoAmount.decode(obj['amount']),
                              account_id=obj['account_id'],
                              description=obj['description'])
            except KeyError as error:
                raise MissingKey(error.args[0])

            return entry

        return [decode(e) for e in data]