Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Add python-iso4217 integration which eliminates Unions in currency field- #28

Open
wants to merge 2 commits into
base: dev-2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
✨ Add python-iso4217 integration which eliminates Unions in curre…
…ncy field

Combine `PlainAmount` and `AmountWithCurrency` into `Amount` to simplify API
  • Loading branch information
GLEF1X committed Jul 11, 2022
commit ea9d3f7dd3c3a2d685b46034e36b9081bfca760e
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ htmlcov

.benchmarks

glQiwiApi/t.py
glQiwiApi/playground.py.py
*.pem
# Distribution / packaging
.Python
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def default_cache_storage() -> CacheStorage:
return InMemoryCacheStorage(invalidate_strategy=APIResponsesCacheInvalidationStrategy())


__version__ = '2.11'
__version__ = '2.12'

__all__ = (
# clients
Expand Down
4 changes: 2 additions & 2 deletions glQiwiApi/core/event_fetching/class_based/bill.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from glQiwiApi.core.event_fetching.class_based.base import Handler
from glQiwiApi.qiwi.clients.p2p.types import Bill
from glQiwiApi.types.amount import PlainAmount
from glQiwiApi.types.amount import Amount

if TYPE_CHECKING:
from glQiwiApi.qiwi.clients.p2p.client import QiwiP2PClient
Expand All @@ -21,7 +21,7 @@ def bill_id(self) -> str:
return self.event.id

@property
def bill_sum(self) -> PlainAmount:
def bill_sum(self) -> Amount:
return self.event.amount

@property
Expand Down
4 changes: 2 additions & 2 deletions glQiwiApi/core/event_fetching/class_based/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from typing import TYPE_CHECKING, cast

from glQiwiApi.qiwi.clients.wallet.types.transaction import Transaction
from glQiwiApi.types.amount import AmountWithCurrency
from glQiwiApi.types.amount import Amount

from .base import Handler

Expand All @@ -22,5 +22,5 @@ def transaction_id(self) -> int:
return self.event.id

@property
def transaction_sum(self) -> AmountWithCurrency:
def transaction_sum(self) -> Amount:
return self.event.sum
2 changes: 1 addition & 1 deletion glQiwiApi/core/event_fetching/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def __init__(self) -> None:

async def process_event(self, event: Event, *args: Any) -> None:
"""
Feed handlers with event.
Feed handlers withf\\ event.

:param event: any object that will be propagated to handlers
"""
Expand Down
4 changes: 2 additions & 2 deletions glQiwiApi/core/event_fetching/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ async def start_non_blocking_qiwi_api_polling(
on_shutdown: Optional[_EventHandlerType] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
context: Union[Dict[str, Any], Context, None] = None,
) -> asyncio.Task:
) -> asyncio.Task[None]:
if context is None:
context = {}
executor = PollingExecutor(
Expand Down Expand Up @@ -312,7 +312,7 @@ def start_polling(self) -> None:
# allow graceful shutdown
pass

async def start_non_blocking_polling(self) -> asyncio.Task:
async def start_non_blocking_polling(self) -> asyncio.Task[None]:
return asyncio.create_task(self._run_infinite_polling())

async def _run_infinite_polling(self) -> None:
Expand Down
6 changes: 3 additions & 3 deletions glQiwiApi/qiwi/clients/p2p/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from glQiwiApi.qiwi.clients.p2p.methods.refund_bill import RefundBill
from glQiwiApi.qiwi.clients.p2p.methods.reject_p2p_bill import RejectP2PBill
from glQiwiApi.qiwi.clients.p2p.types import Bill, Customer, PairOfP2PKeys, RefundedBill
from glQiwiApi.types.amount import PlainAmount
from glQiwiApi.types.amount import Amount
from glQiwiApi.utils.compat import remove_suffix
from glQiwiApi.utils.deprecated import warn_deprecated
from glQiwiApi.utils.validators import String
Expand Down Expand Up @@ -105,7 +105,7 @@ async def get_bill_status(self, bill_id: str) -> str:
:param bill_id:
:return: status of bill
"""
return (await self.get_bill_by_id(bill_id)).status.value
return (await self.get_bill_by_id(bill_id)).status.amount

async def create_p2p_bill(
self,
Expand Down Expand Up @@ -175,7 +175,7 @@ async def refund_bill(
self,
bill_id: Union[str, int],
refund_id: Union[str, int],
json_bill_data: Union[PlainAmount, Dict[str, Union[str, int]]],
json_bill_data: Union[Amount, Dict[str, Union[str, int]]],
) -> RefundedBill:
"""
The method allows you to make a refund on a paid invoice.
Expand Down
6 changes: 3 additions & 3 deletions glQiwiApi/qiwi/clients/p2p/methods/refund_bill.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from glQiwiApi.core.abc.api_method import Request
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.p2p.types import RefundedBill
from glQiwiApi.types.amount import PlainAmount
from glQiwiApi.types.amount import Amount


class RefundBill(QiwiAPIMethod[RefundedBill]):
Expand All @@ -15,11 +15,11 @@ class RefundBill(QiwiAPIMethod[RefundedBill]):
bill_id: str = Field(..., path_runtime_value=True)
refund_id: str = Field(..., path_runtime_value=True)

json_bill_data: Union[PlainAmount, Dict[str, Union[str, int]]]
json_bill_data: Union[Amount, Dict[str, Union[str, int]]]

def build_request(self, **url_format_kw: Any) -> 'Request':
json_payload = self.json_bill_data
if isinstance(self.json_bill_data, PlainAmount):
if isinstance(self.json_bill_data, Amount):
json_payload = self.json_bill_data.json(encoder=self.Config.json_dumps) # type: ignore

return Request(
Expand Down
10 changes: 5 additions & 5 deletions glQiwiApi/qiwi/clients/p2p/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from pydantic import BaseConfig, Extra, Field

from glQiwiApi.types.amount import HashablePlainAmount, PlainAmount
from glQiwiApi.types.amount import Amount, HashableAmount
from glQiwiApi.types.base import HashableBase
from glQiwiApi.types.exceptions import WebhookSignatureUnverifiedError

Expand All @@ -20,7 +20,7 @@ class Customer(HashableBase):


class BillStatus(HashableBase):
value: str
amount: str
changed_datetime: Optional[datetime] = Field(None, alias='changedDateTime')


Expand All @@ -39,7 +39,7 @@ class BillError(HashableBase):


class Bill(HashableBase):
amount: HashablePlainAmount
amount: HashableAmount
status: BillStatus
site_id: str = Field(..., alias='siteId')
id: str = Field(..., alias='billId')
Expand All @@ -61,7 +61,7 @@ def invoice_uid(self) -> str:
class RefundedBill(HashableBase):
"""object: RefundedBill"""

amount: PlainAmount
amount: Amount
datetime: datetime
refund_id: str = Field(..., alias='refundId')
status: str
Expand All @@ -85,7 +85,7 @@ def verify_signature(self, sha256_signature: str, secret_p2p_key: str) -> None:
webhook_key = base64.b64decode(bytes(secret_p2p_key, 'utf-8'))
bill = self.bill

invoice_params = f'{bill.amount.currency}|{bill.amount.value}|{bill.id}|{bill.site_id}|{bill.status.value}'
invoice_params = f'{bill.amount.currency}|{bill.amount.amount}|{bill.id}|{bill.site_id}|{bill.status.amount}'
generated_signature = hmac.new(
webhook_key, invoice_params.encode('utf-8'), hashlib.sha256
).hexdigest()
Expand Down
6 changes: 3 additions & 3 deletions glQiwiApi/qiwi/clients/wallet/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
from glQiwiApi.qiwi.clients.wallet.methods.webhook.send_test_notification import (
SendTestWebhookNotification,
)
from glQiwiApi.types.amount import AmountWithCurrency
from glQiwiApi.types.amount import Amount
from glQiwiApi.types.arbitrary import File
from glQiwiApi.utils.validators import PhoneNumber, String

Expand Down Expand Up @@ -381,7 +381,7 @@ async def get_list_of_balances(self) -> List[Balance]:
GetBalances(), phone_number=self.phone_number_without_plus_sign
)

async def get_balance(self, *, account_number: int = 1) -> AmountWithCurrency:
async def get_balance(self, *, account_number: int = 1) -> Amount:
resp: List[Balance] = await self._request_service.execute_api_method(
GetBalances(),
phone_number=self._phone_number,
Expand Down Expand Up @@ -506,7 +506,7 @@ async def get_cross_rates(self) -> List[CrossRate]:

async def payment_by_payment_details(
self,
payment_sum: AmountWithCurrency,
payment_sum: Amount,
payment_method: PaymentMethod,
fields: PaymentDetails,
payment_id: Optional[str] = None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class DetectMobileNumber(QiwiAPIMethod[MobileOperator]):
@classmethod
def parse_http_response(cls, response: HTTPResponse) -> ReturningType:
mobile_operator: MobileOperator = super().parse_http_response(response)
if mobile_operator.code.value == '2' or mobile_operator.code.name == 'ERROR':
if mobile_operator.code.amount == '2' or mobile_operator.code.name == 'ERROR':
raise MobileOperatorCannotBeDeterminedError(
response, custom_message=mobile_operator.message
)
Expand Down
4 changes: 2 additions & 2 deletions glQiwiApi/qiwi/clients/wallet/methods/payment_by_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from glQiwiApi.core.abc.api_method import RuntimeValue
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.wallet.types import PaymentDetails, PaymentInfo, PaymentMethod
from glQiwiApi.types.amount import AmountWithCurrency
from glQiwiApi.types.amount import Amount


class MakePaymentByDetails(QiwiAPIMethod[PaymentInfo]):
Expand All @@ -20,7 +20,7 @@ class MakePaymentByDetails(QiwiAPIMethod[PaymentInfo]):
'fields': RuntimeValue(),
}

payment_sum: AmountWithCurrency = Field(..., scheme_path='sum')
payment_sum: Amount = Field(..., scheme_path='sum')
payment_method: PaymentMethod = Field(..., scheme_path='paymentMethod')
details: PaymentDetails = Field(..., scheme_path='fields')
payment_id: Optional[str] = Field(None, scheme_path='id')
15 changes: 4 additions & 11 deletions glQiwiApi/qiwi/clients/wallet/types/account_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@
from datetime import datetime
from typing import Any, Dict, List, Optional, Union

from pydantic import Field, validator
from pydantic import Field

from glQiwiApi.types.amount import AmountWithCurrency, CurrencyModel
from glQiwiApi.types.amount import Amount, Currency
from glQiwiApi.types.base import Base
from glQiwiApi.utils.currency_util import Currency


class PassInfo(Base):
Expand Down Expand Up @@ -48,7 +47,7 @@ class AuthInfo(Base):
class SmsNotification(Base):
"""object: SmsNotification"""

price: AmountWithCurrency
price: Amount
enabled: bool
active: bool
end_date: Optional[datetime] = Field(None, alias='endDate')
Expand Down Expand Up @@ -95,7 +94,7 @@ class ContractInfo(Base):
class UserInfo(Base):
"""object: UserInfo"""

default_pay_currency: CurrencyModel = Field(..., alias='defaultPayCurrency')
default_pay_currency: Currency = Field(..., alias='defaultPayCurrency')
default_pay_source: Optional[int] = Field(None, alias='defaultPaySource')
default_pay_account_alias: Optional[str] = Field(None, alias='defaultPayAccountAlias')
email: Optional[str] = None
Expand All @@ -105,12 +104,6 @@ class UserInfo(Base):
phone_hash: str = Field(alias='phoneHash')
promo_enabled: Optional[bool] = Field(None, alias='promoEnabled')

@validator('default_pay_currency', pre=True)
def humanize_pay_currency(cls, v): # type: ignore
if not isinstance(v, int):
return v
return Currency.get(str(v))


class UserProfile(Base):
auth_info: Optional[AuthInfo] = Field(None, alias='authInfo')
Expand Down
19 changes: 6 additions & 13 deletions glQiwiApi/qiwi/clients/wallet/types/balance.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
from typing import Any, Dict, Optional, Union
from typing import Any, Dict, Optional

from pydantic import Field, validator
from pydantic import Field

from glQiwiApi.types.amount import AmountWithCurrency, CurrencyModel
from glQiwiApi.types.amount import Amount, Currency
from glQiwiApi.types.base import HashableBase
from glQiwiApi.utils.currency_util import Currency


class AvailableBalance(HashableBase):
alias: str
currency: Union[str, CurrencyModel]
currency: Currency


class Balance(HashableBase):
Expand All @@ -20,13 +19,7 @@ class Balance(HashableBase):
fs_alias: str = Field(alias='fsAlias')
bank_alias: str = Field(alias='bankAlias')
has_balance: bool = Field(alias='hasBalance')
balance: Optional[AmountWithCurrency] = None
currency: CurrencyModel
balance: Optional[Amount] = None
currency: Currency
account_type: Optional[Dict[str, Any]] = Field(None, alias='type')
is_default_account: bool = Field(alias='defaultAccount')

@validator('currency', pre=True)
def humanize_pay_currency(cls, v): # type: ignore
if not isinstance(v, int):
return v
return Currency.get(str(v))
8 changes: 4 additions & 4 deletions glQiwiApi/qiwi/clients/wallet/types/commission.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from pydantic import Field

from glQiwiApi.types.amount import AmountWithCurrency
from glQiwiApi.types.amount import Amount
from glQiwiApi.types.base import Base


class Commission(Base):
provider_id: int = Field(alias='providerId')
withdraw_sum: AmountWithCurrency = Field(alias='withdrawSum')
enrollment_sum: AmountWithCurrency = Field(alias='enrollmentSum')
qiwi_commission: AmountWithCurrency = Field(alias='qwCommission')
withdraw_sum: Amount = Field(alias='withdrawSum')
enrollment_sum: Amount = Field(alias='enrollmentSum')
qiwi_commission: Amount = Field(alias='qwCommission')
withdraw_to_enrollment_rate: int = Field(alias='withdrawToEnrollmentRate')
13 changes: 3 additions & 10 deletions glQiwiApi/qiwi/clients/wallet/types/limit.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from datetime import datetime
from typing import Union

from pydantic import Field, validator
from pydantic import Field

from glQiwiApi.types.amount import CurrencyModel
from glQiwiApi.types.amount import Currency
from glQiwiApi.types.base import Base
from glQiwiApi.utils.currency_util import Currency


class Interval(Base):
Expand All @@ -18,18 +17,12 @@ class Interval(Base):
class Limit(Base):
"""object: Limit"""

currency: CurrencyModel
currency: Currency
rest: Union[float, int]
max_limit: Union[float, int] = Field(alias='max')
spent: Union[float, int]
interval: Interval
limit_type: str = Field(alias='type')

@validator('currency', pre=True)
def currency_validate(cls, v): # type: ignore
if not isinstance(v, str):
raise ValueError()
return Currency.get(v)


__all__ = ['Limit']
2 changes: 1 addition & 1 deletion glQiwiApi/qiwi/clients/wallet/types/mobile_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


class Code(Base):
value: str
amount: str
name: str = Field(..., alias='_name')


Expand Down
Loading