|
| 1 | +""" |
| 2 | +Currency definitions that are based on the [ISO4217](https://en.wikipedia.org/wiki/ISO_4217). |
| 3 | +""" |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler |
| 9 | +from pydantic_core import PydanticCustomError, core_schema |
| 10 | + |
| 11 | +try: |
| 12 | + import pycountry |
| 13 | +except ModuleNotFoundError: # pragma: no cover |
| 14 | + raise RuntimeError( |
| 15 | + 'The `currency_code` module requires "pycountry" to be installed. You can install it with "pip install ' |
| 16 | + 'pycountry".' |
| 17 | + ) |
| 18 | + |
| 19 | +# List of codes that should not be usually used within regular transactions |
| 20 | +_CODES_FOR_BONDS_METAL_TESTING = { |
| 21 | + 'XTS', # testing |
| 22 | + 'XAU', # gold |
| 23 | + 'XAG', # silver |
| 24 | + 'XPD', # palladium |
| 25 | + 'XPT', # platinum |
| 26 | + 'XBA', # Bond Markets Unit European Composite Unit (EURCO) |
| 27 | + 'XBB', # Bond Markets Unit European Monetary Unit (E.M.U.-6) |
| 28 | + 'XBC', # Bond Markets Unit European Unit of Account 9 (E.U.A.-9) |
| 29 | + 'XBD', # Bond Markets Unit European Unit of Account 17 (E.U.A.-17) |
| 30 | + 'XXX', # no currency |
| 31 | + 'XDR', # SDR (Special Drawing Right) |
| 32 | +} |
| 33 | + |
| 34 | + |
| 35 | +class ISO4217(str): |
| 36 | + """ISO4217 parses Currency in the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) format. |
| 37 | +
|
| 38 | + ```py |
| 39 | + from pydantic import BaseModel |
| 40 | +
|
| 41 | + from pydantic_extra_types.currency_code import ISO4217 |
| 42 | +
|
| 43 | + class Currency(BaseModel): |
| 44 | + alpha_3: ISO4217 |
| 45 | +
|
| 46 | + currency = Currency(alpha_3='AED') |
| 47 | + print(currency) |
| 48 | + # > alpha_3='AED' |
| 49 | + ``` |
| 50 | + """ |
| 51 | + |
| 52 | + allowed_countries_list = [country.alpha_3 for country in pycountry.currencies] |
| 53 | + allowed_currencies = set(allowed_countries_list) |
| 54 | + |
| 55 | + @classmethod |
| 56 | + def _validate(cls, currency_code: str, _: core_schema.ValidationInfo) -> str: |
| 57 | + """ |
| 58 | + Validate a ISO 4217 language code from the provided str value. |
| 59 | +
|
| 60 | + Args: |
| 61 | + currency_code: The str value to be validated. |
| 62 | + _: The Pydantic ValidationInfo. |
| 63 | +
|
| 64 | + Returns: |
| 65 | + The validated ISO 4217 currency code. |
| 66 | +
|
| 67 | + Raises: |
| 68 | + PydanticCustomError: If the ISO 4217 currency code is not valid. |
| 69 | + """ |
| 70 | + if currency_code not in cls.allowed_currencies: |
| 71 | + raise PydanticCustomError( |
| 72 | + 'ISO4217', 'Invalid ISO 4217 currency code. See https://en.wikipedia.org/wiki/ISO_4217' |
| 73 | + ) |
| 74 | + return currency_code |
| 75 | + |
| 76 | + @classmethod |
| 77 | + def __get_pydantic_core_schema__(cls, _: type[Any], __: GetCoreSchemaHandler) -> core_schema.CoreSchema: |
| 78 | + return core_schema.with_info_after_validator_function( |
| 79 | + cls._validate, |
| 80 | + core_schema.str_schema(min_length=3, max_length=3), |
| 81 | + ) |
| 82 | + |
| 83 | + @classmethod |
| 84 | + def __get_pydantic_json_schema__( |
| 85 | + cls, schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler |
| 86 | + ) -> dict[str, Any]: |
| 87 | + json_schema = handler(schema) |
| 88 | + json_schema.update({'enum': cls.allowed_countries_list}) |
| 89 | + return json_schema |
| 90 | + |
| 91 | + |
| 92 | +class Currency(str): |
| 93 | + """Currency parses currency subset of the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) format. |
| 94 | + It excludes bonds testing codes and precious metals. |
| 95 | + ```py |
| 96 | + from pydantic import BaseModel |
| 97 | +
|
| 98 | + from pydantic_extra_types.currency_code import Currency |
| 99 | +
|
| 100 | + class currency(BaseModel): |
| 101 | + alpha_3: Currency |
| 102 | +
|
| 103 | + cur = currency(alpha_3='AED') |
| 104 | + print(cur) |
| 105 | + # > alpha_3='AED' |
| 106 | + ``` |
| 107 | + """ |
| 108 | + |
| 109 | + allowed_countries_list = list( |
| 110 | + filter(lambda x: x not in _CODES_FOR_BONDS_METAL_TESTING, ISO4217.allowed_countries_list) |
| 111 | + ) |
| 112 | + allowed_currencies = set(allowed_countries_list) |
| 113 | + |
| 114 | + @classmethod |
| 115 | + def _validate(cls, currency_symbol: str, _: core_schema.ValidationInfo) -> str: |
| 116 | + """ |
| 117 | + Validate a subset of the [ISO4217](https://en.wikipedia.org/wiki/ISO_4217) format. |
| 118 | + It excludes bonds testing codes and precious metals. |
| 119 | +
|
| 120 | + Args: |
| 121 | + currency_symbol: The str value to be validated. |
| 122 | + _: The Pydantic ValidationInfo. |
| 123 | +
|
| 124 | + Returns: |
| 125 | + The validated ISO 4217 currency code. |
| 126 | +
|
| 127 | + Raises: |
| 128 | + PydanticCustomError: If the ISO 4217 currency code is not valid or is bond, precious metal or testing code. |
| 129 | + """ |
| 130 | + if currency_symbol not in cls.allowed_currencies: |
| 131 | + raise PydanticCustomError( |
| 132 | + 'InvalidCurrency', |
| 133 | + 'Invalid currency code.' |
| 134 | + ' See https://en.wikipedia.org/wiki/ISO_4217. ' |
| 135 | + 'Bonds, testing and precious metals codes are not allowed.', |
| 136 | + ) |
| 137 | + return currency_symbol |
| 138 | + |
| 139 | + @classmethod |
| 140 | + def __get_pydantic_core_schema__(cls, _: type[Any], __: GetCoreSchemaHandler) -> core_schema.CoreSchema: |
| 141 | + """ |
| 142 | + Return a Pydantic CoreSchema with the currency subset of the |
| 143 | + [ISO4217](https://en.wikipedia.org/wiki/ISO_4217) format. |
| 144 | + It excludes bonds testing codes and precious metals. |
| 145 | +
|
| 146 | + Args: |
| 147 | + _: The source type. |
| 148 | + __: The handler to get the CoreSchema. |
| 149 | +
|
| 150 | + Returns: |
| 151 | + A Pydantic CoreSchema with the subset of the currency subset of the |
| 152 | + [ISO4217](https://en.wikipedia.org/wiki/ISO_4217) format. |
| 153 | + It excludes bonds testing codes and precious metals. |
| 154 | + """ |
| 155 | + return core_schema.with_info_after_validator_function( |
| 156 | + cls._validate, |
| 157 | + core_schema.str_schema(min_length=3, max_length=3), |
| 158 | + ) |
| 159 | + |
| 160 | + @classmethod |
| 161 | + def __get_pydantic_json_schema__( |
| 162 | + cls, schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler |
| 163 | + ) -> dict[str, Any]: |
| 164 | + """ |
| 165 | + Return a Pydantic JSON Schema with subset of the [ISO4217](https://en.wikipedia.org/wiki/ISO_4217) format. |
| 166 | + Excluding bonds testing codes and precious metals. |
| 167 | +
|
| 168 | + Args: |
| 169 | + schema: The Pydantic CoreSchema. |
| 170 | + handler: The handler to get the JSON Schema. |
| 171 | +
|
| 172 | + Returns: |
| 173 | + A Pydantic JSON Schema with the subset of the ISO4217 currency code validation. without bonds testing codes |
| 174 | + and precious metals. |
| 175 | +
|
| 176 | + """ |
| 177 | + json_schema = handler(schema) |
| 178 | + json_schema.update({'enum': cls.allowed_countries_list}) |
| 179 | + return json_schema |
0 commit comments